ETH Price: $2,303.26 (+1.84%)

Transaction Decoder

Block:
17444535 at Jun-09-2023 06:46:47 PM +UTC
Transaction Fee:
0.00256939716414858 ETH $5.92
Gas Used:
136,095 Gas / 18.879438364 Gwei

Emitted Events:

171 Bueno721Drop.PaymentReleased( to=[Sender] 0x5b0baf4b7189a265ef7d2c93e09614c1feba6dc7, amount=1705155000000000000 )
172 GnosisSafeProxy.0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d( 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d, 0x000000000000000000000000b85172a5957b6b47bf2c18dee4b8d0b2aa7273a1, 000000000000000000000000000000000000000000000000013ed69a1d5e1000 )
173 Bueno721Drop.PaymentReleased( to=GnosisSafeProxy, amount=89745000000000000 )

Account State Difference:

  Address   Before After State Difference Code
0x5b0BaF4b...1feBA6Dc7
(GEN2LOCS: Deployer)
0.036225481152721264 Eth
Nonce: 17
1.738811083988572684 Eth
Nonce: 18
1.70258560283585142
0x985AFcA0...E4F237A1B 992.422905102331311213 Eth992.512650102331311213 Eth0.089745
0xb85172A5...2aa7273A1 1.7949 Eth0 Eth1.7949
(eth-builder)
26.862397400012672935 Eth26.862411009512672935 Eth0.0000136095

Execution Trace

Bueno721Drop.CALL( )
  • Bueno721Drop.DELEGATECALL( )
    • ETH 1.705155 GEN2LOCS: Deployer.CALL( )
    • ETH 0.089745 GnosisSafeProxy.CALL( )
      • ETH 0.089745 GnosisSafe.DELEGATECALL( )
        File 1 of 4: Bueno721Drop
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/ContextUpgradeable.sol";
        import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            function __Ownable_init() internal onlyInitializing {
                __Ownable_init_unchained();
            }
            function __Ownable_init_unchained() internal onlyInitializing {
                _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);
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[49] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (finance/PaymentSplitter.sol)
        pragma solidity ^0.8.0;
        import "../token/ERC20/utils/SafeERC20Upgradeable.sol";
        import "../utils/AddressUpgradeable.sol";
        import "../utils/ContextUpgradeable.sol";
        import "../proxy/utils/Initializable.sol";
        /**
         * @title PaymentSplitter
         * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
         * that the Ether will be split in this way, since it is handled transparently by the contract.
         *
         * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
         * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
         * an amount proportional to the percentage of total shares they were assigned. The distribution of shares is set at the
         * time of contract deployment and can't be updated thereafter.
         *
         * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
         * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
         * function.
         *
         * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
         * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
         * to run tests before sending real value to this contract.
         */
        contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
            event PayeeAdded(address account, uint256 shares);
            event PaymentReleased(address to, uint256 amount);
            event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount);
            event PaymentReceived(address from, uint256 amount);
            uint256 private _totalShares;
            uint256 private _totalReleased;
            mapping(address => uint256) private _shares;
            mapping(address => uint256) private _released;
            address[] private _payees;
            mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased;
            mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released;
            /**
             * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
             * the matching position in the `shares` array.
             *
             * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
             * duplicates in `payees`.
             */
            function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal onlyInitializing {
                __PaymentSplitter_init_unchained(payees, shares_);
            }
            function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal onlyInitializing {
                require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
                require(payees.length > 0, "PaymentSplitter: no payees");
                for (uint256 i = 0; i < payees.length; i++) {
                    _addPayee(payees[i], shares_[i]);
                }
            }
            /**
             * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
             * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
             * reliability of the events, and not the actual splitting of Ether.
             *
             * To learn more about this see the Solidity documentation for
             * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
             * functions].
             */
            receive() external payable virtual {
                emit PaymentReceived(_msgSender(), msg.value);
            }
            /**
             * @dev Getter for the total shares held by payees.
             */
            function totalShares() public view returns (uint256) {
                return _totalShares;
            }
            /**
             * @dev Getter for the total amount of Ether already released.
             */
            function totalReleased() public view returns (uint256) {
                return _totalReleased;
            }
            /**
             * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
             * contract.
             */
            function totalReleased(IERC20Upgradeable token) public view returns (uint256) {
                return _erc20TotalReleased[token];
            }
            /**
             * @dev Getter for the amount of shares held by an account.
             */
            function shares(address account) public view returns (uint256) {
                return _shares[account];
            }
            /**
             * @dev Getter for the amount of Ether already released to a payee.
             */
            function released(address account) public view returns (uint256) {
                return _released[account];
            }
            /**
             * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
             * IERC20 contract.
             */
            function released(IERC20Upgradeable token, address account) public view returns (uint256) {
                return _erc20Released[token][account];
            }
            /**
             * @dev Getter for the address of the payee number `index`.
             */
            function payee(uint256 index) public view returns (address) {
                return _payees[index];
            }
            /**
             * @dev Getter for the amount of payee's releasable Ether.
             */
            function releasable(address account) public view returns (uint256) {
                uint256 totalReceived = address(this).balance + totalReleased();
                return _pendingPayment(account, totalReceived, released(account));
            }
            /**
             * @dev Getter for the amount of payee's releasable `token` tokens. `token` should be the address of an
             * IERC20 contract.
             */
            function releasable(IERC20Upgradeable token, address account) public view returns (uint256) {
                uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
                return _pendingPayment(account, totalReceived, released(token, account));
            }
            /**
             * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
             * total shares and their previous withdrawals.
             */
            function release(address payable account) public virtual {
                require(_shares[account] > 0, "PaymentSplitter: account has no shares");
                uint256 payment = releasable(account);
                require(payment != 0, "PaymentSplitter: account is not due payment");
                // _totalReleased is the sum of all values in _released.
                // If "_totalReleased += payment" does not overflow, then "_released[account] += payment" cannot overflow.
                _totalReleased += payment;
                unchecked {
                    _released[account] += payment;
                }
                AddressUpgradeable.sendValue(account, payment);
                emit PaymentReleased(account, payment);
            }
            /**
             * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
             * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
             * contract.
             */
            function release(IERC20Upgradeable token, address account) public virtual {
                require(_shares[account] > 0, "PaymentSplitter: account has no shares");
                uint256 payment = releasable(token, account);
                require(payment != 0, "PaymentSplitter: account is not due payment");
                // _erc20TotalReleased[token] is the sum of all values in _erc20Released[token].
                // If "_erc20TotalReleased[token] += payment" does not overflow, then "_erc20Released[token][account] += payment"
                // cannot overflow.
                _erc20TotalReleased[token] += payment;
                unchecked {
                    _erc20Released[token][account] += payment;
                }
                SafeERC20Upgradeable.safeTransfer(token, account, payment);
                emit ERC20PaymentReleased(token, account, payment);
            }
            /**
             * @dev internal logic for computing the pending payment of an `account` given the token historical balances and
             * already released amounts.
             */
            function _pendingPayment(
                address account,
                uint256 totalReceived,
                uint256 alreadyReleased
            ) private view returns (uint256) {
                return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
            }
            /**
             * @dev Add a new payee to the contract.
             * @param account The address of the payee to add.
             * @param shares_ The number of shares owned by the payee.
             */
            function _addPayee(address account, uint256 shares_) private {
                require(account != address(0), "PaymentSplitter: account is the zero address");
                require(shares_ > 0, "PaymentSplitter: shares are 0");
                require(_shares[account] == 0, "PaymentSplitter: account already has shares");
                _payees.push(account);
                _shares[account] = shares_;
                _totalShares = _totalShares + shares_;
                emit PayeeAdded(account, shares_);
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[43] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
        pragma solidity ^0.8.0;
        import "../utils/introspection/IERC165Upgradeable.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 IERC2981Upgradeable is IERC165Upgradeable {
            /**
             * @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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/AddressUpgradeable.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * contract MyToken is ERC20Upgradeable {
         *     function initialize() initializer public {
         *         __ERC20_init("MyToken", "MTK");
         *     }
         * }
         * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
         *     function initializeV2() reinitializer(2) public {
         *         __ERC20Permit_init("MyToken");
         *     }
         * }
         * ```
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         *
         * [CAUTION]
         * ====
         * Avoid leaving a contract uninitialized.
         *
         * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
         * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
         * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * /// @custom:oz-upgrades-unsafe-allow constructor
         * constructor() {
         *     _disableInitializers();
         * }
         * ```
         * ====
         */
        abstract contract Initializable {
            /**
             * @dev Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts.
             *
             * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
             * constructor.
             *
             * Emits an {Initialized} event.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * A reinitializer may be used after the original initialization step. This is essential to configure modules that
             * are added through upgrades and that require initialization.
             *
             * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
             * cannot be nested. If one is invoked in the context of another, execution will revert.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             *
             * WARNING: setting the version to 255 will prevent any future reinitialization.
             *
             * Emits an {Initialized} event.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             *
             * Emits an {Initialized} event the first time it is successfully executed.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized < type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
            /**
             * @dev Internal function that returns the initialized version. Returns `_initialized`
             */
            function _getInitializedVersion() internal view returns (uint8) {
                return _initialized;
            }
            /**
             * @dev Internal function that returns the initialized version. Returns `_initializing`
             */
            function _isInitializing() internal view returns (bool) {
                return _initializing;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
        pragma solidity ^0.8.0;
        import "../../interfaces/IERC2981Upgradeable.sol";
        import "../../utils/introspection/ERC165Upgradeable.sol";
        import "../../proxy/utils/Initializable.sol";
        /**
         * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
         *
         * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
         * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
         *
         * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
         * fee is specified in basis points by default.
         *
         * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
         * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
         * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
         *
         * _Available since v4.5._
         */
        abstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
            function __ERC2981_init() internal onlyInitializing {
            }
            function __ERC2981_init_unchained() internal onlyInitializing {
            }
            struct RoyaltyInfo {
                address receiver;
                uint96 royaltyFraction;
            }
            RoyaltyInfo private _defaultRoyaltyInfo;
            mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
            /**
             * @dev See {IERC165-supportsInterface}.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {
                return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId);
            }
            /**
             * @inheritdoc IERC2981Upgradeable
             */
            function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
                RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
                if (royalty.receiver == address(0)) {
                    royalty = _defaultRoyaltyInfo;
                }
                uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
                return (royalty.receiver, royaltyAmount);
            }
            /**
             * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
             * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
             * override.
             */
            function _feeDenominator() internal pure virtual returns (uint96) {
                return 10000;
            }
            /**
             * @dev Sets the royalty information that all ids in this contract will default to.
             *
             * Requirements:
             *
             * - `receiver` cannot be the zero address.
             * - `feeNumerator` cannot be greater than the fee denominator.
             */
            function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
                require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                require(receiver != address(0), "ERC2981: invalid receiver");
                _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
            }
            /**
             * @dev Removes default royalty information.
             */
            function _deleteDefaultRoyalty() internal virtual {
                delete _defaultRoyaltyInfo;
            }
            /**
             * @dev Sets the royalty information for a specific token id, overriding the global default.
             *
             * Requirements:
             *
             * - `receiver` cannot be the zero address.
             * - `feeNumerator` cannot be greater than the fee denominator.
             */
            function _setTokenRoyalty(
                uint256 tokenId,
                address receiver,
                uint96 feeNumerator
            ) internal virtual {
                require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                require(receiver != address(0), "ERC2981: Invalid parameters");
                _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
            }
            /**
             * @dev Resets royalty information for the token id back to the global default.
             */
            function _resetTokenRoyalty(uint256 tokenId) internal virtual {
                delete _tokenRoyaltyInfo[tokenId];
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[48] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
         * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
         *
         * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
         * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
         * need to send a transaction, and thus is not required to hold Ether at all.
         */
        interface IERC20PermitUpgradeable {
            /**
             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
             * given ``owner``'s signed approval.
             *
             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
             * ordering also apply here.
             *
             * Emits an {Approval} event.
             *
             * Requirements:
             *
             * - `spender` cannot be the zero address.
             * - `deadline` must be a timestamp in the future.
             * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
             * over the EIP712-formatted function arguments.
             * - the signature must use ``owner``'s current nonce (see {nonces}).
             *
             * For more information on the signature format, see the
             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
             * section].
             */
            function permit(
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) external;
            /**
             * @dev Returns the current nonce for `owner`. This value must be
             * included whenever a signature is generated for {permit}.
             *
             * Every successful call to {permit} increases ``owner``'s nonce by one. This
             * prevents a signature from being used multiple times.
             */
            function nonces(address owner) external view returns (uint256);
            /**
             * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
             */
            // solhint-disable-next-line func-name-mixedcase
            function DOMAIN_SEPARATOR() external view returns (bytes32);
        }
        // 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 IERC20Upgradeable {
            /**
             * @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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
        pragma solidity ^0.8.0;
        import "../IERC20Upgradeable.sol";
        import "../extensions/draft-IERC20PermitUpgradeable.sol";
        import "../../../utils/AddressUpgradeable.sol";
        /**
         * @title SafeERC20
         * @dev Wrappers around ERC20 operations that throw on failure (when the token
         * contract returns false). Tokens that return no value (and instead revert or
         * throw on failure) are also supported, non-reverting calls are assumed to be
         * successful.
         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
         */
        library SafeERC20Upgradeable {
            using AddressUpgradeable for address;
            function safeTransfer(
                IERC20Upgradeable token,
                address to,
                uint256 value
            ) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
            }
            function safeTransferFrom(
                IERC20Upgradeable token,
                address from,
                address to,
                uint256 value
            ) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
            }
            /**
             * @dev Deprecated. This function has issues similar to the ones found in
             * {IERC20-approve}, and its usage is discouraged.
             *
             * Whenever possible, use {safeIncreaseAllowance} and
             * {safeDecreaseAllowance} instead.
             */
            function safeApprove(
                IERC20Upgradeable token,
                address spender,
                uint256 value
            ) internal {
                // safeApprove should only be called when setting an initial allowance,
                // or when resetting it to zero. To increase and decrease it, use
                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                require(
                    (value == 0) || (token.allowance(address(this), spender) == 0),
                    "SafeERC20: approve from non-zero to non-zero allowance"
                );
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
            }
            function safeIncreaseAllowance(
                IERC20Upgradeable token,
                address spender,
                uint256 value
            ) internal {
                uint256 newAllowance = token.allowance(address(this), spender) + value;
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
            function safeDecreaseAllowance(
                IERC20Upgradeable token,
                address spender,
                uint256 value
            ) internal {
                unchecked {
                    uint256 oldAllowance = token.allowance(address(this), spender);
                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                    uint256 newAllowance = oldAllowance - value;
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                }
            }
            function safePermit(
                IERC20PermitUpgradeable token,
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) internal {
                uint256 nonceBefore = token.nonces(owner);
                token.permit(owner, spender, value, deadline, v, r, s);
                uint256 nonceAfter = token.nonces(owner);
                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
            }
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             */
            function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                // the target address contains contract code and also asserts for success in the low-level call.
                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                if (returndata.length > 0) {
                    // Return data is optional
                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library AddressUpgradeable {
            /**
             * @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 functionCallWithValue(target, data, 0, "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");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, 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) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or 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 {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // 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);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
        pragma solidity ^0.8.0;
        import "../proxy/utils/Initializable.sol";
        /**
         * @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 ContextUpgradeable is Initializable {
            function __Context_init() internal onlyInitializing {
            }
            function __Context_init_unchained() internal onlyInitializing {
            }
            function _msgSender() internal view virtual returns (address) {
                return msg.sender;
            }
            function _msgData() internal view virtual returns (bytes calldata) {
                return msg.data;
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[50] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
        pragma solidity ^0.8.0;
        import "./IERC165Upgradeable.sol";
        import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
            function __ERC165_init() internal onlyInitializing {
            }
            function __ERC165_init_unchained() internal onlyInitializing {
            }
            /**
             * @dev See {IERC165-supportsInterface}.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                return interfaceId == type(IERC165Upgradeable).interfaceId;
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[50] private __gap;
        }
        // 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 IERC165Upgradeable {
            /**
             * @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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev These functions deal with verification of Merkle Tree proofs.
         *
         * The tree and the proofs can be generated using our
         * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
         * You will find a quickstart guide in the readme.
         *
         * 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.
         * OpenZeppelin's JavaScript library generates merkle trees that are safe
         * against this attack out of the box.
         */
        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 simultaneously proven to be a part of a merkle tree defined by
             * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
             *
             * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
             *
             * _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}
             *
             * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
             *
             * _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 sibling nodes in `proof`. The reconstruction
             * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
             * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
             * respectively.
             *
             * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
             * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
             * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
             *
             * _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}.
             *
             * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
             *
             * _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)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.17;
        import "erc721a-upgradeable/contracts/extensions/ERC721AQueryableUpgradeable.sol";
        import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
        import "@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol";
        import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
        import "@openzeppelin/contracts-upgradeable/finance/PaymentSplitterUpgradeable.sol";
        import "operator-filter-registry/src/upgradeable/OperatorFiltererUpgradeable.sol";
        import "./ICommon.sol";
        struct PhaseSettings {
            /// @dev phase supply. This can be released to public by ending the phase.
            uint64 maxSupply;
            /// @dev tracks the total amount minted in the phase
            uint64 amountMinted;
            /// @dev wallet maximum for the phase
            uint64 maxPerWallet;
            /// @dev merkle root for the phase (if applicable, otherwise bytes32(0))
            bytes32 merkleRoot;
            /// @dev whether the phase is active
            bool isActive;
            /// @dev price for the phase (or free if 0)
            uint256 price;
        }
        struct BaseSettings {
            /// @dev public sale supply. ending a phase will carry supply into this value
            uint64 maxSupply;
            /// @dev global wallet maximum across all phases (including public)
            uint64 maxPerWallet;
            /// @dev tracks the total amount minted in the public sale
            uint64 amountMinted;
            /// @dev price for the public sale (or free if 0)
            uint256 price;
        }
        struct SaleState {
            uint64 numPhases;
            mapping(uint256 => PhaseSettings) phases;
        }
        error PhaseNotActive();
        error InvalidPhase();
        /// @author Bueno.art
        /// @title ERC-721 Multi-Phase Drop Contract
        contract Bueno721Drop is
            ERC721AQueryableUpgradeable,
            OwnableUpgradeable,
            ERC2981Upgradeable,
            PaymentSplitterUpgradeable,
            OperatorFiltererUpgradeable
        {
            string public _baseTokenURI;
            SaleState public saleState;
            BaseSettings public baseSettings;
            uint256 public maxSupply;
            address[] public withdrawAddresses;
            mapping(address => mapping(uint256 => uint64)) private amountMintedForPhase;
            bool public isPublicActive;
            bool private allowBurning;
            event TokensMinted(address indexed to, uint256 quantity);
            event TokenBurned(address indexed owner, uint256 tokenId);
            event TokensAirdropped(uint256 numRecipients, uint256 numTokens);
            event PhasesActivated(uint256[] phaseIds, bool activatedPublic);
            event PhasesPaused(uint256[] phaseIds, bool pausedPublic);
            event PhaseEnded(uint256 phaseIds);
            event BurnStatusChanged(bool burnActive);
            event PhaseSettingsUpdated(uint256 phaseId, PhaseSettings settings);
            event BaseSettingsUpdated(BaseSettings settings);
            event BaseURIUpdated(string baseURI);
            event RoyaltyUpdated(address royaltyAddress, uint96 royaltyAmount);
            /// @custom:oz-upgrades-unsafe-allow constructor
            constructor() {
                _disableInitializers();
            }
            function initialize(
                string memory _name,
                string memory _symbol,
                string memory _baseUri,
                RoyaltySettings calldata _royaltySettings,
                PhaseSettings[] calldata _phases,
                BaseSettings calldata _baseSettings,
                PaymentSplitterSettings calldata _paymentSplitterSettings,
                uint256 _maxIntendedSupply,
                bool _allowBurning,
                address _deployer,
                address _operatorFilter
            ) public initializerERC721A initializer {
                __ERC721A_init(_name, _symbol);
                __Ownable_init();
                __PaymentSplitter_init(
                    _paymentSplitterSettings.payees,
                    _paymentSplitterSettings.shares
                );
                uint64 numPhases = uint64(_phases.length);
                uint256 supplyValidationCount = _baseSettings.maxSupply;
                for (uint256 i = 0; i < numPhases; ) {
                    saleState.phases[i] = _phases[i];
                    supplyValidationCount += _phases[i].maxSupply;
                    // numPhases has a maximum value of 2^64 - 1
                    unchecked {
                        ++i;
                    }
                }
                require(
                    supplyValidationCount == _maxIntendedSupply,
                    "Supply of all phases must equal maxIntendedSupply"
                );
                _baseTokenURI = _baseUri;
                withdrawAddresses = _paymentSplitterSettings.payees;
                saleState.numPhases = numPhases;
                baseSettings = _baseSettings;
                allowBurning = _allowBurning;
                maxSupply = _maxIntendedSupply;
                _setDefaultRoyalty(
                    _royaltySettings.royaltyAddress,
                    _royaltySettings.royaltyAmount
                );
                transferOwnership(_deployer);
                OperatorFiltererUpgradeable.__OperatorFilterer_init(
                    _operatorFilter,
                    _operatorFilter == address(0) ? false : true // only subscribe if a filter is provided
                );
            }
            // ========= EXTERNAL MINTING METHODS =========
            /**
             * @notice Mint tokens for an allowlisted phase
             * @dev Calling this function for a phase that doesn't have an allowlist will fail
             */
            function mintPhaseAllowlist(
                uint256 phaseIndex,
                uint64 quantity,
                bytes32[] calldata proof
            ) external payable {
                uint64 updatedAmountMinted = _checkAllowlistPhaseMintConditions(
                    msg.sender,
                    quantity,
                    proof,
                    phaseIndex,
                    msg.value
                );
                _checkGlobalPerWalletMax(msg.sender, quantity);
                saleState.phases[phaseIndex].amountMinted += quantity;
                amountMintedForPhase[msg.sender][phaseIndex] = updatedAmountMinted;
                _mint(msg.sender, quantity);
                emit TokensMinted(msg.sender, quantity);
            }
            /**
             * @notice Mint tokens for a non-allowlist phase.
             * @dev Calling this function for a phase that has an allowlist will fail
             */
            function mintPhase(uint256 phaseIndex, uint64 quantity) external payable {
                uint64 updatedAmountMinted = _checkPhaseMintConditions(
                    msg.sender,
                    quantity,
                    phaseIndex,
                    msg.value
                );
                _checkGlobalPerWalletMax(msg.sender, quantity);
                saleState.phases[phaseIndex].amountMinted += quantity;
                amountMintedForPhase[msg.sender][phaseIndex] = updatedAmountMinted;
                _mint(msg.sender, quantity);
                emit TokensMinted(msg.sender, quantity);
            }
            /**
             * @notice Mint tokens in the public sale
             */
            function mintPublic(uint64 quantity) external payable {
                uint64 updatedAmountMinted = _checkPublicMintConditions(
                    quantity,
                    msg.value
                );
                _checkGlobalPerWalletMax(msg.sender, quantity);
                baseSettings.amountMinted = updatedAmountMinted;
                _mint(msg.sender, quantity);
                emit TokensMinted(msg.sender, quantity);
            }
            /**
             * @notice Mint tokens in all possible phases (including public sale)
             */
            function mintBatch(
                uint64[] calldata quantities,
                bytes32[][] calldata proofs,
                uint256[] calldata phaseIndices,
                uint64 publicQuantity
            ) external payable {
                uint256 phaseLength = phaseIndices.length;
                if (
                    phaseLength > saleState.numPhases ||
                    phaseLength != quantities.length ||
                    phaseLength != proofs.length
                ) {
                    revert InvalidPhase();
                }
                uint256 balance = msg.value;
                uint256 quantityToMint;
                for (uint256 i = 0; i < phaseLength; ) {
                    uint64 updatedAmount;
                    uint256 phaseIndex = phaseIndices[i];
                    uint64 quantity = quantities[i];
                    bytes32[] calldata proof = proofs[i];
                    PhaseSettings storage phase = saleState.phases[phaseIndex];
                    uint256 priceForPhase = phase.price * quantity;
                    // Since price is strictly checked in the _check* functions below,
                    // we have an additional check here to ensure that the balance doesn't underflow
                    if (balance < priceForPhase) {
                        revert InvalidPrice();
                    }
                    // if the phase has no allowlist, the merkleRoot will be zeroed out.
                    if (phase.merkleRoot == bytes32(0)) {
                        updatedAmount = _checkPhaseMintConditions(
                            msg.sender,
                            quantity,
                            phaseIndex,
                            priceForPhase
                        );
                    } else {
                        updatedAmount = _checkAllowlistPhaseMintConditions(
                            msg.sender,
                            quantity,
                            proof,
                            phaseIndex,
                            priceForPhase
                        );
                    }
                    // quantity & phaseLength have a maximum value of 2^64 - 1
                    // balance underflow is checked above
                    unchecked {
                        saleState.phases[phaseIndex].amountMinted += quantity;
                        amountMintedForPhase[msg.sender][phaseIndex] = updatedAmount;
                        balance -= priceForPhase;
                        quantityToMint += quantity;
                        ++i;
                    }
                }
                uint256 totalMintQuantity = quantityToMint;
                if (publicQuantity > 0) {
                    _checkPublicMintConditions(publicQuantity, balance);
                    // publicQuantity has a max value of 2^64 - 1
                    unchecked {
                        baseSettings.amountMinted += publicQuantity;
                        totalMintQuantity += publicQuantity;
                    }
                }
                _checkGlobalPerWalletMax(msg.sender, totalMintQuantity);
                _mint(msg.sender, totalMintQuantity);
                emit TokensMinted(msg.sender, totalMintQuantity);
            }
            /**
             * @notice Burn a token, if the contract allows for it
             */
            function burn(uint256 tokenId) external {
                if (!allowBurning) {
                    revert BurningNotAllowed();
                }
                _burn(tokenId, true);
                emit TokenBurned(msg.sender, tokenId);
            }
            // ========= OWNER METHODS =========
            /**
             * @notice Perform a batch airdrop for a particular phase.
             * @dev Minted tokens are pulled from the phase that is specified in the airdropper.
             */
            function airdropForPhase(
                uint256 phaseIndex,
                uint64[] calldata quantities,
                address[] calldata recipients
            ) external onlyOwner {
                uint256 numRecipients = recipients.length;
                uint256 totalAirdropped;
                if (numRecipients != quantities.length) revert InvalidAirdrop();
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                for (uint256 i = 0; i < numRecipients; ) {
                    uint64 updatedAmountMinted = phase.amountMinted + quantities[i];
                    if (updatedAmountMinted > phase.maxSupply) {
                        revert SoldOut();
                    }
                    // airdrops are not subject to the per-wallet mint limits,
                    // but we track how much is minted for the phase
                    phase.amountMinted = updatedAmountMinted;
                    totalAirdropped += quantities[i];
                    _mint(recipients[i], quantities[i]);
                    // numRecipients has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                emit TokensAirdropped(numRecipients, totalAirdropped);
            }
            /**
             * @notice Perform a batch airdrop for the public phase.
             * @dev Minted tokens are pulled from the public phase.
             */
            function airdropPublic(
                uint64[] calldata quantities,
                address[] calldata recipients
            ) external onlyOwner {
                uint256 numRecipients = recipients.length;
                uint256 totalAirdropped;
                if (numRecipients != quantities.length) revert InvalidAirdrop();
                for (uint256 i = 0; i < numRecipients; ) {
                    uint64 updatedAmountMinted = baseSettings.amountMinted +
                        quantities[i];
                    if (updatedAmountMinted > baseSettings.maxSupply) {
                        revert SoldOut();
                    }
                    // airdrops are not subject to the per-wallet mint limits,
                    // but we track how much is minted for the phase
                    baseSettings.amountMinted = updatedAmountMinted;
                    totalAirdropped += quantities[i];
                    _mint(recipients[i], quantities[i]);
                    // numRecipients has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                emit TokensAirdropped(numRecipients, totalAirdropped);
            }
            /**
             * @notice Specify which phases are active.
             * Public sale can be activated by setting `activatePublic` to true.
             */
            function activatePhases(
                uint256[] calldata phaseIndices,
                bool activatePublic
            ) external onlyOwner {
                uint256 numPhases = phaseIndices.length;
                // activate all the phases provided in phaseIndices
                for (uint256 i = 0; i < numPhases; ) {
                    uint256 phaseIndex = phaseIndices[i];
                    if (phaseIndex >= saleState.numPhases) {
                        // phaseIndex is out of bounds
                        revert InvalidPhase();
                    }
                    saleState.phases[phaseIndices[i]].isActive = true;
                    // numPhases has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                // calling this function with activatePublic=false only indicates the public sale
                // is not intended to be activated, but it does not pause it.
                if (activatePublic) {
                    isPublicActive = true;
                }
                emit PhasesActivated(phaseIndices, activatePublic);
            }
            /**
             * @notice Specify which phases are inactive (paused).
             * Public sale can be paused by setting `pausePublic` to true.
             * Pausing is separate from ending, since ending permanently closes the phase.
             */
            function pausePhases(
                uint256[] calldata phaseIndices,
                bool pausePublic
            ) external onlyOwner {
                uint256 numPhases = phaseIndices.length;
                for (uint256 i = 0; i < numPhases; ) {
                    uint256 phaseIndex = phaseIndices[i];
                    if (phaseIndex >= saleState.numPhases) {
                        // phaseIndex is out of bounds
                        revert InvalidPhase();
                    }
                    saleState.phases[phaseIndex].isActive = false;
                    // numPhases has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                // calling this function with pausePublic=false only indicates the public sale
                // is not intended to be paused, but it does not pause it.
                if (pausePublic) {
                    isPublicActive = false;
                }
                emit PhasesPaused(phaseIndices, pausePublic);
            }
            /**
             * @notice If enabled, the token can be burned, for approved operators.
             * @dev The burn method will revert unless this is enabled
             */
            function toggleBurning() external onlyOwner {
                allowBurning = !allowBurning;
                emit BurnStatusChanged(allowBurning);
            }
            /**
             * @notice Permanently closes a phase by capping the supply & releasing it
             */
            function endPhase(uint256 phaseIndex) public onlyOwner {
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                // if the phase never had supply, there is nothing to do
                if (phase.maxSupply == 0) {
                    revert InvalidPhase();
                }
                // transfer the remaining supply into the base settings (used for public sale accounting)
                baseSettings.maxSupply += phase.maxSupply - phase.amountMinted;
                // remove the supply from the phase
                phase.maxSupply = 0;
                emit PhaseEnded(phaseIndex);
            }
            function endPhases(uint64[] calldata phaseIndices) external onlyOwner {
                uint256 phaseIndicesLength = phaseIndices.length;
                // ensure that phaseIndices argument will only ever be as large as the number of phases
                if (phaseIndicesLength > saleState.numPhases) {
                    revert InvalidPhase();
                }
                for (uint256 i = 0; i < phaseIndicesLength; ) {
                    endPhase(phaseIndices[i]);
                    // phaseIndicesLength has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
            }
            /**
             * @notice Updates the minting rules for a particular phase
             * @dev supply & amountMinted are not changeable
             */
            function updatePhaseSettings(
                uint256 phaseIndex,
                PhaseSettings calldata phase
            ) external onlyOwner {
                uint64 existingAmountMinted = saleState.phases[phaseIndex].amountMinted;
                uint64 existingMaxSupply = saleState.phases[phaseIndex].maxSupply;
                bool existingStatus = saleState.phases[phaseIndex].isActive;
                saleState.phases[phaseIndex] = phase;
                // ensure that the amountMinted, maxSupply, and status values cannot be set
                saleState.phases[phaseIndex].amountMinted = existingAmountMinted;
                saleState.phases[phaseIndex].maxSupply = existingMaxSupply;
                saleState.phases[phaseIndex].isActive = existingStatus;
                emit PhaseSettingsUpdated(phaseIndex, phase);
            }
            /**
             * @notice Updates the the base minting settings
             * The global maxPerWallet setting applies to all phases
             * Pricing and other fields will apply to the public sale
             *
             * @dev maxSupply & amountMinted are not changeable
             */
            function updateBaseSettings(
                BaseSettings calldata _baseSettings
            ) external onlyOwner {
                uint64 existingMaxSupply = baseSettings.maxSupply;
                uint64 existingAmountMinted = baseSettings.amountMinted;
                baseSettings = _baseSettings;
                // ensure that the maxSupply & amountMinted value cannot be set
                baseSettings.maxSupply = existingMaxSupply;
                baseSettings.amountMinted = existingAmountMinted;
                emit BaseSettingsUpdated(_baseSettings);
            }
            /**
             * @dev Payment can be pulled via PaymentSplitter.release
             * this method is provided for convenience to release all payee funds
             */
            function withdraw() external onlyOwner {
                uint256 numAddresses = withdrawAddresses.length;
                for (uint256 i = 0; i < numAddresses; ) {
                    address payable withdrawAddress = payable(withdrawAddresses[i]);
                    if (releasable(withdrawAddress) > 0) {
                        release(withdrawAddress);
                    }
                    // numAddresses has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
            }
            function setBaseURI(string memory baseURI) external onlyOwner {
                _baseTokenURI = baseURI;
                emit BaseURIUpdated(baseURI);
            }
            function setRoyaltyInfo(
                address receiver,
                uint96 feeBasisPoints
            ) external onlyOwner {
                _setDefaultRoyalty(receiver, feeBasisPoints);
                emit RoyaltyUpdated(receiver, feeBasisPoints);
            }
            // ========= VIEW METHODS =========
            function _startTokenId() internal view virtual override returns (uint256) {
                return 1;
            }
            function _checkAllowlistPhaseMintConditions(
                address wallet,
                uint64 quantity,
                bytes32[] calldata proof,
                uint256 phaseIndex,
                uint256 balance
            ) internal view returns (uint64) {
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                if (!phase.isActive) {
                    revert PhaseNotActive();
                }
                // there should be a valid merkle root for the phase
                if (phase.merkleRoot == bytes32(0)) {
                    revert InvalidMintFunction();
                }
                if (phase.amountMinted + quantity > phase.maxSupply) {
                    revert SoldOut();
                }
                if (balance != quantity * phase.price) {
                    revert InvalidPrice();
                }
                if (
                    !MerkleProof.verify(
                        proof,
                        phase.merkleRoot,
                        keccak256(abi.encodePacked(wallet))
                    )
                ) {
                    revert InvalidProof();
                }
                uint256 amountMinted = amountMintedForPhase[wallet][phaseIndex];
                uint256 updatedAmountMinted = amountMinted + quantity;
                // phases can have a maxPerWallet
                if (
                    phase.maxPerWallet > 0 && updatedAmountMinted > phase.maxPerWallet
                ) {
                    revert ExceedMaxPerWallet();
                }
                return uint64(updatedAmountMinted);
            }
            function _checkPhaseMintConditions(
                address wallet,
                uint256 quantity,
                uint256 phaseIndex,
                uint256 balance
            ) internal view returns (uint64) {
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                if (!phase.isActive) {
                    revert PhaseNotActive();
                }
                // the phase should not have a merkleRoot
                if (phase.merkleRoot != bytes32(0)) {
                    revert InvalidMintFunction();
                }
                if (phase.amountMinted + quantity > phase.maxSupply) {
                    revert SoldOut();
                }
                if (balance != quantity * phase.price) {
                    revert InvalidPrice();
                }
                uint256 amountMinted = amountMintedForPhase[wallet][phaseIndex];
                uint256 updatedAmountMinted = amountMinted + quantity;
                // phases can have a maxPerWallet
                if (
                    phase.maxPerWallet > 0 && updatedAmountMinted > phase.maxPerWallet
                ) {
                    revert ExceedMaxPerWallet();
                }
                return uint64(updatedAmountMinted);
            }
            function _checkPublicMintConditions(
                uint256 quantity,
                uint256 balance
            ) internal view returns (uint64) {
                if (!isPublicActive) {
                    revert PhaseNotActive();
                }
                uint256 updatedAmountMinted = baseSettings.amountMinted + quantity;
                if (updatedAmountMinted > baseSettings.maxSupply) {
                    revert SoldOut();
                }
                if (balance != quantity * baseSettings.price) {
                    revert InvalidPrice();
                }
                return uint64(updatedAmountMinted);
            }
            function _checkGlobalPerWalletMax(
                address wallet,
                uint256 quantity
            ) internal view {
                if (
                    baseSettings.maxPerWallet > 0 &&
                    _numberMinted(wallet) + quantity > baseSettings.maxPerWallet
                ) {
                    revert ExceedMaxPerWallet();
                }
            }
            function getDataForPhase(
                uint256 phaseIndex
            ) external view returns (PhaseSettings memory) {
                return saleState.phases[phaseIndex];
            }
            function getMintBalance(address wallet) external view returns (uint256) {
                return _numberMinted(wallet);
            }
            function getAmountMintedForPhase(
                uint256 phaseIndex,
                address wallet
            ) external view returns (uint64) {
                return amountMintedForPhase[wallet][phaseIndex];
            }
            function getAmountMintedForOwner(
                address wallet
            ) external view returns (uint256[] memory) {
                uint256[] memory amountMintedPerPhase = new uint256[](
                    saleState.numPhases + 1
                );
                for (uint64 i = 0; i < saleState.numPhases; ) {
                    amountMintedPerPhase[i] = amountMintedForPhase[wallet][i];
                    // numPhases has a maximum value of 2^64 - 1
                    unchecked {
                        ++i;
                    }
                }
                amountMintedPerPhase[saleState.numPhases] = _numberMinted(wallet);
                return amountMintedPerPhase;
            }
            /**
             * @dev See {ERC721-_baseURI}.
             */
            function _baseURI() internal view virtual override returns (string memory) {
                return _baseTokenURI;
            }
            function supportsInterface(
                bytes4 interfaceId
            )
                public
                view
                virtual
                override(IERC721AUpgradeable, ERC721AUpgradeable, ERC2981Upgradeable)
                returns (bool)
            {
                return
                    ERC721AUpgradeable.supportsInterface(interfaceId) ||
                    ERC2981Upgradeable.supportsInterface(interfaceId);
            }
            // ========= OPERATOR FILTERER OVERRIDES =========
            function setApprovalForAll(
                address operator,
                bool approved
            )
                public
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperatorApproval(operator)
            {
                super.setApprovalForAll(operator, approved);
            }
            function approve(
                address operator,
                uint256 tokenId
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperatorApproval(operator)
            {
                super.approve(operator, tokenId);
            }
            function transferFrom(
                address from,
                address to,
                uint256 tokenId
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperator(from)
            {
                super.transferFrom(from, to, tokenId);
            }
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperator(from)
            {
                super.safeTransferFrom(from, to, tokenId);
            }
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId,
                bytes memory data
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperator(from)
            {
                super.safeTransferFrom(from, to, tokenId, data);
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.17;
        error InvalidPrice();
        error SoldOut();
        error ExceedMaxPerWallet();
        error InvalidProof();
        error InvalidMintFunction();
        error InvalidAirdrop();
        error BurningNotAllowed();
        struct PaymentSplitterSettings {
            address[] payees;
            uint256[] shares;
        }
        struct RoyaltySettings {
            address royaltyAddress;
            uint96 royaltyAmount;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /**
         * @dev This is a base contract to aid in writing upgradeable diamond facet contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         */
        import {ERC721A__InitializableStorage} from './ERC721A__InitializableStorage.sol';
        abstract contract ERC721A__Initializable {
            using ERC721A__InitializableStorage for ERC721A__InitializableStorage.Layout;
            /**
             * @dev Modifier to protect an initializer function from being invoked twice.
             */
            modifier initializerERC721A() {
                // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                // contract may have been reentered.
                require(
                    ERC721A__InitializableStorage.layout()._initializing
                        ? _isConstructor()
                        : !ERC721A__InitializableStorage.layout()._initialized,
                    'ERC721A__Initializable: contract is already initialized'
                );
                bool isTopLevelCall = !ERC721A__InitializableStorage.layout()._initializing;
                if (isTopLevelCall) {
                    ERC721A__InitializableStorage.layout()._initializing = true;
                    ERC721A__InitializableStorage.layout()._initialized = true;
                }
                _;
                if (isTopLevelCall) {
                    ERC721A__InitializableStorage.layout()._initializing = false;
                }
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} modifier, directly or indirectly.
             */
            modifier onlyInitializingERC721A() {
                require(
                    ERC721A__InitializableStorage.layout()._initializing,
                    'ERC721A__Initializable: contract is not initializing'
                );
                _;
            }
            /// @dev Returns true if and only if the function is running in the constructor
            function _isConstructor() private view returns (bool) {
                // extcodesize checks the size of the code stored in an address, and
                // address returns the current address. Since the code is still not
                // deployed when running a constructor, any checks on its code size will
                // yield zero, making it an effective way to detect if a contract is
                // under construction or not.
                address self = address(this);
                uint256 cs;
                assembly {
                    cs := extcodesize(self)
                }
                return cs == 0;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /**
         * @dev This is a base storage for the  initialization function for upgradeable diamond facet contracts
         **/
        library ERC721A__InitializableStorage {
            struct Layout {
                /*
                 * Indicates that the contract has been initialized.
                 */
                bool _initialized;
                /*
                 * Indicates that the contract is in the process of being initialized.
                 */
                bool _initializing;
            }
            bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.initializable.facet');
            function layout() internal pure returns (Layout storage l) {
                bytes32 slot = STORAGE_SLOT;
                assembly {
                    l.slot := slot
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        library ERC721AStorage {
            // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
            struct TokenApprovalRef {
                address value;
            }
            struct Layout {
                // =============================================================
                //                            STORAGE
                // =============================================================
                // The next token ID to be minted.
                uint256 _currentIndex;
                // The number of tokens burned.
                uint256 _burnCounter;
                // Token name
                string _name;
                // Token symbol
                string _symbol;
                // Mapping from token ID to ownership details
                // An empty struct value does not necessarily mean the token is unowned.
                // See {_packedOwnershipOf} implementation for details.
                //
                // Bits Layout:
                // - [0..159]   `addr`
                // - [160..223] `startTimestamp`
                // - [224]      `burned`
                // - [225]      `nextInitialized`
                // - [232..255] `extraData`
                mapping(uint256 => uint256) _packedOwnerships;
                // Mapping owner address to address data.
                //
                // Bits Layout:
                // - [0..63]    `balance`
                // - [64..127]  `numberMinted`
                // - [128..191] `numberBurned`
                // - [192..255] `aux`
                mapping(address => uint256) _packedAddressData;
                // Mapping from token ID to approved address.
                mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals;
                // Mapping from owner to operator approvals
                mapping(address => mapping(address => bool)) _operatorApprovals;
            }
            bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.ERC721A');
            function layout() internal pure returns (Layout storage l) {
                bytes32 slot = STORAGE_SLOT;
                assembly {
                    l.slot := slot
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        import './IERC721AUpgradeable.sol';
        import {ERC721AStorage} from './ERC721AStorage.sol';
        import './ERC721A__Initializable.sol';
        /**
         * @dev Interface of ERC721 token receiver.
         */
        interface ERC721A__IERC721ReceiverUpgradeable {
            function onERC721Received(
                address operator,
                address from,
                uint256 tokenId,
                bytes calldata data
            ) external returns (bytes4);
        }
        /**
         * @title ERC721A
         *
         * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
         * Non-Fungible Token Standard, including the Metadata extension.
         * Optimized for lower gas during batch mints.
         *
         * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
         * starting from `_startTokenId()`.
         *
         * Assumptions:
         *
         * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
         * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
         */
        contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable {
            using ERC721AStorage for ERC721AStorage.Layout;
            // =============================================================
            //                           CONSTANTS
            // =============================================================
            // Mask of an entry in packed address data.
            uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
            // The bit position of `numberMinted` in packed address data.
            uint256 private constant _BITPOS_NUMBER_MINTED = 64;
            // The bit position of `numberBurned` in packed address data.
            uint256 private constant _BITPOS_NUMBER_BURNED = 128;
            // The bit position of `aux` in packed address data.
            uint256 private constant _BITPOS_AUX = 192;
            // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
            uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
            // The bit position of `startTimestamp` in packed ownership.
            uint256 private constant _BITPOS_START_TIMESTAMP = 160;
            // The bit mask of the `burned` bit in packed ownership.
            uint256 private constant _BITMASK_BURNED = 1 << 224;
            // The bit position of the `nextInitialized` bit in packed ownership.
            uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
            // The bit mask of the `nextInitialized` bit in packed ownership.
            uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
            // The bit position of `extraData` in packed ownership.
            uint256 private constant _BITPOS_EXTRA_DATA = 232;
            // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
            uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
            // The mask of the lower 160 bits for addresses.
            uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
            // The maximum `quantity` that can be minted with {_mintERC2309}.
            // This limit is to prevent overflows on the address data entries.
            // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
            // is required to cause an overflow, which is unrealistic.
            uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
            // The `Transfer` event signature is given by:
            // `keccak256(bytes("Transfer(address,address,uint256)"))`.
            bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
                0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
            // =============================================================
            //                          CONSTRUCTOR
            // =============================================================
            function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                __ERC721A_init_unchained(name_, symbol_);
            }
            function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                ERC721AStorage.layout()._name = name_;
                ERC721AStorage.layout()._symbol = symbol_;
                ERC721AStorage.layout()._currentIndex = _startTokenId();
            }
            // =============================================================
            //                   TOKEN COUNTING OPERATIONS
            // =============================================================
            /**
             * @dev Returns the starting token ID.
             * To change the starting token ID, please override this function.
             */
            function _startTokenId() internal view virtual returns (uint256) {
                return 0;
            }
            /**
             * @dev Returns the next token ID to be minted.
             */
            function _nextTokenId() internal view virtual returns (uint256) {
                return ERC721AStorage.layout()._currentIndex;
            }
            /**
             * @dev Returns the total number of tokens in existence.
             * Burned tokens will reduce the count.
             * To get the total number of tokens minted, please see {_totalMinted}.
             */
            function totalSupply() public view virtual override returns (uint256) {
                // Counter underflow is impossible as _burnCounter cannot be incremented
                // more than `_currentIndex - _startTokenId()` times.
                unchecked {
                    return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId();
                }
            }
            /**
             * @dev Returns the total amount of tokens minted in the contract.
             */
            function _totalMinted() internal view virtual returns (uint256) {
                // Counter underflow is impossible as `_currentIndex` does not decrement,
                // and it is initialized to `_startTokenId()`.
                unchecked {
                    return ERC721AStorage.layout()._currentIndex - _startTokenId();
                }
            }
            /**
             * @dev Returns the total number of tokens burned.
             */
            function _totalBurned() internal view virtual returns (uint256) {
                return ERC721AStorage.layout()._burnCounter;
            }
            // =============================================================
            //                    ADDRESS DATA OPERATIONS
            // =============================================================
            /**
             * @dev Returns the number of tokens in `owner`'s account.
             */
            function balanceOf(address owner) public view virtual override returns (uint256) {
                if (owner == address(0)) revert BalanceQueryForZeroAddress();
                return ERC721AStorage.layout()._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
            }
            /**
             * Returns the number of tokens minted by `owner`.
             */
            function _numberMinted(address owner) internal view returns (uint256) {
                return
                    (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
            }
            /**
             * Returns the number of tokens burned by or on behalf of `owner`.
             */
            function _numberBurned(address owner) internal view returns (uint256) {
                return
                    (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
            }
            /**
             * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
             */
            function _getAux(address owner) internal view returns (uint64) {
                return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX);
            }
            /**
             * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
             * If there are multiple variables, please pack them into a uint64.
             */
            function _setAux(address owner, uint64 aux) internal virtual {
                uint256 packed = ERC721AStorage.layout()._packedAddressData[owner];
                uint256 auxCasted;
                // Cast `aux` with assembly to avoid redundant masking.
                assembly {
                    auxCasted := aux
                }
                packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
                ERC721AStorage.layout()._packedAddressData[owner] = packed;
            }
            // =============================================================
            //                            IERC165
            // =============================================================
            /**
             * @dev Returns true if this contract implements the interface defined by
             * `interfaceId`. See the corresponding
             * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
             * to learn more about how these ids are created.
             *
             * This function call must use less than 30000 gas.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                // The interface IDs are constants representing the first 4 bytes
                // of the XOR of all function selectors in the interface.
                // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
                // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
                return
                    interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                    interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
                    interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
            }
            // =============================================================
            //                        IERC721Metadata
            // =============================================================
            /**
             * @dev Returns the token collection name.
             */
            function name() public view virtual override returns (string memory) {
                return ERC721AStorage.layout()._name;
            }
            /**
             * @dev Returns the token collection symbol.
             */
            function symbol() public view virtual override returns (string memory) {
                return ERC721AStorage.layout()._symbol;
            }
            /**
             * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
             */
            function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                string memory baseURI = _baseURI();
                return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
            }
            /**
             * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
             * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
             * by default, it can be overridden in child contracts.
             */
            function _baseURI() internal view virtual returns (string memory) {
                return '';
            }
            // =============================================================
            //                     OWNERSHIPS OPERATIONS
            // =============================================================
            /**
             * @dev Returns the owner of the `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function ownerOf(uint256 tokenId) public view virtual override returns (address) {
                return address(uint160(_packedOwnershipOf(tokenId)));
            }
            /**
             * @dev Gas spent here starts off proportional to the maximum mint batch size.
             * It gradually moves to O(1) as tokens get transferred around over time.
             */
            function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
                return _unpackedOwnership(_packedOwnershipOf(tokenId));
            }
            /**
             * @dev Returns the unpacked `TokenOwnership` struct at `index`.
             */
            function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
                return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]);
            }
            /**
             * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
             */
            function _initializeOwnershipAt(uint256 index) internal virtual {
                if (ERC721AStorage.layout()._packedOwnerships[index] == 0) {
                    ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index);
                }
            }
            /**
             * Returns the packed ownership data of `tokenId`.
             */
            function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
                if (_startTokenId() <= tokenId) {
                    packed = ERC721AStorage.layout()._packedOwnerships[tokenId];
                    // If not burned.
                    if (packed & _BITMASK_BURNED == 0) {
                        // If the data at the starting slot does not exist, start the scan.
                        if (packed == 0) {
                            if (tokenId >= ERC721AStorage.layout()._currentIndex) revert OwnerQueryForNonexistentToken();
                            // Invariant:
                            // There will always be an initialized ownership slot
                            // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                            // before an unintialized ownership slot
                            // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                            // Hence, `tokenId` will not underflow.
                            //
                            // We can directly compare the packed value.
                            // If the address is zero, packed will be zero.
                            for (;;) {
                                unchecked {
                                    packed = ERC721AStorage.layout()._packedOwnerships[--tokenId];
                                }
                                if (packed == 0) continue;
                                return packed;
                            }
                        }
                        // Otherwise, the data exists and is not burned. We can skip the scan.
                        // This is possible because we have already achieved the target condition.
                        // This saves 2143 gas on transfers of initialized tokens.
                        return packed;
                    }
                }
                revert OwnerQueryForNonexistentToken();
            }
            /**
             * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
             */
            function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
                ownership.addr = address(uint160(packed));
                ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
                ownership.burned = packed & _BITMASK_BURNED != 0;
                ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
            }
            /**
             * @dev Packs ownership data into a single uint256.
             */
            function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
                assembly {
                    // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                    owner := and(owner, _BITMASK_ADDRESS)
                    // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                    result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
                }
            }
            /**
             * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
             */
            function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
                // For branchless setting of the `nextInitialized` flag.
                assembly {
                    // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                    result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
                }
            }
            // =============================================================
            //                      APPROVAL OPERATIONS
            // =============================================================
            /**
             * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
             *
             * Requirements:
             *
             * - The caller must own the token or be an approved operator.
             */
            function approve(address to, uint256 tokenId) public payable virtual override {
                _approve(to, tokenId, true);
            }
            /**
             * @dev Returns the account approved for `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function getApproved(uint256 tokenId) public view virtual override returns (address) {
                if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
                return ERC721AStorage.layout()._tokenApprovals[tokenId].value;
            }
            /**
             * @dev Approve or remove `operator` as an operator for the caller.
             * Operators can call {transferFrom} or {safeTransferFrom}
             * for any token owned by the caller.
             *
             * Requirements:
             *
             * - The `operator` cannot be the caller.
             *
             * Emits an {ApprovalForAll} event.
             */
            function setApprovalForAll(address operator, bool approved) public virtual override {
                ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved;
                emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
            }
            /**
             * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
             *
             * See {setApprovalForAll}.
             */
            function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
                return ERC721AStorage.layout()._operatorApprovals[owner][operator];
            }
            /**
             * @dev Returns whether `tokenId` exists.
             *
             * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
             *
             * Tokens start existing when they are minted. See {_mint}.
             */
            function _exists(uint256 tokenId) internal view virtual returns (bool) {
                return
                    _startTokenId() <= tokenId &&
                    tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds,
                    ERC721AStorage.layout()._packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
            }
            /**
             * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
             */
            function _isSenderApprovedOrOwner(
                address approvedAddress,
                address owner,
                address msgSender
            ) private pure returns (bool result) {
                assembly {
                    // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                    owner := and(owner, _BITMASK_ADDRESS)
                    // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                    msgSender := and(msgSender, _BITMASK_ADDRESS)
                    // `msgSender == owner || msgSender == approvedAddress`.
                    result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
                }
            }
            /**
             * @dev Returns the storage slot and value for the approved address of `tokenId`.
             */
            function _getApprovedSlotAndAddress(uint256 tokenId)
                private
                view
                returns (uint256 approvedAddressSlot, address approvedAddress)
            {
                ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage.layout()._tokenApprovals[tokenId];
                // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
                assembly {
                    approvedAddressSlot := tokenApproval.slot
                    approvedAddress := sload(approvedAddressSlot)
                }
            }
            // =============================================================
            //                      TRANSFER OPERATIONS
            // =============================================================
            /**
             * @dev Transfers `tokenId` from `from` to `to`.
             *
             * 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
            ) public payable virtual override {
                uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
                (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                // The nested ifs save around 20+ gas over a compound boolean condition.
                if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                    if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                if (to == address(0)) revert TransferToZeroAddress();
                _beforeTokenTransfers(from, to, tokenId, 1);
                // Clear approvals from the previous owner.
                assembly {
                    if approvedAddress {
                        // This is equivalent to `delete _tokenApprovals[tokenId]`.
                        sstore(approvedAddressSlot, 0)
                    }
                }
                // Underflow of the sender's balance is impossible because we check for
                // ownership above and the recipient's balance can't realistically overflow.
                // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                unchecked {
                    // We can directly increment and decrement the balances.
                    --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`.
                    ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`.
                    // Updates:
                    // - `address` to the next owner.
                    // - `startTimestamp` to the timestamp of transfering.
                    // - `burned` to `false`.
                    // - `nextInitialized` to `true`.
                    ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                        to,
                        _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
                    );
                    // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                    if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                        uint256 nextTokenId = tokenId + 1;
                        // If the next slot's address is zero and not burned (i.e. packed value is zero).
                        if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                            // If the next slot is within bounds.
                            if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                            }
                        }
                    }
                }
                emit Transfer(from, to, tokenId);
                _afterTokenTransfers(from, to, tokenId, 1);
            }
            /**
             * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
             */
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
            ) public payable virtual override {
                safeTransferFrom(from, to, tokenId, '');
            }
            /**
             * @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 memory _data
            ) public payable virtual override {
                transferFrom(from, to, tokenId);
                if (to.code.length != 0)
                    if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                        revert TransferToNonERC721ReceiverImplementer();
                    }
            }
            /**
             * @dev Hook that is called before a set of serially-ordered token IDs
             * are about to be transferred. This includes minting.
             * And also called before burning one token.
             *
             * `startTokenId` - the first token ID to be transferred.
             * `quantity` - the amount to be transferred.
             *
             * Calling conditions:
             *
             * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
             * transferred to `to`.
             * - When `from` is zero, `tokenId` will be minted for `to`.
             * - When `to` is zero, `tokenId` will be burned by `from`.
             * - `from` and `to` are never both zero.
             */
            function _beforeTokenTransfers(
                address from,
                address to,
                uint256 startTokenId,
                uint256 quantity
            ) internal virtual {}
            /**
             * @dev Hook that is called after a set of serially-ordered token IDs
             * have been transferred. This includes minting.
             * And also called after one token has been burned.
             *
             * `startTokenId` - the first token ID to be transferred.
             * `quantity` - the amount to be transferred.
             *
             * Calling conditions:
             *
             * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
             * transferred to `to`.
             * - When `from` is zero, `tokenId` has been minted for `to`.
             * - When `to` is zero, `tokenId` has been burned by `from`.
             * - `from` and `to` are never both zero.
             */
            function _afterTokenTransfers(
                address from,
                address to,
                uint256 startTokenId,
                uint256 quantity
            ) internal virtual {}
            /**
             * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
             *
             * `from` - Previous owner of the given token ID.
             * `to` - Target address that will receive the token.
             * `tokenId` - Token ID to be transferred.
             * `_data` - Optional data to send along with the call.
             *
             * Returns whether the call correctly returned the expected magic value.
             */
            function _checkContractOnERC721Received(
                address from,
                address to,
                uint256 tokenId,
                bytes memory _data
            ) private returns (bool) {
                try
                    ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data)
                returns (bytes4 retval) {
                    return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector;
                } catch (bytes memory reason) {
                    if (reason.length == 0) {
                        revert TransferToNonERC721ReceiverImplementer();
                    } else {
                        assembly {
                            revert(add(32, reason), mload(reason))
                        }
                    }
                }
            }
            // =============================================================
            //                        MINT OPERATIONS
            // =============================================================
            /**
             * @dev Mints `quantity` tokens and transfers them to `to`.
             *
             * Requirements:
             *
             * - `to` cannot be the zero address.
             * - `quantity` must be greater than 0.
             *
             * Emits a {Transfer} event for each mint.
             */
            function _mint(address to, uint256 quantity) internal virtual {
                uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                if (quantity == 0) revert MintZeroQuantity();
                _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                // Overflows are incredibly unrealistic.
                // `balance` and `numberMinted` have a maximum limit of 2**64.
                // `tokenId` has a maximum limit of 2**256.
                unchecked {
                    // Updates:
                    // - `balance += quantity`.
                    // - `numberMinted += quantity`.
                    //
                    // We can directly add to the `balance` and `numberMinted`.
                    ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                    // Updates:
                    // - `address` to the owner.
                    // - `startTimestamp` to the timestamp of minting.
                    // - `burned` to `false`.
                    // - `nextInitialized` to `quantity == 1`.
                    ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                        to,
                        _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                    );
                    uint256 toMasked;
                    uint256 end = startTokenId + quantity;
                    // Use assembly to loop and emit the `Transfer` event for gas savings.
                    // The duplicated `log4` removes an extra check and reduces stack juggling.
                    // The assembly, together with the surrounding Solidity code, have been
                    // delicately arranged to nudge the compiler into producing optimized opcodes.
                    assembly {
                        // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        toMasked := and(to, _BITMASK_ADDRESS)
                        // Emit the `Transfer` event.
                        log4(
                            0, // Start of data (0, since no data).
                            0, // End of data (0, since no data).
                            _TRANSFER_EVENT_SIGNATURE, // Signature.
                            0, // `address(0)`.
                            toMasked, // `to`.
                            startTokenId // `tokenId`.
                        )
                        // The `iszero(eq(,))` check ensures that large values of `quantity`
                        // that overflows uint256 will make the loop run out of gas.
                        // The compiler will optimize the `iszero` away for performance.
                        for {
                            let tokenId := add(startTokenId, 1)
                        } iszero(eq(tokenId, end)) {
                            tokenId := add(tokenId, 1)
                        } {
                            // Emit the `Transfer` event. Similar to above.
                            log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                        }
                    }
                    if (toMasked == 0) revert MintToZeroAddress();
                    ERC721AStorage.layout()._currentIndex = end;
                }
                _afterTokenTransfers(address(0), to, startTokenId, quantity);
            }
            /**
             * @dev Mints `quantity` tokens and transfers them to `to`.
             *
             * This function is intended for efficient minting only during contract creation.
             *
             * It emits only one {ConsecutiveTransfer} as defined in
             * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
             * instead of a sequence of {Transfer} event(s).
             *
             * Calling this function outside of contract creation WILL make your contract
             * non-compliant with the ERC721 standard.
             * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
             * {ConsecutiveTransfer} event is only permissible during contract creation.
             *
             * Requirements:
             *
             * - `to` cannot be the zero address.
             * - `quantity` must be greater than 0.
             *
             * Emits a {ConsecutiveTransfer} event.
             */
            function _mintERC2309(address to, uint256 quantity) internal virtual {
                uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                if (to == address(0)) revert MintToZeroAddress();
                if (quantity == 0) revert MintZeroQuantity();
                if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
                _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
                unchecked {
                    // Updates:
                    // - `balance += quantity`.
                    // - `numberMinted += quantity`.
                    //
                    // We can directly add to the `balance` and `numberMinted`.
                    ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                    // Updates:
                    // - `address` to the owner.
                    // - `startTimestamp` to the timestamp of minting.
                    // - `burned` to `false`.
                    // - `nextInitialized` to `quantity == 1`.
                    ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                        to,
                        _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                    );
                    emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
                    ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
                }
                _afterTokenTransfers(address(0), to, startTokenId, quantity);
            }
            /**
             * @dev Safely mints `quantity` tokens and transfers them to `to`.
             *
             * Requirements:
             *
             * - If `to` refers to a smart contract, it must implement
             * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
             * - `quantity` must be greater than 0.
             *
             * See {_mint}.
             *
             * Emits a {Transfer} event for each mint.
             */
            function _safeMint(
                address to,
                uint256 quantity,
                bytes memory _data
            ) internal virtual {
                _mint(to, quantity);
                unchecked {
                    if (to.code.length != 0) {
                        uint256 end = ERC721AStorage.layout()._currentIndex;
                        uint256 index = end - quantity;
                        do {
                            if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                                revert TransferToNonERC721ReceiverImplementer();
                            }
                        } while (index < end);
                        // Reentrancy protection.
                        if (ERC721AStorage.layout()._currentIndex != end) revert();
                    }
                }
            }
            /**
             * @dev Equivalent to `_safeMint(to, quantity, '')`.
             */
            function _safeMint(address to, uint256 quantity) internal virtual {
                _safeMint(to, quantity, '');
            }
            // =============================================================
            //                       APPROVAL OPERATIONS
            // =============================================================
            /**
             * @dev Equivalent to `_approve(to, tokenId, false)`.
             */
            function _approve(address to, uint256 tokenId) internal virtual {
                _approve(to, tokenId, false);
            }
            /**
             * @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:
             *
             * - `tokenId` must exist.
             *
             * Emits an {Approval} event.
             */
            function _approve(
                address to,
                uint256 tokenId,
                bool approvalCheck
            ) internal virtual {
                address owner = ownerOf(tokenId);
                if (approvalCheck)
                    if (_msgSenderERC721A() != owner)
                        if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                            revert ApprovalCallerNotOwnerNorApproved();
                        }
                ERC721AStorage.layout()._tokenApprovals[tokenId].value = to;
                emit Approval(owner, to, tokenId);
            }
            // =============================================================
            //                        BURN OPERATIONS
            // =============================================================
            /**
             * @dev Equivalent to `_burn(tokenId, false)`.
             */
            function _burn(uint256 tokenId) internal virtual {
                _burn(tokenId, false);
            }
            /**
             * @dev Destroys `tokenId`.
             * The approval is cleared when the token is burned.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             *
             * Emits a {Transfer} event.
             */
            function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
                uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                address from = address(uint160(prevOwnershipPacked));
                (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                if (approvalCheck) {
                    // The nested ifs save around 20+ gas over a compound boolean condition.
                    if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                        if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                }
                _beforeTokenTransfers(from, address(0), tokenId, 1);
                // Clear approvals from the previous owner.
                assembly {
                    if approvedAddress {
                        // This is equivalent to `delete _tokenApprovals[tokenId]`.
                        sstore(approvedAddressSlot, 0)
                    }
                }
                // Underflow of the sender's balance is impossible because we check for
                // ownership above and the recipient's balance can't realistically overflow.
                // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                unchecked {
                    // Updates:
                    // - `balance -= 1`.
                    // - `numberBurned += 1`.
                    //
                    // We can directly decrement the balance, and increment the number burned.
                    // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
                    ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
                    // Updates:
                    // - `address` to the last owner.
                    // - `startTimestamp` to the timestamp of burning.
                    // - `burned` to `true`.
                    // - `nextInitialized` to `true`.
                    ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                        from,
                        (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
                    );
                    // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                    if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                        uint256 nextTokenId = tokenId + 1;
                        // If the next slot's address is zero and not burned (i.e. packed value is zero).
                        if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                            // If the next slot is within bounds.
                            if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                            }
                        }
                    }
                }
                emit Transfer(from, address(0), tokenId);
                _afterTokenTransfers(from, address(0), tokenId, 1);
                // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
                unchecked {
                    ERC721AStorage.layout()._burnCounter++;
                }
            }
            // =============================================================
            //                     EXTRA DATA OPERATIONS
            // =============================================================
            /**
             * @dev Directly sets the extra data for the ownership data `index`.
             */
            function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
                uint256 packed = ERC721AStorage.layout()._packedOwnerships[index];
                if (packed == 0) revert OwnershipNotInitializedForExtraData();
                uint256 extraDataCasted;
                // Cast `extraData` with assembly to avoid redundant masking.
                assembly {
                    extraDataCasted := extraData
                }
                packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
                ERC721AStorage.layout()._packedOwnerships[index] = packed;
            }
            /**
             * @dev Called during each token transfer to set the 24bit `extraData` field.
             * Intended to be overridden by the cosumer contract.
             *
             * `previousExtraData` - the value of `extraData` before transfer.
             *
             * Calling conditions:
             *
             * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
             * transferred to `to`.
             * - When `from` is zero, `tokenId` will be minted for `to`.
             * - When `to` is zero, `tokenId` will be burned by `from`.
             * - `from` and `to` are never both zero.
             */
            function _extraData(
                address from,
                address to,
                uint24 previousExtraData
            ) internal view virtual returns (uint24) {}
            /**
             * @dev Returns the next extra data for the packed ownership data.
             * The returned result is shifted into position.
             */
            function _nextExtraData(
                address from,
                address to,
                uint256 prevOwnershipPacked
            ) private view returns (uint256) {
                uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
                return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
            }
            // =============================================================
            //                       OTHER OPERATIONS
            // =============================================================
            /**
             * @dev Returns the message sender (defaults to `msg.sender`).
             *
             * If you are writing GSN compatible contracts, you need to override this function.
             */
            function _msgSenderERC721A() internal view virtual returns (address) {
                return msg.sender;
            }
            /**
             * @dev Converts a uint256 to its ASCII string decimal representation.
             */
            function _toString(uint256 value) internal pure virtual returns (string memory str) {
                assembly {
                    // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                    // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                    // We will need 1 word for the trailing zeros padding, 1 word for the length,
                    // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                    let m := add(mload(0x40), 0xa0)
                    // Update the free memory pointer to allocate.
                    mstore(0x40, m)
                    // Assign the `str` to the end.
                    str := sub(m, 0x20)
                    // Zeroize the slot after the string.
                    mstore(str, 0)
                    // Cache the end of the memory to calculate the length later.
                    let end := str
                    // We write the string from rightmost digit to leftmost digit.
                    // The following is essentially a do-while loop that also handles the zero case.
                    // prettier-ignore
                    for { let temp := value } 1 {} {
                        str := sub(str, 1)
                        // Write the character to the pointer.
                        // The ASCII index of the '0' character is 48.
                        mstore8(str, add(48, mod(temp, 10)))
                        // Keep dividing `temp` until zero.
                        temp := div(temp, 10)
                        // prettier-ignore
                        if iszero(temp) { break }
                    }
                    let length := sub(end, str)
                    // Move the pointer 32 bytes leftwards to make room for the length.
                    str := sub(str, 0x20)
                    // Store the length.
                    mstore(str, length)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        import './IERC721AQueryableUpgradeable.sol';
        import '../ERC721AUpgradeable.sol';
        import '../ERC721A__Initializable.sol';
        /**
         * @title ERC721AQueryable.
         *
         * @dev ERC721A subclass with convenience query functions.
         */
        abstract contract ERC721AQueryableUpgradeable is
            ERC721A__Initializable,
            ERC721AUpgradeable,
            IERC721AQueryableUpgradeable
        {
            function __ERC721AQueryable_init() internal onlyInitializingERC721A {
                __ERC721AQueryable_init_unchained();
            }
            function __ERC721AQueryable_init_unchained() internal onlyInitializingERC721A {}
            /**
             * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
             *
             * If the `tokenId` is out of bounds:
             *
             * - `addr = address(0)`
             * - `startTimestamp = 0`
             * - `burned = false`
             * - `extraData = 0`
             *
             * If the `tokenId` is burned:
             *
             * - `addr = <Address of owner before token was burned>`
             * - `startTimestamp = <Timestamp when token was burned>`
             * - `burned = true`
             * - `extraData = <Extra data when token was burned>`
             *
             * Otherwise:
             *
             * - `addr = <Address of owner>`
             * - `startTimestamp = <Timestamp of start of ownership>`
             * - `burned = false`
             * - `extraData = <Extra data at start of ownership>`
             */
            function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
                TokenOwnership memory ownership;
                if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
                    return ownership;
                }
                ownership = _ownershipAt(tokenId);
                if (ownership.burned) {
                    return ownership;
                }
                return _ownershipOf(tokenId);
            }
            /**
             * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
             * See {ERC721AQueryable-explicitOwnershipOf}
             */
            function explicitOwnershipsOf(uint256[] calldata tokenIds)
                external
                view
                virtual
                override
                returns (TokenOwnership[] memory)
            {
                unchecked {
                    uint256 tokenIdsLength = tokenIds.length;
                    TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
                    for (uint256 i; i != tokenIdsLength; ++i) {
                        ownerships[i] = explicitOwnershipOf(tokenIds[i]);
                    }
                    return ownerships;
                }
            }
            /**
             * @dev Returns an array of token IDs owned by `owner`,
             * in the range [`start`, `stop`)
             * (i.e. `start <= tokenId < stop`).
             *
             * This function allows for tokens to be queried if the collection
             * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
             *
             * Requirements:
             *
             * - `start < stop`
             */
            function tokensOfOwnerIn(
                address owner,
                uint256 start,
                uint256 stop
            ) external view virtual override returns (uint256[] memory) {
                unchecked {
                    if (start >= stop) revert InvalidQueryRange();
                    uint256 tokenIdsIdx;
                    uint256 stopLimit = _nextTokenId();
                    // Set `start = max(start, _startTokenId())`.
                    if (start < _startTokenId()) {
                        start = _startTokenId();
                    }
                    // Set `stop = min(stop, stopLimit)`.
                    if (stop > stopLimit) {
                        stop = stopLimit;
                    }
                    uint256 tokenIdsMaxLength = balanceOf(owner);
                    // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
                    // to cater for cases where `balanceOf(owner)` is too big.
                    if (start < stop) {
                        uint256 rangeLength = stop - start;
                        if (rangeLength < tokenIdsMaxLength) {
                            tokenIdsMaxLength = rangeLength;
                        }
                    } else {
                        tokenIdsMaxLength = 0;
                    }
                    uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
                    if (tokenIdsMaxLength == 0) {
                        return tokenIds;
                    }
                    // We need to call `explicitOwnershipOf(start)`,
                    // because the slot at `start` may not be initialized.
                    TokenOwnership memory ownership = explicitOwnershipOf(start);
                    address currOwnershipAddr;
                    // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
                    // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
                    if (!ownership.burned) {
                        currOwnershipAddr = ownership.addr;
                    }
                    for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
                        ownership = _ownershipAt(i);
                        if (ownership.burned) {
                            continue;
                        }
                        if (ownership.addr != address(0)) {
                            currOwnershipAddr = ownership.addr;
                        }
                        if (currOwnershipAddr == owner) {
                            tokenIds[tokenIdsIdx++] = i;
                        }
                    }
                    // Downsize the array to fit.
                    assembly {
                        mstore(tokenIds, tokenIdsIdx)
                    }
                    return tokenIds;
                }
            }
            /**
             * @dev Returns an array of token IDs owned by `owner`.
             *
             * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
             * It is meant to be called off-chain.
             *
             * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
             * multiple smaller scans if the collection is large enough to cause
             * an out-of-gas error (10K collections should be fine).
             */
            function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
                unchecked {
                    uint256 tokenIdsIdx;
                    address currOwnershipAddr;
                    uint256 tokenIdsLength = balanceOf(owner);
                    uint256[] memory tokenIds = new uint256[](tokenIdsLength);
                    TokenOwnership memory ownership;
                    for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
                        ownership = _ownershipAt(i);
                        if (ownership.burned) {
                            continue;
                        }
                        if (ownership.addr != address(0)) {
                            currOwnershipAddr = ownership.addr;
                        }
                        if (currOwnershipAddr == owner) {
                            tokenIds[tokenIdsIdx++] = i;
                        }
                    }
                    return tokenIds;
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        import '../IERC721AUpgradeable.sol';
        /**
         * @dev Interface of ERC721AQueryable.
         */
        interface IERC721AQueryableUpgradeable is IERC721AUpgradeable {
            /**
             * Invalid query range (`start` >= `stop`).
             */
            error InvalidQueryRange();
            /**
             * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
             *
             * If the `tokenId` is out of bounds:
             *
             * - `addr = address(0)`
             * - `startTimestamp = 0`
             * - `burned = false`
             * - `extraData = 0`
             *
             * If the `tokenId` is burned:
             *
             * - `addr = <Address of owner before token was burned>`
             * - `startTimestamp = <Timestamp when token was burned>`
             * - `burned = true`
             * - `extraData = <Extra data when token was burned>`
             *
             * Otherwise:
             *
             * - `addr = <Address of owner>`
             * - `startTimestamp = <Timestamp of start of ownership>`
             * - `burned = false`
             * - `extraData = <Extra data at start of ownership>`
             */
            function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory);
            /**
             * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
             * See {ERC721AQueryable-explicitOwnershipOf}
             */
            function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory);
            /**
             * @dev Returns an array of token IDs owned by `owner`,
             * in the range [`start`, `stop`)
             * (i.e. `start <= tokenId < stop`).
             *
             * This function allows for tokens to be queried if the collection
             * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
             *
             * Requirements:
             *
             * - `start < stop`
             */
            function tokensOfOwnerIn(
                address owner,
                uint256 start,
                uint256 stop
            ) external view returns (uint256[] memory);
            /**
             * @dev Returns an array of token IDs owned by `owner`.
             *
             * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
             * It is meant to be called off-chain.
             *
             * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
             * multiple smaller scans if the collection is large enough to cause
             * an out-of-gas error (10K collections should be fine).
             */
            function tokensOfOwner(address owner) external view returns (uint256[] memory);
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        /**
         * @dev Interface of ERC721A.
         */
        interface IERC721AUpgradeable {
            /**
             * The caller must own the token or be an approved operator.
             */
            error ApprovalCallerNotOwnerNorApproved();
            /**
             * The token does not exist.
             */
            error ApprovalQueryForNonexistentToken();
            /**
             * Cannot query the balance for the zero address.
             */
            error BalanceQueryForZeroAddress();
            /**
             * Cannot mint to the zero address.
             */
            error MintToZeroAddress();
            /**
             * The quantity of tokens minted must be more than zero.
             */
            error MintZeroQuantity();
            /**
             * The token does not exist.
             */
            error OwnerQueryForNonexistentToken();
            /**
             * The caller must own the token or be an approved operator.
             */
            error TransferCallerNotOwnerNorApproved();
            /**
             * The token must be owned by `from`.
             */
            error TransferFromIncorrectOwner();
            /**
             * Cannot safely transfer to a contract that does not implement the
             * ERC721Receiver interface.
             */
            error TransferToNonERC721ReceiverImplementer();
            /**
             * Cannot transfer to the zero address.
             */
            error TransferToZeroAddress();
            /**
             * The token does not exist.
             */
            error URIQueryForNonexistentToken();
            /**
             * The `quantity` minted with ERC2309 exceeds the safety limit.
             */
            error MintERC2309QuantityExceedsLimit();
            /**
             * The `extraData` cannot be set on an unintialized ownership slot.
             */
            error OwnershipNotInitializedForExtraData();
            // =============================================================
            //                            STRUCTS
            // =============================================================
            struct TokenOwnership {
                // The address of the owner.
                address addr;
                // Stores the start time of ownership with minimal overhead for tokenomics.
                uint64 startTimestamp;
                // Whether the token has been burned.
                bool burned;
                // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
                uint24 extraData;
            }
            // =============================================================
            //                         TOKEN COUNTERS
            // =============================================================
            /**
             * @dev Returns the total number of tokens in existence.
             * Burned tokens will reduce the count.
             * To get the total number of tokens minted, please see {_totalMinted}.
             */
            function totalSupply() external view returns (uint256);
            // =============================================================
            //                            IERC165
            // =============================================================
            /**
             * @dev Returns true if this contract implements the interface defined by
             * `interfaceId`. See the corresponding
             * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
             * to learn more about how these ids are created.
             *
             * This function call must use less than 30000 gas.
             */
            function supportsInterface(bytes4 interfaceId) external view returns (bool);
            // =============================================================
            //                            IERC721
            // =============================================================
            /**
             * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
             */
            event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
            /**
             * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
             */
            event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
            /**
             * @dev Emitted when `owner` enables or disables
             * (`approved`) `operator` to manage all of its assets.
             */
            event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
            /**
             * @dev Returns the number of tokens in `owner`'s account.
             */
            function balanceOf(address owner) external view returns (uint256 balance);
            /**
             * @dev Returns the owner of the `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function ownerOf(uint256 tokenId) external view returns (address owner);
            /**
             * @dev Safely transfers `tokenId` token from `from` to `to`,
             * checking first that contract recipients are aware of the ERC721 protocol
             * to prevent tokens from being forever locked.
             *
             * Requirements:
             *
             * - `from` cannot be the zero address.
             * - `to` cannot be the zero address.
             * - `tokenId` token must exist and be owned by `from`.
             * - If the caller is not `from`, it must be have been allowed to move
             * this token by either {approve} or {setApprovalForAll}.
             * - If `to` refers to a smart contract, it must implement
             * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
             *
             * Emits a {Transfer} event.
             */
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId,
                bytes calldata data
            ) external payable;
            /**
             * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
             */
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
            ) external payable;
            /**
             * @dev Transfers `tokenId` from `from` to `to`.
             *
             * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
             * whenever possible.
             *
             * Requirements:
             *
             * - `from` cannot be the zero address.
             * - `to` cannot be the zero address.
             * - `tokenId` token must be owned by `from`.
             * - If the caller is not `from`, it must be approved to move this token
             * by either {approve} or {setApprovalForAll}.
             *
             * Emits a {Transfer} event.
             */
            function transferFrom(
                address from,
                address to,
                uint256 tokenId
            ) external payable;
            /**
             * @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 payable;
            /**
             * @dev Approve or remove `operator` as an operator for the caller.
             * Operators can call {transferFrom} or {safeTransferFrom}
             * for any token owned by the caller.
             *
             * Requirements:
             *
             * - The `operator` cannot be the caller.
             *
             * Emits an {ApprovalForAll} event.
             */
            function setApprovalForAll(address operator, bool _approved) external;
            /**
             * @dev Returns the account approved for `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function getApproved(uint256 tokenId) external view returns (address operator);
            /**
             * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
             *
             * See {setApprovalForAll}.
             */
            function isApprovedForAll(address owner, address operator) external view returns (bool);
            // =============================================================
            //                        IERC721Metadata
            // =============================================================
            /**
             * @dev Returns the token collection name.
             */
            function name() external view returns (string memory);
            /**
             * @dev Returns the token collection symbol.
             */
            function symbol() external view returns (string memory);
            /**
             * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
             */
            function tokenURI(uint256 tokenId) external view returns (string memory);
            // =============================================================
            //                           IERC2309
            // =============================================================
            /**
             * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
             * (inclusive) is transferred from `from` to `to`, as defined in the
             * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
             *
             * See {_mintERC2309} for more details.
             */
            event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.13;
        interface IOperatorFilterRegistry {
            function isOperatorAllowed(address registrant, address operator) external view returns (bool);
            function register(address registrant) external;
            function registerAndSubscribe(address registrant, address subscription) external;
            function registerAndCopyEntries(address registrant, address registrantToCopy) external;
            function unregister(address addr) external;
            function updateOperator(address registrant, address operator, bool filtered) external;
            function updateOperators(address registrant, address[] calldata operators, bool filtered) external;
            function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;
            function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;
            function subscribe(address registrant, address registrantToSubscribe) external;
            function unsubscribe(address registrant, bool copyExistingEntries) external;
            function subscriptionOf(address addr) external returns (address registrant);
            function subscribers(address registrant) external returns (address[] memory);
            function subscriberAt(address registrant, uint256 index) external returns (address);
            function copyEntriesOf(address registrant, address registrantToCopy) external;
            function isOperatorFiltered(address registrant, address operator) external returns (bool);
            function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);
            function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);
            function filteredOperators(address addr) external returns (address[] memory);
            function filteredCodeHashes(address addr) external returns (bytes32[] memory);
            function filteredOperatorAt(address registrant, uint256 index) external returns (address);
            function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);
            function isRegistered(address addr) external returns (bool);
            function codeHashOf(address addr) external returns (bytes32);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.13;
        import {IOperatorFilterRegistry} from "../IOperatorFilterRegistry.sol";
        import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
        abstract contract OperatorFiltererUpgradeable is Initializable {
            error OperatorNotAllowed(address operator);
            IOperatorFilterRegistry constant operatorFilterRegistry =
                IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);
            function __OperatorFilterer_init(address subscriptionOrRegistrantToCopy, bool subscribe)
                internal
                onlyInitializing
            {
                // If an inheriting token contract is deployed to a network without the registry deployed, the modifier
                // will not revert, but the contract will need to be registered with the registry once it is deployed in
                // order for the modifier to filter addresses.
                if (address(operatorFilterRegistry).code.length > 0) {
                    if (!operatorFilterRegistry.isRegistered(address(this))) {
                        if (subscribe) {
                            operatorFilterRegistry.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);
                        } else {
                            if (subscriptionOrRegistrantToCopy != address(0)) {
                                operatorFilterRegistry.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);
                            } else {
                                operatorFilterRegistry.register(address(this));
                            }
                        }
                    }
                }
            }
            modifier onlyAllowedOperator(address from) virtual {
                // Check registry code length to facilitate testing in environments without a deployed registry.
                if (address(operatorFilterRegistry).code.length > 0) {
                    // Allow spending tokens from addresses with balance
                    // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred
                    // from an EOA.
                    if (from == msg.sender) {
                        _;
                        return;
                    }
                    if (!operatorFilterRegistry.isOperatorAllowed(address(this), msg.sender)) {
                        revert OperatorNotAllowed(msg.sender);
                    }
                }
                _;
            }
            modifier onlyAllowedOperatorApproval(address operator) virtual {
                // Check registry code length to facilitate testing in environments without a deployed registry.
                if (address(operatorFilterRegistry).code.length > 0) {
                    if (!operatorFilterRegistry.isOperatorAllowed(address(this), operator)) {
                        revert OperatorNotAllowed(operator);
                    }
                }
                _;
            }
        }
        

        File 2 of 4: GnosisSafeProxy
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        
        /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
        /// @author Richard Meissner - <richard@gnosis.io>
        interface IProxy {
            function masterCopy() external view returns (address);
        }
        
        /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
        /// @author Stefan George - <stefan@gnosis.io>
        /// @author Richard Meissner - <richard@gnosis.io>
        contract GnosisSafeProxy {
            // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
            // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
            address internal singleton;
        
            /// @dev Constructor function sets address of singleton contract.
            /// @param _singleton Singleton address.
            constructor(address _singleton) {
                require(_singleton != address(0), "Invalid singleton address provided");
                singleton = _singleton;
            }
        
            /// @dev Fallback function forwards all transactions and returns all received return data.
            fallback() external payable {
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                    // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                    if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                        mstore(0, _singleton)
                        return(0, 0x20)
                    }
                    calldatacopy(0, 0, calldatasize())
                    let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                    returndatacopy(0, 0, returndatasize())
                    if eq(success, 0) {
                        revert(0, returndatasize())
                    }
                    return(0, returndatasize())
                }
            }
        }
        
        /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
        /// @author Stefan George - <stefan@gnosis.pm>
        contract GnosisSafeProxyFactory {
            event ProxyCreation(GnosisSafeProxy proxy, address singleton);
        
            /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
            /// @param singleton Address of singleton contract.
            /// @param data Payload for message call sent to new proxy contract.
            function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
                proxy = new GnosisSafeProxy(singleton);
                if (data.length > 0)
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                            revert(0, 0)
                        }
                    }
                emit ProxyCreation(proxy, singleton);
            }
        
            /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
            function proxyRuntimeCode() public pure returns (bytes memory) {
                return type(GnosisSafeProxy).runtimeCode;
            }
        
            /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
            function proxyCreationCode() public pure returns (bytes memory) {
                return type(GnosisSafeProxy).creationCode;
            }
        
            /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
            ///      This method is only meant as an utility to be called from other methods
            /// @param _singleton Address of singleton contract.
            /// @param initializer Payload for message call sent to new proxy contract.
            /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
            function deployProxyWithNonce(
                address _singleton,
                bytes memory initializer,
                uint256 saltNonce
            ) internal returns (GnosisSafeProxy proxy) {
                // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
                bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
                bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
                }
                require(address(proxy) != address(0), "Create2 call failed");
            }
        
            /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
            /// @param _singleton Address of singleton contract.
            /// @param initializer Payload for message call sent to new proxy contract.
            /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
            function createProxyWithNonce(
                address _singleton,
                bytes memory initializer,
                uint256 saltNonce
            ) public returns (GnosisSafeProxy proxy) {
                proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                if (initializer.length > 0)
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                            revert(0, 0)
                        }
                    }
                emit ProxyCreation(proxy, _singleton);
            }
        
            /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
            /// @param _singleton Address of singleton contract.
            /// @param initializer Payload for message call sent to new proxy contract.
            /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
            /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
            function createProxyWithCallback(
                address _singleton,
                bytes memory initializer,
                uint256 saltNonce,
                IProxyCreationCallback callback
            ) public returns (GnosisSafeProxy proxy) {
                uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
                proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
                if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
            }
        
            /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
            ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
            ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
            /// @param _singleton Address of singleton contract.
            /// @param initializer Payload for message call sent to new proxy contract.
            /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
            function calculateCreateProxyWithNonceAddress(
                address _singleton,
                bytes calldata initializer,
                uint256 saltNonce
            ) external returns (GnosisSafeProxy proxy) {
                proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                revert(string(abi.encodePacked(proxy)));
            }
        }
        
        interface IProxyCreationCallback {
            function proxyCreated(
                GnosisSafeProxy proxy,
                address _singleton,
                bytes calldata initializer,
                uint256 saltNonce
            ) external;
        }

        File 3 of 4: Bueno721Drop
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/ContextUpgradeable.sol";
        import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            function __Ownable_init() internal onlyInitializing {
                __Ownable_init_unchained();
            }
            function __Ownable_init_unchained() internal onlyInitializing {
                _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);
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[49] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (finance/PaymentSplitter.sol)
        pragma solidity ^0.8.0;
        import "../token/ERC20/utils/SafeERC20Upgradeable.sol";
        import "../utils/AddressUpgradeable.sol";
        import "../utils/ContextUpgradeable.sol";
        import "../proxy/utils/Initializable.sol";
        /**
         * @title PaymentSplitter
         * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
         * that the Ether will be split in this way, since it is handled transparently by the contract.
         *
         * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
         * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
         * an amount proportional to the percentage of total shares they were assigned. The distribution of shares is set at the
         * time of contract deployment and can't be updated thereafter.
         *
         * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
         * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
         * function.
         *
         * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
         * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
         * to run tests before sending real value to this contract.
         */
        contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
            event PayeeAdded(address account, uint256 shares);
            event PaymentReleased(address to, uint256 amount);
            event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount);
            event PaymentReceived(address from, uint256 amount);
            uint256 private _totalShares;
            uint256 private _totalReleased;
            mapping(address => uint256) private _shares;
            mapping(address => uint256) private _released;
            address[] private _payees;
            mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased;
            mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released;
            /**
             * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
             * the matching position in the `shares` array.
             *
             * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
             * duplicates in `payees`.
             */
            function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal onlyInitializing {
                __PaymentSplitter_init_unchained(payees, shares_);
            }
            function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal onlyInitializing {
                require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
                require(payees.length > 0, "PaymentSplitter: no payees");
                for (uint256 i = 0; i < payees.length; i++) {
                    _addPayee(payees[i], shares_[i]);
                }
            }
            /**
             * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
             * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
             * reliability of the events, and not the actual splitting of Ether.
             *
             * To learn more about this see the Solidity documentation for
             * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
             * functions].
             */
            receive() external payable virtual {
                emit PaymentReceived(_msgSender(), msg.value);
            }
            /**
             * @dev Getter for the total shares held by payees.
             */
            function totalShares() public view returns (uint256) {
                return _totalShares;
            }
            /**
             * @dev Getter for the total amount of Ether already released.
             */
            function totalReleased() public view returns (uint256) {
                return _totalReleased;
            }
            /**
             * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
             * contract.
             */
            function totalReleased(IERC20Upgradeable token) public view returns (uint256) {
                return _erc20TotalReleased[token];
            }
            /**
             * @dev Getter for the amount of shares held by an account.
             */
            function shares(address account) public view returns (uint256) {
                return _shares[account];
            }
            /**
             * @dev Getter for the amount of Ether already released to a payee.
             */
            function released(address account) public view returns (uint256) {
                return _released[account];
            }
            /**
             * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
             * IERC20 contract.
             */
            function released(IERC20Upgradeable token, address account) public view returns (uint256) {
                return _erc20Released[token][account];
            }
            /**
             * @dev Getter for the address of the payee number `index`.
             */
            function payee(uint256 index) public view returns (address) {
                return _payees[index];
            }
            /**
             * @dev Getter for the amount of payee's releasable Ether.
             */
            function releasable(address account) public view returns (uint256) {
                uint256 totalReceived = address(this).balance + totalReleased();
                return _pendingPayment(account, totalReceived, released(account));
            }
            /**
             * @dev Getter for the amount of payee's releasable `token` tokens. `token` should be the address of an
             * IERC20 contract.
             */
            function releasable(IERC20Upgradeable token, address account) public view returns (uint256) {
                uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
                return _pendingPayment(account, totalReceived, released(token, account));
            }
            /**
             * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
             * total shares and their previous withdrawals.
             */
            function release(address payable account) public virtual {
                require(_shares[account] > 0, "PaymentSplitter: account has no shares");
                uint256 payment = releasable(account);
                require(payment != 0, "PaymentSplitter: account is not due payment");
                // _totalReleased is the sum of all values in _released.
                // If "_totalReleased += payment" does not overflow, then "_released[account] += payment" cannot overflow.
                _totalReleased += payment;
                unchecked {
                    _released[account] += payment;
                }
                AddressUpgradeable.sendValue(account, payment);
                emit PaymentReleased(account, payment);
            }
            /**
             * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
             * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
             * contract.
             */
            function release(IERC20Upgradeable token, address account) public virtual {
                require(_shares[account] > 0, "PaymentSplitter: account has no shares");
                uint256 payment = releasable(token, account);
                require(payment != 0, "PaymentSplitter: account is not due payment");
                // _erc20TotalReleased[token] is the sum of all values in _erc20Released[token].
                // If "_erc20TotalReleased[token] += payment" does not overflow, then "_erc20Released[token][account] += payment"
                // cannot overflow.
                _erc20TotalReleased[token] += payment;
                unchecked {
                    _erc20Released[token][account] += payment;
                }
                SafeERC20Upgradeable.safeTransfer(token, account, payment);
                emit ERC20PaymentReleased(token, account, payment);
            }
            /**
             * @dev internal logic for computing the pending payment of an `account` given the token historical balances and
             * already released amounts.
             */
            function _pendingPayment(
                address account,
                uint256 totalReceived,
                uint256 alreadyReleased
            ) private view returns (uint256) {
                return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
            }
            /**
             * @dev Add a new payee to the contract.
             * @param account The address of the payee to add.
             * @param shares_ The number of shares owned by the payee.
             */
            function _addPayee(address account, uint256 shares_) private {
                require(account != address(0), "PaymentSplitter: account is the zero address");
                require(shares_ > 0, "PaymentSplitter: shares are 0");
                require(_shares[account] == 0, "PaymentSplitter: account already has shares");
                _payees.push(account);
                _shares[account] = shares_;
                _totalShares = _totalShares + shares_;
                emit PayeeAdded(account, shares_);
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[43] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
        pragma solidity ^0.8.0;
        import "../utils/introspection/IERC165Upgradeable.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 IERC2981Upgradeable is IERC165Upgradeable {
            /**
             * @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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/AddressUpgradeable.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * contract MyToken is ERC20Upgradeable {
         *     function initialize() initializer public {
         *         __ERC20_init("MyToken", "MTK");
         *     }
         * }
         * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
         *     function initializeV2() reinitializer(2) public {
         *         __ERC20Permit_init("MyToken");
         *     }
         * }
         * ```
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         *
         * [CAUTION]
         * ====
         * Avoid leaving a contract uninitialized.
         *
         * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
         * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
         * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * /// @custom:oz-upgrades-unsafe-allow constructor
         * constructor() {
         *     _disableInitializers();
         * }
         * ```
         * ====
         */
        abstract contract Initializable {
            /**
             * @dev Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts.
             *
             * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
             * constructor.
             *
             * Emits an {Initialized} event.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * A reinitializer may be used after the original initialization step. This is essential to configure modules that
             * are added through upgrades and that require initialization.
             *
             * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
             * cannot be nested. If one is invoked in the context of another, execution will revert.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             *
             * WARNING: setting the version to 255 will prevent any future reinitialization.
             *
             * Emits an {Initialized} event.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             *
             * Emits an {Initialized} event the first time it is successfully executed.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized < type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
            /**
             * @dev Internal function that returns the initialized version. Returns `_initialized`
             */
            function _getInitializedVersion() internal view returns (uint8) {
                return _initialized;
            }
            /**
             * @dev Internal function that returns the initialized version. Returns `_initializing`
             */
            function _isInitializing() internal view returns (bool) {
                return _initializing;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
        pragma solidity ^0.8.0;
        import "../../interfaces/IERC2981Upgradeable.sol";
        import "../../utils/introspection/ERC165Upgradeable.sol";
        import "../../proxy/utils/Initializable.sol";
        /**
         * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
         *
         * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
         * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
         *
         * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
         * fee is specified in basis points by default.
         *
         * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
         * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
         * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
         *
         * _Available since v4.5._
         */
        abstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
            function __ERC2981_init() internal onlyInitializing {
            }
            function __ERC2981_init_unchained() internal onlyInitializing {
            }
            struct RoyaltyInfo {
                address receiver;
                uint96 royaltyFraction;
            }
            RoyaltyInfo private _defaultRoyaltyInfo;
            mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
            /**
             * @dev See {IERC165-supportsInterface}.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {
                return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId);
            }
            /**
             * @inheritdoc IERC2981Upgradeable
             */
            function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
                RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
                if (royalty.receiver == address(0)) {
                    royalty = _defaultRoyaltyInfo;
                }
                uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
                return (royalty.receiver, royaltyAmount);
            }
            /**
             * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
             * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
             * override.
             */
            function _feeDenominator() internal pure virtual returns (uint96) {
                return 10000;
            }
            /**
             * @dev Sets the royalty information that all ids in this contract will default to.
             *
             * Requirements:
             *
             * - `receiver` cannot be the zero address.
             * - `feeNumerator` cannot be greater than the fee denominator.
             */
            function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
                require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                require(receiver != address(0), "ERC2981: invalid receiver");
                _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
            }
            /**
             * @dev Removes default royalty information.
             */
            function _deleteDefaultRoyalty() internal virtual {
                delete _defaultRoyaltyInfo;
            }
            /**
             * @dev Sets the royalty information for a specific token id, overriding the global default.
             *
             * Requirements:
             *
             * - `receiver` cannot be the zero address.
             * - `feeNumerator` cannot be greater than the fee denominator.
             */
            function _setTokenRoyalty(
                uint256 tokenId,
                address receiver,
                uint96 feeNumerator
            ) internal virtual {
                require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                require(receiver != address(0), "ERC2981: Invalid parameters");
                _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
            }
            /**
             * @dev Resets royalty information for the token id back to the global default.
             */
            function _resetTokenRoyalty(uint256 tokenId) internal virtual {
                delete _tokenRoyaltyInfo[tokenId];
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[48] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
         * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
         *
         * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
         * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
         * need to send a transaction, and thus is not required to hold Ether at all.
         */
        interface IERC20PermitUpgradeable {
            /**
             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
             * given ``owner``'s signed approval.
             *
             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
             * ordering also apply here.
             *
             * Emits an {Approval} event.
             *
             * Requirements:
             *
             * - `spender` cannot be the zero address.
             * - `deadline` must be a timestamp in the future.
             * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
             * over the EIP712-formatted function arguments.
             * - the signature must use ``owner``'s current nonce (see {nonces}).
             *
             * For more information on the signature format, see the
             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
             * section].
             */
            function permit(
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) external;
            /**
             * @dev Returns the current nonce for `owner`. This value must be
             * included whenever a signature is generated for {permit}.
             *
             * Every successful call to {permit} increases ``owner``'s nonce by one. This
             * prevents a signature from being used multiple times.
             */
            function nonces(address owner) external view returns (uint256);
            /**
             * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
             */
            // solhint-disable-next-line func-name-mixedcase
            function DOMAIN_SEPARATOR() external view returns (bytes32);
        }
        // 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 IERC20Upgradeable {
            /**
             * @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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
        pragma solidity ^0.8.0;
        import "../IERC20Upgradeable.sol";
        import "../extensions/draft-IERC20PermitUpgradeable.sol";
        import "../../../utils/AddressUpgradeable.sol";
        /**
         * @title SafeERC20
         * @dev Wrappers around ERC20 operations that throw on failure (when the token
         * contract returns false). Tokens that return no value (and instead revert or
         * throw on failure) are also supported, non-reverting calls are assumed to be
         * successful.
         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
         */
        library SafeERC20Upgradeable {
            using AddressUpgradeable for address;
            function safeTransfer(
                IERC20Upgradeable token,
                address to,
                uint256 value
            ) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
            }
            function safeTransferFrom(
                IERC20Upgradeable token,
                address from,
                address to,
                uint256 value
            ) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
            }
            /**
             * @dev Deprecated. This function has issues similar to the ones found in
             * {IERC20-approve}, and its usage is discouraged.
             *
             * Whenever possible, use {safeIncreaseAllowance} and
             * {safeDecreaseAllowance} instead.
             */
            function safeApprove(
                IERC20Upgradeable token,
                address spender,
                uint256 value
            ) internal {
                // safeApprove should only be called when setting an initial allowance,
                // or when resetting it to zero. To increase and decrease it, use
                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                require(
                    (value == 0) || (token.allowance(address(this), spender) == 0),
                    "SafeERC20: approve from non-zero to non-zero allowance"
                );
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
            }
            function safeIncreaseAllowance(
                IERC20Upgradeable token,
                address spender,
                uint256 value
            ) internal {
                uint256 newAllowance = token.allowance(address(this), spender) + value;
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
            function safeDecreaseAllowance(
                IERC20Upgradeable token,
                address spender,
                uint256 value
            ) internal {
                unchecked {
                    uint256 oldAllowance = token.allowance(address(this), spender);
                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                    uint256 newAllowance = oldAllowance - value;
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                }
            }
            function safePermit(
                IERC20PermitUpgradeable token,
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) internal {
                uint256 nonceBefore = token.nonces(owner);
                token.permit(owner, spender, value, deadline, v, r, s);
                uint256 nonceAfter = token.nonces(owner);
                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
            }
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             */
            function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                // the target address contains contract code and also asserts for success in the low-level call.
                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                if (returndata.length > 0) {
                    // Return data is optional
                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library AddressUpgradeable {
            /**
             * @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 functionCallWithValue(target, data, 0, "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");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, 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) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or 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 {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // 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);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
        pragma solidity ^0.8.0;
        import "../proxy/utils/Initializable.sol";
        /**
         * @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 ContextUpgradeable is Initializable {
            function __Context_init() internal onlyInitializing {
            }
            function __Context_init_unchained() internal onlyInitializing {
            }
            function _msgSender() internal view virtual returns (address) {
                return msg.sender;
            }
            function _msgData() internal view virtual returns (bytes calldata) {
                return msg.data;
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[50] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
        pragma solidity ^0.8.0;
        import "./IERC165Upgradeable.sol";
        import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
            function __ERC165_init() internal onlyInitializing {
            }
            function __ERC165_init_unchained() internal onlyInitializing {
            }
            /**
             * @dev See {IERC165-supportsInterface}.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                return interfaceId == type(IERC165Upgradeable).interfaceId;
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[50] private __gap;
        }
        // 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 IERC165Upgradeable {
            /**
             * @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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev These functions deal with verification of Merkle Tree proofs.
         *
         * The tree and the proofs can be generated using our
         * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
         * You will find a quickstart guide in the readme.
         *
         * 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.
         * OpenZeppelin's JavaScript library generates merkle trees that are safe
         * against this attack out of the box.
         */
        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 simultaneously proven to be a part of a merkle tree defined by
             * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
             *
             * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
             *
             * _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}
             *
             * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
             *
             * _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 sibling nodes in `proof`. The reconstruction
             * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
             * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
             * respectively.
             *
             * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
             * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
             * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
             *
             * _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}.
             *
             * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
             *
             * _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)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.17;
        import "erc721a-upgradeable/contracts/extensions/ERC721AQueryableUpgradeable.sol";
        import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
        import "@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol";
        import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
        import "@openzeppelin/contracts-upgradeable/finance/PaymentSplitterUpgradeable.sol";
        import "operator-filter-registry/src/upgradeable/OperatorFiltererUpgradeable.sol";
        import "./ICommon.sol";
        struct PhaseSettings {
            /// @dev phase supply. This can be released to public by ending the phase.
            uint64 maxSupply;
            /// @dev tracks the total amount minted in the phase
            uint64 amountMinted;
            /// @dev wallet maximum for the phase
            uint64 maxPerWallet;
            /// @dev merkle root for the phase (if applicable, otherwise bytes32(0))
            bytes32 merkleRoot;
            /// @dev whether the phase is active
            bool isActive;
            /// @dev price for the phase (or free if 0)
            uint256 price;
        }
        struct BaseSettings {
            /// @dev public sale supply. ending a phase will carry supply into this value
            uint64 maxSupply;
            /// @dev global wallet maximum across all phases (including public)
            uint64 maxPerWallet;
            /// @dev tracks the total amount minted in the public sale
            uint64 amountMinted;
            /// @dev price for the public sale (or free if 0)
            uint256 price;
        }
        struct SaleState {
            uint64 numPhases;
            mapping(uint256 => PhaseSettings) phases;
        }
        error PhaseNotActive();
        error InvalidPhase();
        /// @author Bueno.art
        /// @title ERC-721 Multi-Phase Drop Contract
        contract Bueno721Drop is
            ERC721AQueryableUpgradeable,
            OwnableUpgradeable,
            ERC2981Upgradeable,
            PaymentSplitterUpgradeable,
            OperatorFiltererUpgradeable
        {
            string public _baseTokenURI;
            SaleState public saleState;
            BaseSettings public baseSettings;
            uint256 public maxSupply;
            address[] public withdrawAddresses;
            mapping(address => mapping(uint256 => uint64)) private amountMintedForPhase;
            bool public isPublicActive;
            bool private allowBurning;
            event TokensMinted(address indexed to, uint256 quantity);
            event TokenBurned(address indexed owner, uint256 tokenId);
            event TokensAirdropped(uint256 numRecipients, uint256 numTokens);
            event PhasesActivated(uint256[] phaseIds, bool activatedPublic);
            event PhasesPaused(uint256[] phaseIds, bool pausedPublic);
            event PhaseEnded(uint256 phaseIds);
            event BurnStatusChanged(bool burnActive);
            event PhaseSettingsUpdated(uint256 phaseId, PhaseSettings settings);
            event BaseSettingsUpdated(BaseSettings settings);
            event BaseURIUpdated(string baseURI);
            event RoyaltyUpdated(address royaltyAddress, uint96 royaltyAmount);
            /// @custom:oz-upgrades-unsafe-allow constructor
            constructor() {
                _disableInitializers();
            }
            function initialize(
                string memory _name,
                string memory _symbol,
                string memory _baseUri,
                RoyaltySettings calldata _royaltySettings,
                PhaseSettings[] calldata _phases,
                BaseSettings calldata _baseSettings,
                PaymentSplitterSettings calldata _paymentSplitterSettings,
                uint256 _maxIntendedSupply,
                bool _allowBurning,
                address _deployer,
                address _operatorFilter
            ) public initializerERC721A initializer {
                __ERC721A_init(_name, _symbol);
                __Ownable_init();
                __PaymentSplitter_init(
                    _paymentSplitterSettings.payees,
                    _paymentSplitterSettings.shares
                );
                uint64 numPhases = uint64(_phases.length);
                uint256 supplyValidationCount = _baseSettings.maxSupply;
                for (uint256 i = 0; i < numPhases; ) {
                    saleState.phases[i] = _phases[i];
                    supplyValidationCount += _phases[i].maxSupply;
                    // numPhases has a maximum value of 2^64 - 1
                    unchecked {
                        ++i;
                    }
                }
                require(
                    supplyValidationCount == _maxIntendedSupply,
                    "Supply of all phases must equal maxIntendedSupply"
                );
                _baseTokenURI = _baseUri;
                withdrawAddresses = _paymentSplitterSettings.payees;
                saleState.numPhases = numPhases;
                baseSettings = _baseSettings;
                allowBurning = _allowBurning;
                maxSupply = _maxIntendedSupply;
                _setDefaultRoyalty(
                    _royaltySettings.royaltyAddress,
                    _royaltySettings.royaltyAmount
                );
                transferOwnership(_deployer);
                OperatorFiltererUpgradeable.__OperatorFilterer_init(
                    _operatorFilter,
                    _operatorFilter == address(0) ? false : true // only subscribe if a filter is provided
                );
            }
            // ========= EXTERNAL MINTING METHODS =========
            /**
             * @notice Mint tokens for an allowlisted phase
             * @dev Calling this function for a phase that doesn't have an allowlist will fail
             */
            function mintPhaseAllowlist(
                uint256 phaseIndex,
                uint64 quantity,
                bytes32[] calldata proof
            ) external payable {
                uint64 updatedAmountMinted = _checkAllowlistPhaseMintConditions(
                    msg.sender,
                    quantity,
                    proof,
                    phaseIndex,
                    msg.value
                );
                _checkGlobalPerWalletMax(msg.sender, quantity);
                saleState.phases[phaseIndex].amountMinted += quantity;
                amountMintedForPhase[msg.sender][phaseIndex] = updatedAmountMinted;
                _mint(msg.sender, quantity);
                emit TokensMinted(msg.sender, quantity);
            }
            /**
             * @notice Mint tokens for a non-allowlist phase.
             * @dev Calling this function for a phase that has an allowlist will fail
             */
            function mintPhase(uint256 phaseIndex, uint64 quantity) external payable {
                uint64 updatedAmountMinted = _checkPhaseMintConditions(
                    msg.sender,
                    quantity,
                    phaseIndex,
                    msg.value
                );
                _checkGlobalPerWalletMax(msg.sender, quantity);
                saleState.phases[phaseIndex].amountMinted += quantity;
                amountMintedForPhase[msg.sender][phaseIndex] = updatedAmountMinted;
                _mint(msg.sender, quantity);
                emit TokensMinted(msg.sender, quantity);
            }
            /**
             * @notice Mint tokens in the public sale
             */
            function mintPublic(uint64 quantity) external payable {
                uint64 updatedAmountMinted = _checkPublicMintConditions(
                    quantity,
                    msg.value
                );
                _checkGlobalPerWalletMax(msg.sender, quantity);
                baseSettings.amountMinted = updatedAmountMinted;
                _mint(msg.sender, quantity);
                emit TokensMinted(msg.sender, quantity);
            }
            /**
             * @notice Mint tokens in all possible phases (including public sale)
             */
            function mintBatch(
                uint64[] calldata quantities,
                bytes32[][] calldata proofs,
                uint256[] calldata phaseIndices,
                uint64 publicQuantity
            ) external payable {
                uint256 phaseLength = phaseIndices.length;
                if (
                    phaseLength > saleState.numPhases ||
                    phaseLength != quantities.length ||
                    phaseLength != proofs.length
                ) {
                    revert InvalidPhase();
                }
                uint256 balance = msg.value;
                uint256 quantityToMint;
                for (uint256 i = 0; i < phaseLength; ) {
                    uint64 updatedAmount;
                    uint256 phaseIndex = phaseIndices[i];
                    uint64 quantity = quantities[i];
                    bytes32[] calldata proof = proofs[i];
                    PhaseSettings storage phase = saleState.phases[phaseIndex];
                    uint256 priceForPhase = phase.price * quantity;
                    // Since price is strictly checked in the _check* functions below,
                    // we have an additional check here to ensure that the balance doesn't underflow
                    if (balance < priceForPhase) {
                        revert InvalidPrice();
                    }
                    // if the phase has no allowlist, the merkleRoot will be zeroed out.
                    if (phase.merkleRoot == bytes32(0)) {
                        updatedAmount = _checkPhaseMintConditions(
                            msg.sender,
                            quantity,
                            phaseIndex,
                            priceForPhase
                        );
                    } else {
                        updatedAmount = _checkAllowlistPhaseMintConditions(
                            msg.sender,
                            quantity,
                            proof,
                            phaseIndex,
                            priceForPhase
                        );
                    }
                    // quantity & phaseLength have a maximum value of 2^64 - 1
                    // balance underflow is checked above
                    unchecked {
                        saleState.phases[phaseIndex].amountMinted += quantity;
                        amountMintedForPhase[msg.sender][phaseIndex] = updatedAmount;
                        balance -= priceForPhase;
                        quantityToMint += quantity;
                        ++i;
                    }
                }
                uint256 totalMintQuantity = quantityToMint;
                if (publicQuantity > 0) {
                    _checkPublicMintConditions(publicQuantity, balance);
                    // publicQuantity has a max value of 2^64 - 1
                    unchecked {
                        baseSettings.amountMinted += publicQuantity;
                        totalMintQuantity += publicQuantity;
                    }
                }
                _checkGlobalPerWalletMax(msg.sender, totalMintQuantity);
                _mint(msg.sender, totalMintQuantity);
                emit TokensMinted(msg.sender, totalMintQuantity);
            }
            /**
             * @notice Burn a token, if the contract allows for it
             */
            function burn(uint256 tokenId) external {
                if (!allowBurning) {
                    revert BurningNotAllowed();
                }
                _burn(tokenId, true);
                emit TokenBurned(msg.sender, tokenId);
            }
            // ========= OWNER METHODS =========
            /**
             * @notice Perform a batch airdrop for a particular phase.
             * @dev Minted tokens are pulled from the phase that is specified in the airdropper.
             */
            function airdropForPhase(
                uint256 phaseIndex,
                uint64[] calldata quantities,
                address[] calldata recipients
            ) external onlyOwner {
                uint256 numRecipients = recipients.length;
                uint256 totalAirdropped;
                if (numRecipients != quantities.length) revert InvalidAirdrop();
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                for (uint256 i = 0; i < numRecipients; ) {
                    uint64 updatedAmountMinted = phase.amountMinted + quantities[i];
                    if (updatedAmountMinted > phase.maxSupply) {
                        revert SoldOut();
                    }
                    // airdrops are not subject to the per-wallet mint limits,
                    // but we track how much is minted for the phase
                    phase.amountMinted = updatedAmountMinted;
                    totalAirdropped += quantities[i];
                    _mint(recipients[i], quantities[i]);
                    // numRecipients has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                emit TokensAirdropped(numRecipients, totalAirdropped);
            }
            /**
             * @notice Perform a batch airdrop for the public phase.
             * @dev Minted tokens are pulled from the public phase.
             */
            function airdropPublic(
                uint64[] calldata quantities,
                address[] calldata recipients
            ) external onlyOwner {
                uint256 numRecipients = recipients.length;
                uint256 totalAirdropped;
                if (numRecipients != quantities.length) revert InvalidAirdrop();
                for (uint256 i = 0; i < numRecipients; ) {
                    uint64 updatedAmountMinted = baseSettings.amountMinted +
                        quantities[i];
                    if (updatedAmountMinted > baseSettings.maxSupply) {
                        revert SoldOut();
                    }
                    // airdrops are not subject to the per-wallet mint limits,
                    // but we track how much is minted for the phase
                    baseSettings.amountMinted = updatedAmountMinted;
                    totalAirdropped += quantities[i];
                    _mint(recipients[i], quantities[i]);
                    // numRecipients has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                emit TokensAirdropped(numRecipients, totalAirdropped);
            }
            /**
             * @notice Specify which phases are active.
             * Public sale can be activated by setting `activatePublic` to true.
             */
            function activatePhases(
                uint256[] calldata phaseIndices,
                bool activatePublic
            ) external onlyOwner {
                uint256 numPhases = phaseIndices.length;
                // activate all the phases provided in phaseIndices
                for (uint256 i = 0; i < numPhases; ) {
                    uint256 phaseIndex = phaseIndices[i];
                    if (phaseIndex >= saleState.numPhases) {
                        // phaseIndex is out of bounds
                        revert InvalidPhase();
                    }
                    saleState.phases[phaseIndices[i]].isActive = true;
                    // numPhases has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                // calling this function with activatePublic=false only indicates the public sale
                // is not intended to be activated, but it does not pause it.
                if (activatePublic) {
                    isPublicActive = true;
                }
                emit PhasesActivated(phaseIndices, activatePublic);
            }
            /**
             * @notice Specify which phases are inactive (paused).
             * Public sale can be paused by setting `pausePublic` to true.
             * Pausing is separate from ending, since ending permanently closes the phase.
             */
            function pausePhases(
                uint256[] calldata phaseIndices,
                bool pausePublic
            ) external onlyOwner {
                uint256 numPhases = phaseIndices.length;
                for (uint256 i = 0; i < numPhases; ) {
                    uint256 phaseIndex = phaseIndices[i];
                    if (phaseIndex >= saleState.numPhases) {
                        // phaseIndex is out of bounds
                        revert InvalidPhase();
                    }
                    saleState.phases[phaseIndex].isActive = false;
                    // numPhases has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
                // calling this function with pausePublic=false only indicates the public sale
                // is not intended to be paused, but it does not pause it.
                if (pausePublic) {
                    isPublicActive = false;
                }
                emit PhasesPaused(phaseIndices, pausePublic);
            }
            /**
             * @notice If enabled, the token can be burned, for approved operators.
             * @dev The burn method will revert unless this is enabled
             */
            function toggleBurning() external onlyOwner {
                allowBurning = !allowBurning;
                emit BurnStatusChanged(allowBurning);
            }
            /**
             * @notice Permanently closes a phase by capping the supply & releasing it
             */
            function endPhase(uint256 phaseIndex) public onlyOwner {
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                // if the phase never had supply, there is nothing to do
                if (phase.maxSupply == 0) {
                    revert InvalidPhase();
                }
                // transfer the remaining supply into the base settings (used for public sale accounting)
                baseSettings.maxSupply += phase.maxSupply - phase.amountMinted;
                // remove the supply from the phase
                phase.maxSupply = 0;
                emit PhaseEnded(phaseIndex);
            }
            function endPhases(uint64[] calldata phaseIndices) external onlyOwner {
                uint256 phaseIndicesLength = phaseIndices.length;
                // ensure that phaseIndices argument will only ever be as large as the number of phases
                if (phaseIndicesLength > saleState.numPhases) {
                    revert InvalidPhase();
                }
                for (uint256 i = 0; i < phaseIndicesLength; ) {
                    endPhase(phaseIndices[i]);
                    // phaseIndicesLength has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
            }
            /**
             * @notice Updates the minting rules for a particular phase
             * @dev supply & amountMinted are not changeable
             */
            function updatePhaseSettings(
                uint256 phaseIndex,
                PhaseSettings calldata phase
            ) external onlyOwner {
                uint64 existingAmountMinted = saleState.phases[phaseIndex].amountMinted;
                uint64 existingMaxSupply = saleState.phases[phaseIndex].maxSupply;
                bool existingStatus = saleState.phases[phaseIndex].isActive;
                saleState.phases[phaseIndex] = phase;
                // ensure that the amountMinted, maxSupply, and status values cannot be set
                saleState.phases[phaseIndex].amountMinted = existingAmountMinted;
                saleState.phases[phaseIndex].maxSupply = existingMaxSupply;
                saleState.phases[phaseIndex].isActive = existingStatus;
                emit PhaseSettingsUpdated(phaseIndex, phase);
            }
            /**
             * @notice Updates the the base minting settings
             * The global maxPerWallet setting applies to all phases
             * Pricing and other fields will apply to the public sale
             *
             * @dev maxSupply & amountMinted are not changeable
             */
            function updateBaseSettings(
                BaseSettings calldata _baseSettings
            ) external onlyOwner {
                uint64 existingMaxSupply = baseSettings.maxSupply;
                uint64 existingAmountMinted = baseSettings.amountMinted;
                baseSettings = _baseSettings;
                // ensure that the maxSupply & amountMinted value cannot be set
                baseSettings.maxSupply = existingMaxSupply;
                baseSettings.amountMinted = existingAmountMinted;
                emit BaseSettingsUpdated(_baseSettings);
            }
            /**
             * @dev Payment can be pulled via PaymentSplitter.release
             * this method is provided for convenience to release all payee funds
             */
            function withdraw() external onlyOwner {
                uint256 numAddresses = withdrawAddresses.length;
                for (uint256 i = 0; i < numAddresses; ) {
                    address payable withdrawAddress = payable(withdrawAddresses[i]);
                    if (releasable(withdrawAddress) > 0) {
                        release(withdrawAddress);
                    }
                    // numAddresses has a maximum value of 2^256 - 1
                    unchecked {
                        ++i;
                    }
                }
            }
            function setBaseURI(string memory baseURI) external onlyOwner {
                _baseTokenURI = baseURI;
                emit BaseURIUpdated(baseURI);
            }
            function setRoyaltyInfo(
                address receiver,
                uint96 feeBasisPoints
            ) external onlyOwner {
                _setDefaultRoyalty(receiver, feeBasisPoints);
                emit RoyaltyUpdated(receiver, feeBasisPoints);
            }
            // ========= VIEW METHODS =========
            function _startTokenId() internal view virtual override returns (uint256) {
                return 1;
            }
            function _checkAllowlistPhaseMintConditions(
                address wallet,
                uint64 quantity,
                bytes32[] calldata proof,
                uint256 phaseIndex,
                uint256 balance
            ) internal view returns (uint64) {
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                if (!phase.isActive) {
                    revert PhaseNotActive();
                }
                // there should be a valid merkle root for the phase
                if (phase.merkleRoot == bytes32(0)) {
                    revert InvalidMintFunction();
                }
                if (phase.amountMinted + quantity > phase.maxSupply) {
                    revert SoldOut();
                }
                if (balance != quantity * phase.price) {
                    revert InvalidPrice();
                }
                if (
                    !MerkleProof.verify(
                        proof,
                        phase.merkleRoot,
                        keccak256(abi.encodePacked(wallet))
                    )
                ) {
                    revert InvalidProof();
                }
                uint256 amountMinted = amountMintedForPhase[wallet][phaseIndex];
                uint256 updatedAmountMinted = amountMinted + quantity;
                // phases can have a maxPerWallet
                if (
                    phase.maxPerWallet > 0 && updatedAmountMinted > phase.maxPerWallet
                ) {
                    revert ExceedMaxPerWallet();
                }
                return uint64(updatedAmountMinted);
            }
            function _checkPhaseMintConditions(
                address wallet,
                uint256 quantity,
                uint256 phaseIndex,
                uint256 balance
            ) internal view returns (uint64) {
                PhaseSettings storage phase = saleState.phases[phaseIndex];
                if (!phase.isActive) {
                    revert PhaseNotActive();
                }
                // the phase should not have a merkleRoot
                if (phase.merkleRoot != bytes32(0)) {
                    revert InvalidMintFunction();
                }
                if (phase.amountMinted + quantity > phase.maxSupply) {
                    revert SoldOut();
                }
                if (balance != quantity * phase.price) {
                    revert InvalidPrice();
                }
                uint256 amountMinted = amountMintedForPhase[wallet][phaseIndex];
                uint256 updatedAmountMinted = amountMinted + quantity;
                // phases can have a maxPerWallet
                if (
                    phase.maxPerWallet > 0 && updatedAmountMinted > phase.maxPerWallet
                ) {
                    revert ExceedMaxPerWallet();
                }
                return uint64(updatedAmountMinted);
            }
            function _checkPublicMintConditions(
                uint256 quantity,
                uint256 balance
            ) internal view returns (uint64) {
                if (!isPublicActive) {
                    revert PhaseNotActive();
                }
                uint256 updatedAmountMinted = baseSettings.amountMinted + quantity;
                if (updatedAmountMinted > baseSettings.maxSupply) {
                    revert SoldOut();
                }
                if (balance != quantity * baseSettings.price) {
                    revert InvalidPrice();
                }
                return uint64(updatedAmountMinted);
            }
            function _checkGlobalPerWalletMax(
                address wallet,
                uint256 quantity
            ) internal view {
                if (
                    baseSettings.maxPerWallet > 0 &&
                    _numberMinted(wallet) + quantity > baseSettings.maxPerWallet
                ) {
                    revert ExceedMaxPerWallet();
                }
            }
            function getDataForPhase(
                uint256 phaseIndex
            ) external view returns (PhaseSettings memory) {
                return saleState.phases[phaseIndex];
            }
            function getMintBalance(address wallet) external view returns (uint256) {
                return _numberMinted(wallet);
            }
            function getAmountMintedForPhase(
                uint256 phaseIndex,
                address wallet
            ) external view returns (uint64) {
                return amountMintedForPhase[wallet][phaseIndex];
            }
            function getAmountMintedForOwner(
                address wallet
            ) external view returns (uint256[] memory) {
                uint256[] memory amountMintedPerPhase = new uint256[](
                    saleState.numPhases + 1
                );
                for (uint64 i = 0; i < saleState.numPhases; ) {
                    amountMintedPerPhase[i] = amountMintedForPhase[wallet][i];
                    // numPhases has a maximum value of 2^64 - 1
                    unchecked {
                        ++i;
                    }
                }
                amountMintedPerPhase[saleState.numPhases] = _numberMinted(wallet);
                return amountMintedPerPhase;
            }
            /**
             * @dev See {ERC721-_baseURI}.
             */
            function _baseURI() internal view virtual override returns (string memory) {
                return _baseTokenURI;
            }
            function supportsInterface(
                bytes4 interfaceId
            )
                public
                view
                virtual
                override(IERC721AUpgradeable, ERC721AUpgradeable, ERC2981Upgradeable)
                returns (bool)
            {
                return
                    ERC721AUpgradeable.supportsInterface(interfaceId) ||
                    ERC2981Upgradeable.supportsInterface(interfaceId);
            }
            // ========= OPERATOR FILTERER OVERRIDES =========
            function setApprovalForAll(
                address operator,
                bool approved
            )
                public
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperatorApproval(operator)
            {
                super.setApprovalForAll(operator, approved);
            }
            function approve(
                address operator,
                uint256 tokenId
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperatorApproval(operator)
            {
                super.approve(operator, tokenId);
            }
            function transferFrom(
                address from,
                address to,
                uint256 tokenId
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperator(from)
            {
                super.transferFrom(from, to, tokenId);
            }
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperator(from)
            {
                super.safeTransferFrom(from, to, tokenId);
            }
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId,
                bytes memory data
            )
                public
                payable
                override(ERC721AUpgradeable, IERC721AUpgradeable)
                onlyAllowedOperator(from)
            {
                super.safeTransferFrom(from, to, tokenId, data);
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.17;
        error InvalidPrice();
        error SoldOut();
        error ExceedMaxPerWallet();
        error InvalidProof();
        error InvalidMintFunction();
        error InvalidAirdrop();
        error BurningNotAllowed();
        struct PaymentSplitterSettings {
            address[] payees;
            uint256[] shares;
        }
        struct RoyaltySettings {
            address royaltyAddress;
            uint96 royaltyAmount;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /**
         * @dev This is a base contract to aid in writing upgradeable diamond facet contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         */
        import {ERC721A__InitializableStorage} from './ERC721A__InitializableStorage.sol';
        abstract contract ERC721A__Initializable {
            using ERC721A__InitializableStorage for ERC721A__InitializableStorage.Layout;
            /**
             * @dev Modifier to protect an initializer function from being invoked twice.
             */
            modifier initializerERC721A() {
                // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                // contract may have been reentered.
                require(
                    ERC721A__InitializableStorage.layout()._initializing
                        ? _isConstructor()
                        : !ERC721A__InitializableStorage.layout()._initialized,
                    'ERC721A__Initializable: contract is already initialized'
                );
                bool isTopLevelCall = !ERC721A__InitializableStorage.layout()._initializing;
                if (isTopLevelCall) {
                    ERC721A__InitializableStorage.layout()._initializing = true;
                    ERC721A__InitializableStorage.layout()._initialized = true;
                }
                _;
                if (isTopLevelCall) {
                    ERC721A__InitializableStorage.layout()._initializing = false;
                }
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} modifier, directly or indirectly.
             */
            modifier onlyInitializingERC721A() {
                require(
                    ERC721A__InitializableStorage.layout()._initializing,
                    'ERC721A__Initializable: contract is not initializing'
                );
                _;
            }
            /// @dev Returns true if and only if the function is running in the constructor
            function _isConstructor() private view returns (bool) {
                // extcodesize checks the size of the code stored in an address, and
                // address returns the current address. Since the code is still not
                // deployed when running a constructor, any checks on its code size will
                // yield zero, making it an effective way to detect if a contract is
                // under construction or not.
                address self = address(this);
                uint256 cs;
                assembly {
                    cs := extcodesize(self)
                }
                return cs == 0;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /**
         * @dev This is a base storage for the  initialization function for upgradeable diamond facet contracts
         **/
        library ERC721A__InitializableStorage {
            struct Layout {
                /*
                 * Indicates that the contract has been initialized.
                 */
                bool _initialized;
                /*
                 * Indicates that the contract is in the process of being initialized.
                 */
                bool _initializing;
            }
            bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.initializable.facet');
            function layout() internal pure returns (Layout storage l) {
                bytes32 slot = STORAGE_SLOT;
                assembly {
                    l.slot := slot
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        library ERC721AStorage {
            // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
            struct TokenApprovalRef {
                address value;
            }
            struct Layout {
                // =============================================================
                //                            STORAGE
                // =============================================================
                // The next token ID to be minted.
                uint256 _currentIndex;
                // The number of tokens burned.
                uint256 _burnCounter;
                // Token name
                string _name;
                // Token symbol
                string _symbol;
                // Mapping from token ID to ownership details
                // An empty struct value does not necessarily mean the token is unowned.
                // See {_packedOwnershipOf} implementation for details.
                //
                // Bits Layout:
                // - [0..159]   `addr`
                // - [160..223] `startTimestamp`
                // - [224]      `burned`
                // - [225]      `nextInitialized`
                // - [232..255] `extraData`
                mapping(uint256 => uint256) _packedOwnerships;
                // Mapping owner address to address data.
                //
                // Bits Layout:
                // - [0..63]    `balance`
                // - [64..127]  `numberMinted`
                // - [128..191] `numberBurned`
                // - [192..255] `aux`
                mapping(address => uint256) _packedAddressData;
                // Mapping from token ID to approved address.
                mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals;
                // Mapping from owner to operator approvals
                mapping(address => mapping(address => bool)) _operatorApprovals;
            }
            bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.ERC721A');
            function layout() internal pure returns (Layout storage l) {
                bytes32 slot = STORAGE_SLOT;
                assembly {
                    l.slot := slot
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        import './IERC721AUpgradeable.sol';
        import {ERC721AStorage} from './ERC721AStorage.sol';
        import './ERC721A__Initializable.sol';
        /**
         * @dev Interface of ERC721 token receiver.
         */
        interface ERC721A__IERC721ReceiverUpgradeable {
            function onERC721Received(
                address operator,
                address from,
                uint256 tokenId,
                bytes calldata data
            ) external returns (bytes4);
        }
        /**
         * @title ERC721A
         *
         * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
         * Non-Fungible Token Standard, including the Metadata extension.
         * Optimized for lower gas during batch mints.
         *
         * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
         * starting from `_startTokenId()`.
         *
         * Assumptions:
         *
         * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
         * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
         */
        contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable {
            using ERC721AStorage for ERC721AStorage.Layout;
            // =============================================================
            //                           CONSTANTS
            // =============================================================
            // Mask of an entry in packed address data.
            uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
            // The bit position of `numberMinted` in packed address data.
            uint256 private constant _BITPOS_NUMBER_MINTED = 64;
            // The bit position of `numberBurned` in packed address data.
            uint256 private constant _BITPOS_NUMBER_BURNED = 128;
            // The bit position of `aux` in packed address data.
            uint256 private constant _BITPOS_AUX = 192;
            // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
            uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
            // The bit position of `startTimestamp` in packed ownership.
            uint256 private constant _BITPOS_START_TIMESTAMP = 160;
            // The bit mask of the `burned` bit in packed ownership.
            uint256 private constant _BITMASK_BURNED = 1 << 224;
            // The bit position of the `nextInitialized` bit in packed ownership.
            uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
            // The bit mask of the `nextInitialized` bit in packed ownership.
            uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
            // The bit position of `extraData` in packed ownership.
            uint256 private constant _BITPOS_EXTRA_DATA = 232;
            // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
            uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
            // The mask of the lower 160 bits for addresses.
            uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
            // The maximum `quantity` that can be minted with {_mintERC2309}.
            // This limit is to prevent overflows on the address data entries.
            // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
            // is required to cause an overflow, which is unrealistic.
            uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
            // The `Transfer` event signature is given by:
            // `keccak256(bytes("Transfer(address,address,uint256)"))`.
            bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
                0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
            // =============================================================
            //                          CONSTRUCTOR
            // =============================================================
            function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                __ERC721A_init_unchained(name_, symbol_);
            }
            function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                ERC721AStorage.layout()._name = name_;
                ERC721AStorage.layout()._symbol = symbol_;
                ERC721AStorage.layout()._currentIndex = _startTokenId();
            }
            // =============================================================
            //                   TOKEN COUNTING OPERATIONS
            // =============================================================
            /**
             * @dev Returns the starting token ID.
             * To change the starting token ID, please override this function.
             */
            function _startTokenId() internal view virtual returns (uint256) {
                return 0;
            }
            /**
             * @dev Returns the next token ID to be minted.
             */
            function _nextTokenId() internal view virtual returns (uint256) {
                return ERC721AStorage.layout()._currentIndex;
            }
            /**
             * @dev Returns the total number of tokens in existence.
             * Burned tokens will reduce the count.
             * To get the total number of tokens minted, please see {_totalMinted}.
             */
            function totalSupply() public view virtual override returns (uint256) {
                // Counter underflow is impossible as _burnCounter cannot be incremented
                // more than `_currentIndex - _startTokenId()` times.
                unchecked {
                    return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId();
                }
            }
            /**
             * @dev Returns the total amount of tokens minted in the contract.
             */
            function _totalMinted() internal view virtual returns (uint256) {
                // Counter underflow is impossible as `_currentIndex` does not decrement,
                // and it is initialized to `_startTokenId()`.
                unchecked {
                    return ERC721AStorage.layout()._currentIndex - _startTokenId();
                }
            }
            /**
             * @dev Returns the total number of tokens burned.
             */
            function _totalBurned() internal view virtual returns (uint256) {
                return ERC721AStorage.layout()._burnCounter;
            }
            // =============================================================
            //                    ADDRESS DATA OPERATIONS
            // =============================================================
            /**
             * @dev Returns the number of tokens in `owner`'s account.
             */
            function balanceOf(address owner) public view virtual override returns (uint256) {
                if (owner == address(0)) revert BalanceQueryForZeroAddress();
                return ERC721AStorage.layout()._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
            }
            /**
             * Returns the number of tokens minted by `owner`.
             */
            function _numberMinted(address owner) internal view returns (uint256) {
                return
                    (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
            }
            /**
             * Returns the number of tokens burned by or on behalf of `owner`.
             */
            function _numberBurned(address owner) internal view returns (uint256) {
                return
                    (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
            }
            /**
             * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
             */
            function _getAux(address owner) internal view returns (uint64) {
                return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX);
            }
            /**
             * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
             * If there are multiple variables, please pack them into a uint64.
             */
            function _setAux(address owner, uint64 aux) internal virtual {
                uint256 packed = ERC721AStorage.layout()._packedAddressData[owner];
                uint256 auxCasted;
                // Cast `aux` with assembly to avoid redundant masking.
                assembly {
                    auxCasted := aux
                }
                packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
                ERC721AStorage.layout()._packedAddressData[owner] = packed;
            }
            // =============================================================
            //                            IERC165
            // =============================================================
            /**
             * @dev Returns true if this contract implements the interface defined by
             * `interfaceId`. See the corresponding
             * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
             * to learn more about how these ids are created.
             *
             * This function call must use less than 30000 gas.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                // The interface IDs are constants representing the first 4 bytes
                // of the XOR of all function selectors in the interface.
                // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
                // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
                return
                    interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                    interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
                    interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
            }
            // =============================================================
            //                        IERC721Metadata
            // =============================================================
            /**
             * @dev Returns the token collection name.
             */
            function name() public view virtual override returns (string memory) {
                return ERC721AStorage.layout()._name;
            }
            /**
             * @dev Returns the token collection symbol.
             */
            function symbol() public view virtual override returns (string memory) {
                return ERC721AStorage.layout()._symbol;
            }
            /**
             * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
             */
            function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                string memory baseURI = _baseURI();
                return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
            }
            /**
             * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
             * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
             * by default, it can be overridden in child contracts.
             */
            function _baseURI() internal view virtual returns (string memory) {
                return '';
            }
            // =============================================================
            //                     OWNERSHIPS OPERATIONS
            // =============================================================
            /**
             * @dev Returns the owner of the `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function ownerOf(uint256 tokenId) public view virtual override returns (address) {
                return address(uint160(_packedOwnershipOf(tokenId)));
            }
            /**
             * @dev Gas spent here starts off proportional to the maximum mint batch size.
             * It gradually moves to O(1) as tokens get transferred around over time.
             */
            function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
                return _unpackedOwnership(_packedOwnershipOf(tokenId));
            }
            /**
             * @dev Returns the unpacked `TokenOwnership` struct at `index`.
             */
            function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
                return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]);
            }
            /**
             * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
             */
            function _initializeOwnershipAt(uint256 index) internal virtual {
                if (ERC721AStorage.layout()._packedOwnerships[index] == 0) {
                    ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index);
                }
            }
            /**
             * Returns the packed ownership data of `tokenId`.
             */
            function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
                if (_startTokenId() <= tokenId) {
                    packed = ERC721AStorage.layout()._packedOwnerships[tokenId];
                    // If not burned.
                    if (packed & _BITMASK_BURNED == 0) {
                        // If the data at the starting slot does not exist, start the scan.
                        if (packed == 0) {
                            if (tokenId >= ERC721AStorage.layout()._currentIndex) revert OwnerQueryForNonexistentToken();
                            // Invariant:
                            // There will always be an initialized ownership slot
                            // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                            // before an unintialized ownership slot
                            // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                            // Hence, `tokenId` will not underflow.
                            //
                            // We can directly compare the packed value.
                            // If the address is zero, packed will be zero.
                            for (;;) {
                                unchecked {
                                    packed = ERC721AStorage.layout()._packedOwnerships[--tokenId];
                                }
                                if (packed == 0) continue;
                                return packed;
                            }
                        }
                        // Otherwise, the data exists and is not burned. We can skip the scan.
                        // This is possible because we have already achieved the target condition.
                        // This saves 2143 gas on transfers of initialized tokens.
                        return packed;
                    }
                }
                revert OwnerQueryForNonexistentToken();
            }
            /**
             * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
             */
            function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
                ownership.addr = address(uint160(packed));
                ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
                ownership.burned = packed & _BITMASK_BURNED != 0;
                ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
            }
            /**
             * @dev Packs ownership data into a single uint256.
             */
            function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
                assembly {
                    // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                    owner := and(owner, _BITMASK_ADDRESS)
                    // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                    result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
                }
            }
            /**
             * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
             */
            function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
                // For branchless setting of the `nextInitialized` flag.
                assembly {
                    // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                    result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
                }
            }
            // =============================================================
            //                      APPROVAL OPERATIONS
            // =============================================================
            /**
             * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
             *
             * Requirements:
             *
             * - The caller must own the token or be an approved operator.
             */
            function approve(address to, uint256 tokenId) public payable virtual override {
                _approve(to, tokenId, true);
            }
            /**
             * @dev Returns the account approved for `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function getApproved(uint256 tokenId) public view virtual override returns (address) {
                if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
                return ERC721AStorage.layout()._tokenApprovals[tokenId].value;
            }
            /**
             * @dev Approve or remove `operator` as an operator for the caller.
             * Operators can call {transferFrom} or {safeTransferFrom}
             * for any token owned by the caller.
             *
             * Requirements:
             *
             * - The `operator` cannot be the caller.
             *
             * Emits an {ApprovalForAll} event.
             */
            function setApprovalForAll(address operator, bool approved) public virtual override {
                ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved;
                emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
            }
            /**
             * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
             *
             * See {setApprovalForAll}.
             */
            function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
                return ERC721AStorage.layout()._operatorApprovals[owner][operator];
            }
            /**
             * @dev Returns whether `tokenId` exists.
             *
             * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
             *
             * Tokens start existing when they are minted. See {_mint}.
             */
            function _exists(uint256 tokenId) internal view virtual returns (bool) {
                return
                    _startTokenId() <= tokenId &&
                    tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds,
                    ERC721AStorage.layout()._packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
            }
            /**
             * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
             */
            function _isSenderApprovedOrOwner(
                address approvedAddress,
                address owner,
                address msgSender
            ) private pure returns (bool result) {
                assembly {
                    // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                    owner := and(owner, _BITMASK_ADDRESS)
                    // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                    msgSender := and(msgSender, _BITMASK_ADDRESS)
                    // `msgSender == owner || msgSender == approvedAddress`.
                    result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
                }
            }
            /**
             * @dev Returns the storage slot and value for the approved address of `tokenId`.
             */
            function _getApprovedSlotAndAddress(uint256 tokenId)
                private
                view
                returns (uint256 approvedAddressSlot, address approvedAddress)
            {
                ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage.layout()._tokenApprovals[tokenId];
                // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
                assembly {
                    approvedAddressSlot := tokenApproval.slot
                    approvedAddress := sload(approvedAddressSlot)
                }
            }
            // =============================================================
            //                      TRANSFER OPERATIONS
            // =============================================================
            /**
             * @dev Transfers `tokenId` from `from` to `to`.
             *
             * 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
            ) public payable virtual override {
                uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
                (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                // The nested ifs save around 20+ gas over a compound boolean condition.
                if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                    if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                if (to == address(0)) revert TransferToZeroAddress();
                _beforeTokenTransfers(from, to, tokenId, 1);
                // Clear approvals from the previous owner.
                assembly {
                    if approvedAddress {
                        // This is equivalent to `delete _tokenApprovals[tokenId]`.
                        sstore(approvedAddressSlot, 0)
                    }
                }
                // Underflow of the sender's balance is impossible because we check for
                // ownership above and the recipient's balance can't realistically overflow.
                // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                unchecked {
                    // We can directly increment and decrement the balances.
                    --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`.
                    ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`.
                    // Updates:
                    // - `address` to the next owner.
                    // - `startTimestamp` to the timestamp of transfering.
                    // - `burned` to `false`.
                    // - `nextInitialized` to `true`.
                    ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                        to,
                        _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
                    );
                    // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                    if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                        uint256 nextTokenId = tokenId + 1;
                        // If the next slot's address is zero and not burned (i.e. packed value is zero).
                        if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                            // If the next slot is within bounds.
                            if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                            }
                        }
                    }
                }
                emit Transfer(from, to, tokenId);
                _afterTokenTransfers(from, to, tokenId, 1);
            }
            /**
             * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
             */
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
            ) public payable virtual override {
                safeTransferFrom(from, to, tokenId, '');
            }
            /**
             * @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 memory _data
            ) public payable virtual override {
                transferFrom(from, to, tokenId);
                if (to.code.length != 0)
                    if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                        revert TransferToNonERC721ReceiverImplementer();
                    }
            }
            /**
             * @dev Hook that is called before a set of serially-ordered token IDs
             * are about to be transferred. This includes minting.
             * And also called before burning one token.
             *
             * `startTokenId` - the first token ID to be transferred.
             * `quantity` - the amount to be transferred.
             *
             * Calling conditions:
             *
             * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
             * transferred to `to`.
             * - When `from` is zero, `tokenId` will be minted for `to`.
             * - When `to` is zero, `tokenId` will be burned by `from`.
             * - `from` and `to` are never both zero.
             */
            function _beforeTokenTransfers(
                address from,
                address to,
                uint256 startTokenId,
                uint256 quantity
            ) internal virtual {}
            /**
             * @dev Hook that is called after a set of serially-ordered token IDs
             * have been transferred. This includes minting.
             * And also called after one token has been burned.
             *
             * `startTokenId` - the first token ID to be transferred.
             * `quantity` - the amount to be transferred.
             *
             * Calling conditions:
             *
             * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
             * transferred to `to`.
             * - When `from` is zero, `tokenId` has been minted for `to`.
             * - When `to` is zero, `tokenId` has been burned by `from`.
             * - `from` and `to` are never both zero.
             */
            function _afterTokenTransfers(
                address from,
                address to,
                uint256 startTokenId,
                uint256 quantity
            ) internal virtual {}
            /**
             * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
             *
             * `from` - Previous owner of the given token ID.
             * `to` - Target address that will receive the token.
             * `tokenId` - Token ID to be transferred.
             * `_data` - Optional data to send along with the call.
             *
             * Returns whether the call correctly returned the expected magic value.
             */
            function _checkContractOnERC721Received(
                address from,
                address to,
                uint256 tokenId,
                bytes memory _data
            ) private returns (bool) {
                try
                    ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data)
                returns (bytes4 retval) {
                    return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector;
                } catch (bytes memory reason) {
                    if (reason.length == 0) {
                        revert TransferToNonERC721ReceiverImplementer();
                    } else {
                        assembly {
                            revert(add(32, reason), mload(reason))
                        }
                    }
                }
            }
            // =============================================================
            //                        MINT OPERATIONS
            // =============================================================
            /**
             * @dev Mints `quantity` tokens and transfers them to `to`.
             *
             * Requirements:
             *
             * - `to` cannot be the zero address.
             * - `quantity` must be greater than 0.
             *
             * Emits a {Transfer} event for each mint.
             */
            function _mint(address to, uint256 quantity) internal virtual {
                uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                if (quantity == 0) revert MintZeroQuantity();
                _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                // Overflows are incredibly unrealistic.
                // `balance` and `numberMinted` have a maximum limit of 2**64.
                // `tokenId` has a maximum limit of 2**256.
                unchecked {
                    // Updates:
                    // - `balance += quantity`.
                    // - `numberMinted += quantity`.
                    //
                    // We can directly add to the `balance` and `numberMinted`.
                    ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                    // Updates:
                    // - `address` to the owner.
                    // - `startTimestamp` to the timestamp of minting.
                    // - `burned` to `false`.
                    // - `nextInitialized` to `quantity == 1`.
                    ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                        to,
                        _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                    );
                    uint256 toMasked;
                    uint256 end = startTokenId + quantity;
                    // Use assembly to loop and emit the `Transfer` event for gas savings.
                    // The duplicated `log4` removes an extra check and reduces stack juggling.
                    // The assembly, together with the surrounding Solidity code, have been
                    // delicately arranged to nudge the compiler into producing optimized opcodes.
                    assembly {
                        // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        toMasked := and(to, _BITMASK_ADDRESS)
                        // Emit the `Transfer` event.
                        log4(
                            0, // Start of data (0, since no data).
                            0, // End of data (0, since no data).
                            _TRANSFER_EVENT_SIGNATURE, // Signature.
                            0, // `address(0)`.
                            toMasked, // `to`.
                            startTokenId // `tokenId`.
                        )
                        // The `iszero(eq(,))` check ensures that large values of `quantity`
                        // that overflows uint256 will make the loop run out of gas.
                        // The compiler will optimize the `iszero` away for performance.
                        for {
                            let tokenId := add(startTokenId, 1)
                        } iszero(eq(tokenId, end)) {
                            tokenId := add(tokenId, 1)
                        } {
                            // Emit the `Transfer` event. Similar to above.
                            log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                        }
                    }
                    if (toMasked == 0) revert MintToZeroAddress();
                    ERC721AStorage.layout()._currentIndex = end;
                }
                _afterTokenTransfers(address(0), to, startTokenId, quantity);
            }
            /**
             * @dev Mints `quantity` tokens and transfers them to `to`.
             *
             * This function is intended for efficient minting only during contract creation.
             *
             * It emits only one {ConsecutiveTransfer} as defined in
             * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
             * instead of a sequence of {Transfer} event(s).
             *
             * Calling this function outside of contract creation WILL make your contract
             * non-compliant with the ERC721 standard.
             * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
             * {ConsecutiveTransfer} event is only permissible during contract creation.
             *
             * Requirements:
             *
             * - `to` cannot be the zero address.
             * - `quantity` must be greater than 0.
             *
             * Emits a {ConsecutiveTransfer} event.
             */
            function _mintERC2309(address to, uint256 quantity) internal virtual {
                uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                if (to == address(0)) revert MintToZeroAddress();
                if (quantity == 0) revert MintZeroQuantity();
                if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
                _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
                unchecked {
                    // Updates:
                    // - `balance += quantity`.
                    // - `numberMinted += quantity`.
                    //
                    // We can directly add to the `balance` and `numberMinted`.
                    ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                    // Updates:
                    // - `address` to the owner.
                    // - `startTimestamp` to the timestamp of minting.
                    // - `burned` to `false`.
                    // - `nextInitialized` to `quantity == 1`.
                    ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                        to,
                        _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                    );
                    emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
                    ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
                }
                _afterTokenTransfers(address(0), to, startTokenId, quantity);
            }
            /**
             * @dev Safely mints `quantity` tokens and transfers them to `to`.
             *
             * Requirements:
             *
             * - If `to` refers to a smart contract, it must implement
             * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
             * - `quantity` must be greater than 0.
             *
             * See {_mint}.
             *
             * Emits a {Transfer} event for each mint.
             */
            function _safeMint(
                address to,
                uint256 quantity,
                bytes memory _data
            ) internal virtual {
                _mint(to, quantity);
                unchecked {
                    if (to.code.length != 0) {
                        uint256 end = ERC721AStorage.layout()._currentIndex;
                        uint256 index = end - quantity;
                        do {
                            if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                                revert TransferToNonERC721ReceiverImplementer();
                            }
                        } while (index < end);
                        // Reentrancy protection.
                        if (ERC721AStorage.layout()._currentIndex != end) revert();
                    }
                }
            }
            /**
             * @dev Equivalent to `_safeMint(to, quantity, '')`.
             */
            function _safeMint(address to, uint256 quantity) internal virtual {
                _safeMint(to, quantity, '');
            }
            // =============================================================
            //                       APPROVAL OPERATIONS
            // =============================================================
            /**
             * @dev Equivalent to `_approve(to, tokenId, false)`.
             */
            function _approve(address to, uint256 tokenId) internal virtual {
                _approve(to, tokenId, false);
            }
            /**
             * @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:
             *
             * - `tokenId` must exist.
             *
             * Emits an {Approval} event.
             */
            function _approve(
                address to,
                uint256 tokenId,
                bool approvalCheck
            ) internal virtual {
                address owner = ownerOf(tokenId);
                if (approvalCheck)
                    if (_msgSenderERC721A() != owner)
                        if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                            revert ApprovalCallerNotOwnerNorApproved();
                        }
                ERC721AStorage.layout()._tokenApprovals[tokenId].value = to;
                emit Approval(owner, to, tokenId);
            }
            // =============================================================
            //                        BURN OPERATIONS
            // =============================================================
            /**
             * @dev Equivalent to `_burn(tokenId, false)`.
             */
            function _burn(uint256 tokenId) internal virtual {
                _burn(tokenId, false);
            }
            /**
             * @dev Destroys `tokenId`.
             * The approval is cleared when the token is burned.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             *
             * Emits a {Transfer} event.
             */
            function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
                uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                address from = address(uint160(prevOwnershipPacked));
                (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                if (approvalCheck) {
                    // The nested ifs save around 20+ gas over a compound boolean condition.
                    if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                        if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                }
                _beforeTokenTransfers(from, address(0), tokenId, 1);
                // Clear approvals from the previous owner.
                assembly {
                    if approvedAddress {
                        // This is equivalent to `delete _tokenApprovals[tokenId]`.
                        sstore(approvedAddressSlot, 0)
                    }
                }
                // Underflow of the sender's balance is impossible because we check for
                // ownership above and the recipient's balance can't realistically overflow.
                // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                unchecked {
                    // Updates:
                    // - `balance -= 1`.
                    // - `numberBurned += 1`.
                    //
                    // We can directly decrement the balance, and increment the number burned.
                    // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
                    ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
                    // Updates:
                    // - `address` to the last owner.
                    // - `startTimestamp` to the timestamp of burning.
                    // - `burned` to `true`.
                    // - `nextInitialized` to `true`.
                    ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                        from,
                        (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
                    );
                    // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                    if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                        uint256 nextTokenId = tokenId + 1;
                        // If the next slot's address is zero and not burned (i.e. packed value is zero).
                        if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                            // If the next slot is within bounds.
                            if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                            }
                        }
                    }
                }
                emit Transfer(from, address(0), tokenId);
                _afterTokenTransfers(from, address(0), tokenId, 1);
                // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
                unchecked {
                    ERC721AStorage.layout()._burnCounter++;
                }
            }
            // =============================================================
            //                     EXTRA DATA OPERATIONS
            // =============================================================
            /**
             * @dev Directly sets the extra data for the ownership data `index`.
             */
            function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
                uint256 packed = ERC721AStorage.layout()._packedOwnerships[index];
                if (packed == 0) revert OwnershipNotInitializedForExtraData();
                uint256 extraDataCasted;
                // Cast `extraData` with assembly to avoid redundant masking.
                assembly {
                    extraDataCasted := extraData
                }
                packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
                ERC721AStorage.layout()._packedOwnerships[index] = packed;
            }
            /**
             * @dev Called during each token transfer to set the 24bit `extraData` field.
             * Intended to be overridden by the cosumer contract.
             *
             * `previousExtraData` - the value of `extraData` before transfer.
             *
             * Calling conditions:
             *
             * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
             * transferred to `to`.
             * - When `from` is zero, `tokenId` will be minted for `to`.
             * - When `to` is zero, `tokenId` will be burned by `from`.
             * - `from` and `to` are never both zero.
             */
            function _extraData(
                address from,
                address to,
                uint24 previousExtraData
            ) internal view virtual returns (uint24) {}
            /**
             * @dev Returns the next extra data for the packed ownership data.
             * The returned result is shifted into position.
             */
            function _nextExtraData(
                address from,
                address to,
                uint256 prevOwnershipPacked
            ) private view returns (uint256) {
                uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
                return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
            }
            // =============================================================
            //                       OTHER OPERATIONS
            // =============================================================
            /**
             * @dev Returns the message sender (defaults to `msg.sender`).
             *
             * If you are writing GSN compatible contracts, you need to override this function.
             */
            function _msgSenderERC721A() internal view virtual returns (address) {
                return msg.sender;
            }
            /**
             * @dev Converts a uint256 to its ASCII string decimal representation.
             */
            function _toString(uint256 value) internal pure virtual returns (string memory str) {
                assembly {
                    // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                    // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                    // We will need 1 word for the trailing zeros padding, 1 word for the length,
                    // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                    let m := add(mload(0x40), 0xa0)
                    // Update the free memory pointer to allocate.
                    mstore(0x40, m)
                    // Assign the `str` to the end.
                    str := sub(m, 0x20)
                    // Zeroize the slot after the string.
                    mstore(str, 0)
                    // Cache the end of the memory to calculate the length later.
                    let end := str
                    // We write the string from rightmost digit to leftmost digit.
                    // The following is essentially a do-while loop that also handles the zero case.
                    // prettier-ignore
                    for { let temp := value } 1 {} {
                        str := sub(str, 1)
                        // Write the character to the pointer.
                        // The ASCII index of the '0' character is 48.
                        mstore8(str, add(48, mod(temp, 10)))
                        // Keep dividing `temp` until zero.
                        temp := div(temp, 10)
                        // prettier-ignore
                        if iszero(temp) { break }
                    }
                    let length := sub(end, str)
                    // Move the pointer 32 bytes leftwards to make room for the length.
                    str := sub(str, 0x20)
                    // Store the length.
                    mstore(str, length)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        import './IERC721AQueryableUpgradeable.sol';
        import '../ERC721AUpgradeable.sol';
        import '../ERC721A__Initializable.sol';
        /**
         * @title ERC721AQueryable.
         *
         * @dev ERC721A subclass with convenience query functions.
         */
        abstract contract ERC721AQueryableUpgradeable is
            ERC721A__Initializable,
            ERC721AUpgradeable,
            IERC721AQueryableUpgradeable
        {
            function __ERC721AQueryable_init() internal onlyInitializingERC721A {
                __ERC721AQueryable_init_unchained();
            }
            function __ERC721AQueryable_init_unchained() internal onlyInitializingERC721A {}
            /**
             * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
             *
             * If the `tokenId` is out of bounds:
             *
             * - `addr = address(0)`
             * - `startTimestamp = 0`
             * - `burned = false`
             * - `extraData = 0`
             *
             * If the `tokenId` is burned:
             *
             * - `addr = <Address of owner before token was burned>`
             * - `startTimestamp = <Timestamp when token was burned>`
             * - `burned = true`
             * - `extraData = <Extra data when token was burned>`
             *
             * Otherwise:
             *
             * - `addr = <Address of owner>`
             * - `startTimestamp = <Timestamp of start of ownership>`
             * - `burned = false`
             * - `extraData = <Extra data at start of ownership>`
             */
            function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
                TokenOwnership memory ownership;
                if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
                    return ownership;
                }
                ownership = _ownershipAt(tokenId);
                if (ownership.burned) {
                    return ownership;
                }
                return _ownershipOf(tokenId);
            }
            /**
             * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
             * See {ERC721AQueryable-explicitOwnershipOf}
             */
            function explicitOwnershipsOf(uint256[] calldata tokenIds)
                external
                view
                virtual
                override
                returns (TokenOwnership[] memory)
            {
                unchecked {
                    uint256 tokenIdsLength = tokenIds.length;
                    TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
                    for (uint256 i; i != tokenIdsLength; ++i) {
                        ownerships[i] = explicitOwnershipOf(tokenIds[i]);
                    }
                    return ownerships;
                }
            }
            /**
             * @dev Returns an array of token IDs owned by `owner`,
             * in the range [`start`, `stop`)
             * (i.e. `start <= tokenId < stop`).
             *
             * This function allows for tokens to be queried if the collection
             * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
             *
             * Requirements:
             *
             * - `start < stop`
             */
            function tokensOfOwnerIn(
                address owner,
                uint256 start,
                uint256 stop
            ) external view virtual override returns (uint256[] memory) {
                unchecked {
                    if (start >= stop) revert InvalidQueryRange();
                    uint256 tokenIdsIdx;
                    uint256 stopLimit = _nextTokenId();
                    // Set `start = max(start, _startTokenId())`.
                    if (start < _startTokenId()) {
                        start = _startTokenId();
                    }
                    // Set `stop = min(stop, stopLimit)`.
                    if (stop > stopLimit) {
                        stop = stopLimit;
                    }
                    uint256 tokenIdsMaxLength = balanceOf(owner);
                    // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
                    // to cater for cases where `balanceOf(owner)` is too big.
                    if (start < stop) {
                        uint256 rangeLength = stop - start;
                        if (rangeLength < tokenIdsMaxLength) {
                            tokenIdsMaxLength = rangeLength;
                        }
                    } else {
                        tokenIdsMaxLength = 0;
                    }
                    uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
                    if (tokenIdsMaxLength == 0) {
                        return tokenIds;
                    }
                    // We need to call `explicitOwnershipOf(start)`,
                    // because the slot at `start` may not be initialized.
                    TokenOwnership memory ownership = explicitOwnershipOf(start);
                    address currOwnershipAddr;
                    // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
                    // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
                    if (!ownership.burned) {
                        currOwnershipAddr = ownership.addr;
                    }
                    for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
                        ownership = _ownershipAt(i);
                        if (ownership.burned) {
                            continue;
                        }
                        if (ownership.addr != address(0)) {
                            currOwnershipAddr = ownership.addr;
                        }
                        if (currOwnershipAddr == owner) {
                            tokenIds[tokenIdsIdx++] = i;
                        }
                    }
                    // Downsize the array to fit.
                    assembly {
                        mstore(tokenIds, tokenIdsIdx)
                    }
                    return tokenIds;
                }
            }
            /**
             * @dev Returns an array of token IDs owned by `owner`.
             *
             * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
             * It is meant to be called off-chain.
             *
             * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
             * multiple smaller scans if the collection is large enough to cause
             * an out-of-gas error (10K collections should be fine).
             */
            function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
                unchecked {
                    uint256 tokenIdsIdx;
                    address currOwnershipAddr;
                    uint256 tokenIdsLength = balanceOf(owner);
                    uint256[] memory tokenIds = new uint256[](tokenIdsLength);
                    TokenOwnership memory ownership;
                    for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
                        ownership = _ownershipAt(i);
                        if (ownership.burned) {
                            continue;
                        }
                        if (ownership.addr != address(0)) {
                            currOwnershipAddr = ownership.addr;
                        }
                        if (currOwnershipAddr == owner) {
                            tokenIds[tokenIdsIdx++] = i;
                        }
                    }
                    return tokenIds;
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        import '../IERC721AUpgradeable.sol';
        /**
         * @dev Interface of ERC721AQueryable.
         */
        interface IERC721AQueryableUpgradeable is IERC721AUpgradeable {
            /**
             * Invalid query range (`start` >= `stop`).
             */
            error InvalidQueryRange();
            /**
             * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
             *
             * If the `tokenId` is out of bounds:
             *
             * - `addr = address(0)`
             * - `startTimestamp = 0`
             * - `burned = false`
             * - `extraData = 0`
             *
             * If the `tokenId` is burned:
             *
             * - `addr = <Address of owner before token was burned>`
             * - `startTimestamp = <Timestamp when token was burned>`
             * - `burned = true`
             * - `extraData = <Extra data when token was burned>`
             *
             * Otherwise:
             *
             * - `addr = <Address of owner>`
             * - `startTimestamp = <Timestamp of start of ownership>`
             * - `burned = false`
             * - `extraData = <Extra data at start of ownership>`
             */
            function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory);
            /**
             * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
             * See {ERC721AQueryable-explicitOwnershipOf}
             */
            function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory);
            /**
             * @dev Returns an array of token IDs owned by `owner`,
             * in the range [`start`, `stop`)
             * (i.e. `start <= tokenId < stop`).
             *
             * This function allows for tokens to be queried if the collection
             * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
             *
             * Requirements:
             *
             * - `start < stop`
             */
            function tokensOfOwnerIn(
                address owner,
                uint256 start,
                uint256 stop
            ) external view returns (uint256[] memory);
            /**
             * @dev Returns an array of token IDs owned by `owner`.
             *
             * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
             * It is meant to be called off-chain.
             *
             * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
             * multiple smaller scans if the collection is large enough to cause
             * an out-of-gas error (10K collections should be fine).
             */
            function tokensOfOwner(address owner) external view returns (uint256[] memory);
        }
        // SPDX-License-Identifier: MIT
        // ERC721A Contracts v4.2.3
        // Creator: Chiru Labs
        pragma solidity ^0.8.4;
        /**
         * @dev Interface of ERC721A.
         */
        interface IERC721AUpgradeable {
            /**
             * The caller must own the token or be an approved operator.
             */
            error ApprovalCallerNotOwnerNorApproved();
            /**
             * The token does not exist.
             */
            error ApprovalQueryForNonexistentToken();
            /**
             * Cannot query the balance for the zero address.
             */
            error BalanceQueryForZeroAddress();
            /**
             * Cannot mint to the zero address.
             */
            error MintToZeroAddress();
            /**
             * The quantity of tokens minted must be more than zero.
             */
            error MintZeroQuantity();
            /**
             * The token does not exist.
             */
            error OwnerQueryForNonexistentToken();
            /**
             * The caller must own the token or be an approved operator.
             */
            error TransferCallerNotOwnerNorApproved();
            /**
             * The token must be owned by `from`.
             */
            error TransferFromIncorrectOwner();
            /**
             * Cannot safely transfer to a contract that does not implement the
             * ERC721Receiver interface.
             */
            error TransferToNonERC721ReceiverImplementer();
            /**
             * Cannot transfer to the zero address.
             */
            error TransferToZeroAddress();
            /**
             * The token does not exist.
             */
            error URIQueryForNonexistentToken();
            /**
             * The `quantity` minted with ERC2309 exceeds the safety limit.
             */
            error MintERC2309QuantityExceedsLimit();
            /**
             * The `extraData` cannot be set on an unintialized ownership slot.
             */
            error OwnershipNotInitializedForExtraData();
            // =============================================================
            //                            STRUCTS
            // =============================================================
            struct TokenOwnership {
                // The address of the owner.
                address addr;
                // Stores the start time of ownership with minimal overhead for tokenomics.
                uint64 startTimestamp;
                // Whether the token has been burned.
                bool burned;
                // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
                uint24 extraData;
            }
            // =============================================================
            //                         TOKEN COUNTERS
            // =============================================================
            /**
             * @dev Returns the total number of tokens in existence.
             * Burned tokens will reduce the count.
             * To get the total number of tokens minted, please see {_totalMinted}.
             */
            function totalSupply() external view returns (uint256);
            // =============================================================
            //                            IERC165
            // =============================================================
            /**
             * @dev Returns true if this contract implements the interface defined by
             * `interfaceId`. See the corresponding
             * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
             * to learn more about how these ids are created.
             *
             * This function call must use less than 30000 gas.
             */
            function supportsInterface(bytes4 interfaceId) external view returns (bool);
            // =============================================================
            //                            IERC721
            // =============================================================
            /**
             * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
             */
            event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
            /**
             * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
             */
            event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
            /**
             * @dev Emitted when `owner` enables or disables
             * (`approved`) `operator` to manage all of its assets.
             */
            event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
            /**
             * @dev Returns the number of tokens in `owner`'s account.
             */
            function balanceOf(address owner) external view returns (uint256 balance);
            /**
             * @dev Returns the owner of the `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function ownerOf(uint256 tokenId) external view returns (address owner);
            /**
             * @dev Safely transfers `tokenId` token from `from` to `to`,
             * checking first that contract recipients are aware of the ERC721 protocol
             * to prevent tokens from being forever locked.
             *
             * Requirements:
             *
             * - `from` cannot be the zero address.
             * - `to` cannot be the zero address.
             * - `tokenId` token must exist and be owned by `from`.
             * - If the caller is not `from`, it must be have been allowed to move
             * this token by either {approve} or {setApprovalForAll}.
             * - If `to` refers to a smart contract, it must implement
             * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
             *
             * Emits a {Transfer} event.
             */
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId,
                bytes calldata data
            ) external payable;
            /**
             * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
             */
            function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
            ) external payable;
            /**
             * @dev Transfers `tokenId` from `from` to `to`.
             *
             * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
             * whenever possible.
             *
             * Requirements:
             *
             * - `from` cannot be the zero address.
             * - `to` cannot be the zero address.
             * - `tokenId` token must be owned by `from`.
             * - If the caller is not `from`, it must be approved to move this token
             * by either {approve} or {setApprovalForAll}.
             *
             * Emits a {Transfer} event.
             */
            function transferFrom(
                address from,
                address to,
                uint256 tokenId
            ) external payable;
            /**
             * @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 payable;
            /**
             * @dev Approve or remove `operator` as an operator for the caller.
             * Operators can call {transferFrom} or {safeTransferFrom}
             * for any token owned by the caller.
             *
             * Requirements:
             *
             * - The `operator` cannot be the caller.
             *
             * Emits an {ApprovalForAll} event.
             */
            function setApprovalForAll(address operator, bool _approved) external;
            /**
             * @dev Returns the account approved for `tokenId` token.
             *
             * Requirements:
             *
             * - `tokenId` must exist.
             */
            function getApproved(uint256 tokenId) external view returns (address operator);
            /**
             * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
             *
             * See {setApprovalForAll}.
             */
            function isApprovedForAll(address owner, address operator) external view returns (bool);
            // =============================================================
            //                        IERC721Metadata
            // =============================================================
            /**
             * @dev Returns the token collection name.
             */
            function name() external view returns (string memory);
            /**
             * @dev Returns the token collection symbol.
             */
            function symbol() external view returns (string memory);
            /**
             * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
             */
            function tokenURI(uint256 tokenId) external view returns (string memory);
            // =============================================================
            //                           IERC2309
            // =============================================================
            /**
             * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
             * (inclusive) is transferred from `from` to `to`, as defined in the
             * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
             *
             * See {_mintERC2309} for more details.
             */
            event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.13;
        interface IOperatorFilterRegistry {
            function isOperatorAllowed(address registrant, address operator) external view returns (bool);
            function register(address registrant) external;
            function registerAndSubscribe(address registrant, address subscription) external;
            function registerAndCopyEntries(address registrant, address registrantToCopy) external;
            function unregister(address addr) external;
            function updateOperator(address registrant, address operator, bool filtered) external;
            function updateOperators(address registrant, address[] calldata operators, bool filtered) external;
            function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;
            function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;
            function subscribe(address registrant, address registrantToSubscribe) external;
            function unsubscribe(address registrant, bool copyExistingEntries) external;
            function subscriptionOf(address addr) external returns (address registrant);
            function subscribers(address registrant) external returns (address[] memory);
            function subscriberAt(address registrant, uint256 index) external returns (address);
            function copyEntriesOf(address registrant, address registrantToCopy) external;
            function isOperatorFiltered(address registrant, address operator) external returns (bool);
            function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);
            function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);
            function filteredOperators(address addr) external returns (address[] memory);
            function filteredCodeHashes(address addr) external returns (bytes32[] memory);
            function filteredOperatorAt(address registrant, uint256 index) external returns (address);
            function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);
            function isRegistered(address addr) external returns (bool);
            function codeHashOf(address addr) external returns (bytes32);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.13;
        import {IOperatorFilterRegistry} from "../IOperatorFilterRegistry.sol";
        import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
        abstract contract OperatorFiltererUpgradeable is Initializable {
            error OperatorNotAllowed(address operator);
            IOperatorFilterRegistry constant operatorFilterRegistry =
                IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);
            function __OperatorFilterer_init(address subscriptionOrRegistrantToCopy, bool subscribe)
                internal
                onlyInitializing
            {
                // If an inheriting token contract is deployed to a network without the registry deployed, the modifier
                // will not revert, but the contract will need to be registered with the registry once it is deployed in
                // order for the modifier to filter addresses.
                if (address(operatorFilterRegistry).code.length > 0) {
                    if (!operatorFilterRegistry.isRegistered(address(this))) {
                        if (subscribe) {
                            operatorFilterRegistry.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);
                        } else {
                            if (subscriptionOrRegistrantToCopy != address(0)) {
                                operatorFilterRegistry.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);
                            } else {
                                operatorFilterRegistry.register(address(this));
                            }
                        }
                    }
                }
            }
            modifier onlyAllowedOperator(address from) virtual {
                // Check registry code length to facilitate testing in environments without a deployed registry.
                if (address(operatorFilterRegistry).code.length > 0) {
                    // Allow spending tokens from addresses with balance
                    // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred
                    // from an EOA.
                    if (from == msg.sender) {
                        _;
                        return;
                    }
                    if (!operatorFilterRegistry.isOperatorAllowed(address(this), msg.sender)) {
                        revert OperatorNotAllowed(msg.sender);
                    }
                }
                _;
            }
            modifier onlyAllowedOperatorApproval(address operator) virtual {
                // Check registry code length to facilitate testing in environments without a deployed registry.
                if (address(operatorFilterRegistry).code.length > 0) {
                    if (!operatorFilterRegistry.isOperatorAllowed(address(this), operator)) {
                        revert OperatorNotAllowed(operator);
                    }
                }
                _;
            }
        }
        

        File 4 of 4: GnosisSafe
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        import "./base/ModuleManager.sol";
        import "./base/OwnerManager.sol";
        import "./base/FallbackManager.sol";
        import "./base/GuardManager.sol";
        import "./common/EtherPaymentFallback.sol";
        import "./common/Singleton.sol";
        import "./common/SignatureDecoder.sol";
        import "./common/SecuredTokenTransfer.sol";
        import "./common/StorageAccessible.sol";
        import "./interfaces/ISignatureValidator.sol";
        import "./external/GnosisSafeMath.sol";
        /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
        /// @author Stefan George - <stefan@gnosis.io>
        /// @author Richard Meissner - <richard@gnosis.io>
        contract GnosisSafe is
            EtherPaymentFallback,
            Singleton,
            ModuleManager,
            OwnerManager,
            SignatureDecoder,
            SecuredTokenTransfer,
            ISignatureValidatorConstants,
            FallbackManager,
            StorageAccessible,
            GuardManager
        {
            using GnosisSafeMath for uint256;
            string public constant VERSION = "1.3.0";
            // keccak256(
            //     "EIP712Domain(uint256 chainId,address verifyingContract)"
            // );
            bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
            // keccak256(
            //     "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
            // );
            bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
            event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
            event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
            event SignMsg(bytes32 indexed msgHash);
            event ExecutionFailure(bytes32 txHash, uint256 payment);
            event ExecutionSuccess(bytes32 txHash, uint256 payment);
            uint256 public nonce;
            bytes32 private _deprecatedDomainSeparator;
            // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
            mapping(bytes32 => uint256) public signedMessages;
            // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
            mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
            // This constructor ensures that this contract can only be used as a master copy for Proxy contracts
            constructor() {
                // By setting the threshold it is not possible to call setup anymore,
                // so we create a Safe with 0 owners and threshold 1.
                // This is an unusable Safe, perfect for the singleton
                threshold = 1;
            }
            /// @dev Setup function sets initial storage of contract.
            /// @param _owners List of Safe owners.
            /// @param _threshold Number of required confirmations for a Safe transaction.
            /// @param to Contract address for optional delegate call.
            /// @param data Data payload for optional delegate call.
            /// @param fallbackHandler Handler for fallback calls to this contract
            /// @param paymentToken Token that should be used for the payment (0 is ETH)
            /// @param payment Value that should be paid
            /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
            function setup(
                address[] calldata _owners,
                uint256 _threshold,
                address to,
                bytes calldata data,
                address fallbackHandler,
                address paymentToken,
                uint256 payment,
                address payable paymentReceiver
            ) external {
                // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
                setupOwners(_owners, _threshold);
                if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
                // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
                setupModules(to, data);
                if (payment > 0) {
                    // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
                    // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
                    handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
                }
                emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
            }
            /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
            ///      Note: The fees are always transferred, even if the user transaction fails.
            /// @param to Destination address of Safe transaction.
            /// @param value Ether value of Safe transaction.
            /// @param data Data payload of Safe transaction.
            /// @param operation Operation type of Safe transaction.
            /// @param safeTxGas Gas that should be used for the Safe transaction.
            /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
            /// @param gasPrice Gas price that should be used for the payment calculation.
            /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
            /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
            /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
            function execTransaction(
                address to,
                uint256 value,
                bytes calldata data,
                Enum.Operation operation,
                uint256 safeTxGas,
                uint256 baseGas,
                uint256 gasPrice,
                address gasToken,
                address payable refundReceiver,
                bytes memory signatures
            ) public payable virtual returns (bool success) {
                bytes32 txHash;
                // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                {
                    bytes memory txHashData =
                        encodeTransactionData(
                            // Transaction info
                            to,
                            value,
                            data,
                            operation,
                            safeTxGas,
                            // Payment info
                            baseGas,
                            gasPrice,
                            gasToken,
                            refundReceiver,
                            // Signature info
                            nonce
                        );
                    // Increase nonce and execute transaction.
                    nonce++;
                    txHash = keccak256(txHashData);
                    checkSignatures(txHash, txHashData, signatures);
                }
                address guard = getGuard();
                {
                    if (guard != address(0)) {
                        Guard(guard).checkTransaction(
                            // Transaction info
                            to,
                            value,
                            data,
                            operation,
                            safeTxGas,
                            // Payment info
                            baseGas,
                            gasPrice,
                            gasToken,
                            refundReceiver,
                            // Signature info
                            signatures,
                            msg.sender
                        );
                    }
                }
                // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
                // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
                require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
                // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                {
                    uint256 gasUsed = gasleft();
                    // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
                    // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
                    success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
                    gasUsed = gasUsed.sub(gasleft());
                    // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
                    // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
                    require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
                    // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
                    uint256 payment = 0;
                    if (gasPrice > 0) {
                        payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
                    }
                    if (success) emit ExecutionSuccess(txHash, payment);
                    else emit ExecutionFailure(txHash, payment);
                }
                {
                    if (guard != address(0)) {
                        Guard(guard).checkAfterExecution(txHash, success);
                    }
                }
            }
            function handlePayment(
                uint256 gasUsed,
                uint256 baseGas,
                uint256 gasPrice,
                address gasToken,
                address payable refundReceiver
            ) private returns (uint256 payment) {
                // solhint-disable-next-line avoid-tx-origin
                address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
                if (gasToken == address(0)) {
                    // For ETH we will only adjust the gas price to not be higher than the actual used gas price
                    payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
                    require(receiver.send(payment), "GS011");
                } else {
                    payment = gasUsed.add(baseGas).mul(gasPrice);
                    require(transferToken(gasToken, receiver, payment), "GS012");
                }
            }
            /**
             * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
             * @param dataHash Hash of the data (could be either a message hash or transaction hash)
             * @param data That should be signed (this is passed to an external validator contract)
             * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
             */
            function checkSignatures(
                bytes32 dataHash,
                bytes memory data,
                bytes memory signatures
            ) public view {
                // Load threshold to avoid multiple storage loads
                uint256 _threshold = threshold;
                // Check that a threshold is set
                require(_threshold > 0, "GS001");
                checkNSignatures(dataHash, data, signatures, _threshold);
            }
            /**
             * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
             * @param dataHash Hash of the data (could be either a message hash or transaction hash)
             * @param data That should be signed (this is passed to an external validator contract)
             * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
             * @param requiredSignatures Amount of required valid signatures.
             */
            function checkNSignatures(
                bytes32 dataHash,
                bytes memory data,
                bytes memory signatures,
                uint256 requiredSignatures
            ) public view {
                // Check that the provided signature data is not too short
                require(signatures.length >= requiredSignatures.mul(65), "GS020");
                // There cannot be an owner with address 0.
                address lastOwner = address(0);
                address currentOwner;
                uint8 v;
                bytes32 r;
                bytes32 s;
                uint256 i;
                for (i = 0; i < requiredSignatures; i++) {
                    (v, r, s) = signatureSplit(signatures, i);
                    if (v == 0) {
                        // If v is 0 then it is a contract signature
                        // When handling contract signatures the address of the contract is encoded into r
                        currentOwner = address(uint160(uint256(r)));
                        // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
                        // This check is not completely accurate, since it is possible that more signatures than the threshold are send.
                        // Here we only check that the pointer is not pointing inside the part that is being processed
                        require(uint256(s) >= requiredSignatures.mul(65), "GS021");
                        // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
                        require(uint256(s).add(32) <= signatures.length, "GS022");
                        // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
                        uint256 contractSignatureLen;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            contractSignatureLen := mload(add(add(signatures, s), 0x20))
                        }
                        require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
                        // Check signature
                        bytes memory contractSignature;
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
                            contractSignature := add(add(signatures, s), 0x20)
                        }
                        require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
                    } else if (v == 1) {
                        // If v is 1 then it is an approved hash
                        // When handling approved hashes the address of the approver is encoded into r
                        currentOwner = address(uint160(uint256(r)));
                        // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
                        require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
                    } else if (v > 30) {
                        // If v > 30 then default va (27,28) has been adjusted for eth_sign flow
                        // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
                        currentOwner = ecrecover(keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
        32", dataHash)), v - 4, r, s);
                    } else {
                        // Default is the ecrecover flow with the provided data hash
                        // Use ecrecover with the messageHash for EOA signatures
                        currentOwner = ecrecover(dataHash, v, r, s);
                    }
                    require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
                    lastOwner = currentOwner;
                }
            }
            /// @dev Allows to estimate a Safe transaction.
            ///      This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
            ///      Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
            /// @param to Destination address of Safe transaction.
            /// @param value Ether value of Safe transaction.
            /// @param data Data payload of Safe transaction.
            /// @param operation Operation type of Safe transaction.
            /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
            /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
            function requiredTxGas(
                address to,
                uint256 value,
                bytes calldata data,
                Enum.Operation operation
            ) external returns (uint256) {
                uint256 startGas = gasleft();
                // We don't provide an error message here, as we use it to return the estimate
                require(execute(to, value, data, operation, gasleft()));
                uint256 requiredGas = startGas - gasleft();
                // Convert response to string and return via error message
                revert(string(abi.encodePacked(requiredGas)));
            }
            /**
             * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
             * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
             */
            function approveHash(bytes32 hashToApprove) external {
                require(owners[msg.sender] != address(0), "GS030");
                approvedHashes[msg.sender][hashToApprove] = 1;
                emit ApproveHash(hashToApprove, msg.sender);
            }
            /// @dev Returns the chain id used by this contract.
            function getChainId() public view returns (uint256) {
                uint256 id;
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    id := chainid()
                }
                return id;
            }
            function domainSeparator() public view returns (bytes32) {
                return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
            }
            /// @dev Returns the bytes that are hashed to be signed by owners.
            /// @param to Destination address.
            /// @param value Ether value.
            /// @param data Data payload.
            /// @param operation Operation type.
            /// @param safeTxGas Gas that should be used for the safe transaction.
            /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
            /// @param gasPrice Maximum gas price that should be used for this transaction.
            /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
            /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
            /// @param _nonce Transaction nonce.
            /// @return Transaction hash bytes.
            function encodeTransactionData(
                address to,
                uint256 value,
                bytes calldata data,
                Enum.Operation operation,
                uint256 safeTxGas,
                uint256 baseGas,
                uint256 gasPrice,
                address gasToken,
                address refundReceiver,
                uint256 _nonce
            ) public view returns (bytes memory) {
                bytes32 safeTxHash =
                    keccak256(
                        abi.encode(
                            SAFE_TX_TYPEHASH,
                            to,
                            value,
                            keccak256(data),
                            operation,
                            safeTxGas,
                            baseGas,
                            gasPrice,
                            gasToken,
                            refundReceiver,
                            _nonce
                        )
                    );
                return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
            }
            /// @dev Returns hash to be signed by owners.
            /// @param to Destination address.
            /// @param value Ether value.
            /// @param data Data payload.
            /// @param operation Operation type.
            /// @param safeTxGas Fas that should be used for the safe transaction.
            /// @param baseGas Gas costs for data used to trigger the safe transaction.
            /// @param gasPrice Maximum gas price that should be used for this transaction.
            /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
            /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
            /// @param _nonce Transaction nonce.
            /// @return Transaction hash.
            function getTransactionHash(
                address to,
                uint256 value,
                bytes calldata data,
                Enum.Operation operation,
                uint256 safeTxGas,
                uint256 baseGas,
                uint256 gasPrice,
                address gasToken,
                address refundReceiver,
                uint256 _nonce
            ) public view returns (bytes32) {
                return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        import "../common/Enum.sol";
        /// @title Executor - A contract that can execute transactions
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract Executor {
            function execute(
                address to,
                uint256 value,
                bytes memory data,
                Enum.Operation operation,
                uint256 txGas
            ) internal returns (bool success) {
                if (operation == Enum.Operation.DelegateCall) {
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                    }
                } else {
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
                    }
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        import "../common/SelfAuthorized.sol";
        /// @title Fallback Manager - A contract that manages fallback calls made to this contract
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract FallbackManager is SelfAuthorized {
            event ChangedFallbackHandler(address handler);
            // keccak256("fallback_manager.handler.address")
            bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
            function internalSetFallbackHandler(address handler) internal {
                bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    sstore(slot, handler)
                }
            }
            /// @dev Allows to add a contract to handle fallback calls.
            ///      Only fallback calls without value and with data will be forwarded.
            ///      This can only be done via a Safe transaction.
            /// @param handler contract to handle fallbacks calls.
            function setFallbackHandler(address handler) public authorized {
                internalSetFallbackHandler(handler);
                emit ChangedFallbackHandler(handler);
            }
            // solhint-disable-next-line payable-fallback,no-complex-fallback
            fallback() external {
                bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let handler := sload(slot)
                    if iszero(handler) {
                        return(0, 0)
                    }
                    calldatacopy(0, 0, calldatasize())
                    // The msg.sender address is shifted to the left by 12 bytes to remove the padding
                    // Then the address without padding is stored right after the calldata
                    mstore(calldatasize(), shl(96, caller()))
                    // Add 20 bytes for the address appended add the end
                    let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
                    returndatacopy(0, 0, returndatasize())
                    if iszero(success) {
                        revert(0, returndatasize())
                    }
                    return(0, returndatasize())
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        import "../common/Enum.sol";
        import "../common/SelfAuthorized.sol";
        interface Guard {
            function checkTransaction(
                address to,
                uint256 value,
                bytes memory data,
                Enum.Operation operation,
                uint256 safeTxGas,
                uint256 baseGas,
                uint256 gasPrice,
                address gasToken,
                address payable refundReceiver,
                bytes memory signatures,
                address msgSender
            ) external;
            function checkAfterExecution(bytes32 txHash, bool success) external;
        }
        /// @title Fallback Manager - A contract that manages fallback calls made to this contract
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract GuardManager is SelfAuthorized {
            event ChangedGuard(address guard);
            // keccak256("guard_manager.guard.address")
            bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
            /// @dev Set a guard that checks transactions before execution
            /// @param guard The address of the guard to be used or the 0 address to disable the guard
            function setGuard(address guard) external authorized {
                bytes32 slot = GUARD_STORAGE_SLOT;
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    sstore(slot, guard)
                }
                emit ChangedGuard(guard);
            }
            function getGuard() internal view returns (address guard) {
                bytes32 slot = GUARD_STORAGE_SLOT;
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    guard := sload(slot)
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        import "../common/Enum.sol";
        import "../common/SelfAuthorized.sol";
        import "./Executor.sol";
        /// @title Module Manager - A contract that manages modules that can execute transactions via this contract
        /// @author Stefan George - <stefan@gnosis.pm>
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract ModuleManager is SelfAuthorized, Executor {
            event EnabledModule(address module);
            event DisabledModule(address module);
            event ExecutionFromModuleSuccess(address indexed module);
            event ExecutionFromModuleFailure(address indexed module);
            address internal constant SENTINEL_MODULES = address(0x1);
            mapping(address => address) internal modules;
            function setupModules(address to, bytes memory data) internal {
                require(modules[SENTINEL_MODULES] == address(0), "GS100");
                modules[SENTINEL_MODULES] = SENTINEL_MODULES;
                if (to != address(0))
                    // Setup has to complete successfully or transaction fails.
                    require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
            }
            /// @dev Allows to add a module to the whitelist.
            ///      This can only be done via a Safe transaction.
            /// @notice Enables the module `module` for the Safe.
            /// @param module Module to be whitelisted.
            function enableModule(address module) public authorized {
                // Module address cannot be null or sentinel.
                require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                // Module cannot be added twice.
                require(modules[module] == address(0), "GS102");
                modules[module] = modules[SENTINEL_MODULES];
                modules[SENTINEL_MODULES] = module;
                emit EnabledModule(module);
            }
            /// @dev Allows to remove a module from the whitelist.
            ///      This can only be done via a Safe transaction.
            /// @notice Disables the module `module` for the Safe.
            /// @param prevModule Module that pointed to the module to be removed in the linked list
            /// @param module Module to be removed.
            function disableModule(address prevModule, address module) public authorized {
                // Validate module address and check that it corresponds to module index.
                require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                require(modules[prevModule] == module, "GS103");
                modules[prevModule] = modules[module];
                modules[module] = address(0);
                emit DisabledModule(module);
            }
            /// @dev Allows a Module to execute a Safe transaction without any further confirmations.
            /// @param to Destination address of module transaction.
            /// @param value Ether value of module transaction.
            /// @param data Data payload of module transaction.
            /// @param operation Operation type of module transaction.
            function execTransactionFromModule(
                address to,
                uint256 value,
                bytes memory data,
                Enum.Operation operation
            ) public virtual returns (bool success) {
                // Only whitelisted modules are allowed.
                require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
                // Execute transaction without further confirmations.
                success = execute(to, value, data, operation, gasleft());
                if (success) emit ExecutionFromModuleSuccess(msg.sender);
                else emit ExecutionFromModuleFailure(msg.sender);
            }
            /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
            /// @param to Destination address of module transaction.
            /// @param value Ether value of module transaction.
            /// @param data Data payload of module transaction.
            /// @param operation Operation type of module transaction.
            function execTransactionFromModuleReturnData(
                address to,
                uint256 value,
                bytes memory data,
                Enum.Operation operation
            ) public returns (bool success, bytes memory returnData) {
                success = execTransactionFromModule(to, value, data, operation);
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    // Load free memory location
                    let ptr := mload(0x40)
                    // We allocate memory for the return data by setting the free memory location to
                    // current free memory location + data size + 32 bytes for data size value
                    mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
                    // Store the size
                    mstore(ptr, returndatasize())
                    // Store the data
                    returndatacopy(add(ptr, 0x20), 0, returndatasize())
                    // Point the return data to the correct memory location
                    returnData := ptr
                }
            }
            /// @dev Returns if an module is enabled
            /// @return True if the module is enabled
            function isModuleEnabled(address module) public view returns (bool) {
                return SENTINEL_MODULES != module && modules[module] != address(0);
            }
            /// @dev Returns array of modules.
            /// @param start Start of the page.
            /// @param pageSize Maximum number of modules that should be returned.
            /// @return array Array of modules.
            /// @return next Start of the next page.
            function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
                // Init array with max page size
                array = new address[](pageSize);
                // Populate return array
                uint256 moduleCount = 0;
                address currentModule = modules[start];
                while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
                    array[moduleCount] = currentModule;
                    currentModule = modules[currentModule];
                    moduleCount++;
                }
                next = currentModule;
                // Set correct size of returned array
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    mstore(array, moduleCount)
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        import "../common/SelfAuthorized.sol";
        /// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
        /// @author Stefan George - <stefan@gnosis.pm>
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract OwnerManager is SelfAuthorized {
            event AddedOwner(address owner);
            event RemovedOwner(address owner);
            event ChangedThreshold(uint256 threshold);
            address internal constant SENTINEL_OWNERS = address(0x1);
            mapping(address => address) internal owners;
            uint256 internal ownerCount;
            uint256 internal threshold;
            /// @dev Setup function sets initial storage of contract.
            /// @param _owners List of Safe owners.
            /// @param _threshold Number of required confirmations for a Safe transaction.
            function setupOwners(address[] memory _owners, uint256 _threshold) internal {
                // Threshold can only be 0 at initialization.
                // Check ensures that setup function can only be called once.
                require(threshold == 0, "GS200");
                // Validate that threshold is smaller than number of added owners.
                require(_threshold <= _owners.length, "GS201");
                // There has to be at least one Safe owner.
                require(_threshold >= 1, "GS202");
                // Initializing Safe owners.
                address currentOwner = SENTINEL_OWNERS;
                for (uint256 i = 0; i < _owners.length; i++) {
                    // Owner address cannot be null.
                    address owner = _owners[i];
                    require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
                    // No duplicate owners allowed.
                    require(owners[owner] == address(0), "GS204");
                    owners[currentOwner] = owner;
                    currentOwner = owner;
                }
                owners[currentOwner] = SENTINEL_OWNERS;
                ownerCount = _owners.length;
                threshold = _threshold;
            }
            /// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
            ///      This can only be done via a Safe transaction.
            /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
            /// @param owner New owner address.
            /// @param _threshold New threshold.
            function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
                // Owner address cannot be null, the sentinel or the Safe itself.
                require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
                // No duplicate owners allowed.
                require(owners[owner] == address(0), "GS204");
                owners[owner] = owners[SENTINEL_OWNERS];
                owners[SENTINEL_OWNERS] = owner;
                ownerCount++;
                emit AddedOwner(owner);
                // Change threshold if threshold was changed.
                if (threshold != _threshold) changeThreshold(_threshold);
            }
            /// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
            ///      This can only be done via a Safe transaction.
            /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
            /// @param prevOwner Owner that pointed to the owner to be removed in the linked list
            /// @param owner Owner address to be removed.
            /// @param _threshold New threshold.
            function removeOwner(
                address prevOwner,
                address owner,
                uint256 _threshold
            ) public authorized {
                // Only allow to remove an owner, if threshold can still be reached.
                require(ownerCount - 1 >= _threshold, "GS201");
                // Validate owner address and check that it corresponds to owner index.
                require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
                require(owners[prevOwner] == owner, "GS205");
                owners[prevOwner] = owners[owner];
                owners[owner] = address(0);
                ownerCount--;
                emit RemovedOwner(owner);
                // Change threshold if threshold was changed.
                if (threshold != _threshold) changeThreshold(_threshold);
            }
            /// @dev Allows to swap/replace an owner from the Safe with another address.
            ///      This can only be done via a Safe transaction.
            /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
            /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
            /// @param oldOwner Owner address to be replaced.
            /// @param newOwner New owner address.
            function swapOwner(
                address prevOwner,
                address oldOwner,
                address newOwner
            ) public authorized {
                // Owner address cannot be null, the sentinel or the Safe itself.
                require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
                // No duplicate owners allowed.
                require(owners[newOwner] == address(0), "GS204");
                // Validate oldOwner address and check that it corresponds to owner index.
                require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
                require(owners[prevOwner] == oldOwner, "GS205");
                owners[newOwner] = owners[oldOwner];
                owners[prevOwner] = newOwner;
                owners[oldOwner] = address(0);
                emit RemovedOwner(oldOwner);
                emit AddedOwner(newOwner);
            }
            /// @dev Allows to update the number of required confirmations by Safe owners.
            ///      This can only be done via a Safe transaction.
            /// @notice Changes the threshold of the Safe to `_threshold`.
            /// @param _threshold New threshold.
            function changeThreshold(uint256 _threshold) public authorized {
                // Validate that threshold is smaller than number of owners.
                require(_threshold <= ownerCount, "GS201");
                // There has to be at least one Safe owner.
                require(_threshold >= 1, "GS202");
                threshold = _threshold;
                emit ChangedThreshold(threshold);
            }
            function getThreshold() public view returns (uint256) {
                return threshold;
            }
            function isOwner(address owner) public view returns (bool) {
                return owner != SENTINEL_OWNERS && owners[owner] != address(0);
            }
            /// @dev Returns array of owners.
            /// @return Array of Safe owners.
            function getOwners() public view returns (address[] memory) {
                address[] memory array = new address[](ownerCount);
                // populate return array
                uint256 index = 0;
                address currentOwner = owners[SENTINEL_OWNERS];
                while (currentOwner != SENTINEL_OWNERS) {
                    array[index] = currentOwner;
                    currentOwner = owners[currentOwner];
                    index++;
                }
                return array;
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title Enum - Collection of enums
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract Enum {
            enum Operation {Call, DelegateCall}
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract EtherPaymentFallback {
            event SafeReceived(address indexed sender, uint256 value);
            /// @dev Fallback function accepts Ether transactions.
            receive() external payable {
                emit SafeReceived(msg.sender, msg.value);
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title SecuredTokenTransfer - Secure token transfer
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract SecuredTokenTransfer {
            /// @dev Transfers a token and returns if it was a success
            /// @param token Token that should be transferred
            /// @param receiver Receiver to whom the token should be transferred
            /// @param amount The amount of tokens that should be transferred
            function transferToken(
                address token,
                address receiver,
                uint256 amount
            ) internal returns (bool transferred) {
                // 0xa9059cbb - keccack("transfer(address,uint256)")
                bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    // We write the return value to scratch space.
                    // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
                    let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                    switch returndatasize()
                        case 0 {
                            transferred := success
                        }
                        case 0x20 {
                            transferred := iszero(or(iszero(success), iszero(mload(0))))
                        }
                        default {
                            transferred := 0
                        }
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title SelfAuthorized - authorizes current contract to perform actions
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract SelfAuthorized {
            function requireSelfCall() private view {
                require(msg.sender == address(this), "GS031");
            }
            modifier authorized() {
                // This is a function call as it minimized the bytecode size
                requireSelfCall();
                _;
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title SignatureDecoder - Decodes signatures that a encoded as bytes
        /// @author Richard Meissner - <richard@gnosis.pm>
        contract SignatureDecoder {
            /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
            /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
            /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
            /// @param signatures concatenated rsv signatures
            function signatureSplit(bytes memory signatures, uint256 pos)
                internal
                pure
                returns (
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                )
            {
                // The signature format is a compact form of:
                //   {bytes32 r}{bytes32 s}{uint8 v}
                // Compact means, uint8 is not padded to 32 bytes.
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let signaturePos := mul(0x41, pos)
                    r := mload(add(signatures, add(signaturePos, 0x20)))
                    s := mload(add(signatures, add(signaturePos, 0x40)))
                    // Here we are loading the last 32 bytes, including 31 bytes
                    // of 's'. There is no 'mload8' to do this.
                    //
                    // 'byte' is not working due to the Solidity parser, so lets
                    // use the second best option, 'and'
                    v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title Singleton - Base for singleton contracts (should always be first super contract)
        ///         This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
        /// @author Richard Meissner - <richard@gnosis.io>
        contract Singleton {
            // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
            // It should also always be ensured that the address is stored alone (uses a full word)
            address private singleton;
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
        /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
        contract StorageAccessible {
            /**
             * @dev Reads `length` bytes of storage in the currents contract
             * @param offset - the offset in the current contract's storage in words to start reading from
             * @param length - the number of words (32 bytes) of data to read
             * @return the bytes that were read.
             */
            function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
                bytes memory result = new bytes(length * 32);
                for (uint256 index = 0; index < length; index++) {
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let word := sload(add(offset, index))
                        mstore(add(add(result, 0x20), mul(index, 0x20)), word)
                    }
                }
                return result;
            }
            /**
             * @dev Performs a delegetecall on a targetContract in the context of self.
             * Internally reverts execution to avoid side effects (making it static).
             *
             * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
             * Specifically, the `returndata` after a call to this method will be:
             * `success:bool || response.length:uint256 || response:bytes`.
             *
             * @param targetContract Address of the contract containing the code to execute.
             * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
             */
            function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
                    mstore(0x00, success)
                    mstore(0x20, returndatasize())
                    returndatacopy(0x40, 0, returndatasize())
                    revert(0, add(returndatasize(), 0x40))
                }
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        /**
         * @title GnosisSafeMath
         * @dev Math operations with safety checks that revert on error
         * Renamed from SafeMath to GnosisSafeMath to avoid conflicts
         * TODO: remove once open zeppelin update to solc 0.5.0
         */
        library GnosisSafeMath {
            /**
             * @dev Multiplies two numbers, reverts on overflow.
             */
            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                // benefit is lost if 'b' is also tested.
                // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                if (a == 0) {
                    return 0;
                }
                uint256 c = a * b;
                require(c / a == b);
                return c;
            }
            /**
             * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
             */
            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b <= a);
                uint256 c = a - b;
                return c;
            }
            /**
             * @dev Adds two numbers, reverts on overflow.
             */
            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                uint256 c = a + b;
                require(c >= a);
                return c;
            }
            /**
             * @dev Returns the largest of two numbers.
             */
            function max(uint256 a, uint256 b) internal pure returns (uint256) {
                return a >= b ? a : b;
            }
        }
        // SPDX-License-Identifier: LGPL-3.0-only
        pragma solidity >=0.7.0 <0.9.0;
        contract ISignatureValidatorConstants {
            // bytes4(keccak256("isValidSignature(bytes,bytes)")
            bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
        }
        abstract contract ISignatureValidator is ISignatureValidatorConstants {
            /**
             * @dev Should return whether the signature provided is valid for the provided data
             * @param _data Arbitrary length data signed on the behalf of address(this)
             * @param _signature Signature byte array associated with _data
             *
             * MUST return the bytes4 magic value 0x20c13b0b when function passes.
             * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
             * MUST allow external calls
             */
            function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
        }