{"language":"Solidity","sources":{"@openzeppelin/contracts/access/Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},"@openzeppelin/contracts/interfaces/IERC2981.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC2981.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n */\ninterface IERC2981 is IERC165 {\n    /**\n     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n     *\n     * NOTE: ERC-2981 allows setting the royalty to 100% of the price. In that case all the price would be sent to the\n     * royalty receiver and 0 tokens to the seller. Contracts dealing with royalty should consider empty transfers.\n     */\n    function royaltyInfo(\n        uint256 tokenId,\n        uint256 salePrice\n    ) external view returns (address receiver, uint256 royaltyAmount);\n}\n"},"@openzeppelin/contracts/interfaces/IERC5267.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)\n\npragma solidity >=0.4.16;\n\ninterface IERC5267 {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"},"@openzeppelin/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)\npragma solidity >=0.8.4;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"@openzeppelin/contracts/token/ERC20/ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n    mapping(address account => uint256) private _balances;\n\n    mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * Both values are immutable: they can only be set once during construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /// @inheritdoc IERC20\n    function totalSupply() public view virtual returns (uint256) {\n        return _totalSupply;\n    }\n\n    /// @inheritdoc IERC20\n    function balanceOf(address account) public view virtual returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            _totalSupply += value;\n        } else {\n            uint256 fromBalance = _balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                _balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                _totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                _balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        _allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance < type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},"@openzeppelin/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC20} from \"../ERC20.sol\";\nimport {Context} from \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n    /**\n     * @dev Destroys a `value` amount of tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 value) public virtual {\n        _burn(_msgSender(), value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, deducting from\n     * the caller's allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for ``accounts``'s tokens of at least\n     * `value`.\n     */\n    function burnFrom(address account, uint256 value) public virtual {\n        _spendAllowance(account, _msgSender(), value);\n        _burn(account, value);\n    }\n}\n"},"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"@openzeppelin/contracts/token/ERC721/ERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"./IERC721.sol\";\nimport {IERC721Metadata} from \"./extensions/IERC721Metadata.sol\";\nimport {ERC721Utils} from \"./utils/ERC721Utils.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {Strings} from \"../../utils/Strings.sol\";\nimport {IERC165, ERC165} from \"../../utils/introspection/ERC165.sol\";\nimport {IERC721Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {\n    using Strings for uint256;\n\n    // Token name\n    string private _name;\n\n    // Token symbol\n    string private _symbol;\n\n    mapping(uint256 tokenId => address) private _owners;\n\n    mapping(address owner => uint256) private _balances;\n\n    mapping(uint256 tokenId => address) private _tokenApprovals;\n\n    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /// @inheritdoc IERC721\n    function balanceOf(address owner) public view virtual returns (uint256) {\n        if (owner == address(0)) {\n            revert ERC721InvalidOwner(address(0));\n        }\n        return _balances[owner];\n    }\n\n    /// @inheritdoc IERC721\n    function ownerOf(uint256 tokenId) public view virtual returns (address) {\n        return _requireOwned(tokenId);\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n        _requireOwned(tokenId);\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overridden in child contracts.\n     */\n    function _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n\n    /// @inheritdoc IERC721\n    function approve(address to, uint256 tokenId) public virtual {\n        _approve(to, tokenId, _msgSender());\n    }\n\n    /// @inheritdoc IERC721\n    function getApproved(uint256 tokenId) public view virtual returns (address) {\n        _requireOwned(tokenId);\n\n        return _getApproved(tokenId);\n    }\n\n    /// @inheritdoc IERC721\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /// @inheritdoc IERC721\n    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n        return _operatorApprovals[owner][operator];\n    }\n\n    /// @inheritdoc IERC721\n    function transferFrom(address from, address to, uint256 tokenId) public virtual {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n        address previousOwner = _update(to, tokenId, _msgSender());\n        if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /// @inheritdoc IERC721\n    function safeTransferFrom(address from, address to, uint256 tokenId) public {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /// @inheritdoc IERC721\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n        transferFrom(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n     *\n     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n     */\n    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n        return _owners[tokenId];\n    }\n\n    /**\n     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n     */\n    function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n        return _tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n     * particular (ignoring whether it is owned by `owner`).\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n        return\n            spender != address(0) &&\n            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n    }\n\n    /**\n     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n     * Reverts if:\n     * - `spender` does not have approval from `owner` for `tokenId`.\n     * - `spender` does not have approval to manage all of `owner`'s assets.\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n        if (!_isAuthorized(owner, spender, tokenId)) {\n            if (owner == address(0)) {\n                revert ERC721NonexistentToken(tokenId);\n            } else {\n                revert ERC721InsufficientApproval(spender, tokenId);\n            }\n        }\n    }\n\n    /**\n     * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n     *\n     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n     *\n     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n     * remain consistent with one another.\n     */\n    function _increaseBalance(address account, uint128 value) internal virtual {\n        unchecked {\n            _balances[account] += value;\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n        address from = _ownerOf(tokenId);\n\n        // Perform (optional) operator check\n        if (auth != address(0)) {\n            _checkAuthorized(from, auth, tokenId);\n        }\n\n        // Execute the update\n        if (from != address(0)) {\n            // Clear approval. No need to re-authorize or emit the Approval event\n            _approve(address(0), tokenId, address(0), false);\n\n            unchecked {\n                _balances[from] -= 1;\n            }\n        }\n\n        if (to != address(0)) {\n            unchecked {\n                _balances[to] += 1;\n            }\n        }\n\n        _owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n\n        return from;\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner != address(0)) {\n            revert ERC721InvalidSender(address(0));\n        }\n    }\n\n    /**\n     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n        _mint(to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     * This is an internal function that does not check if the sender is authorized to operate on the token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal {\n        address previousOwner = _update(address(0), tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(address from, address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        } else if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n     * are aware of the ERC-721 standard to prevent tokens from being forever locked.\n     *\n     * `data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is like {safeTransferFrom} in the sense that it invokes\n     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `tokenId` token must exist and be owned by `from`.\n     * - `to` cannot be the zero address.\n     * - `from` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId) internal {\n        _safeTransfer(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n        _transfer(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n     * either the owner of the token, or approved to operate on all tokens held by this owner.\n     *\n     * Emits an {Approval} event.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address to, uint256 tokenId, address auth) internal {\n        _approve(to, tokenId, auth, true);\n    }\n\n    /**\n     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n     * emitted in the context of transfers.\n     */\n    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n        // Avoid reading the owner unless necessary\n        if (emitEvent || auth != address(0)) {\n            address owner = _requireOwned(tokenId);\n\n            // We do not use _isAuthorized because single-token approvals should not be able to call approve\n            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n                revert ERC721InvalidApprover(auth);\n            }\n\n            if (emitEvent) {\n                emit Approval(owner, to, tokenId);\n            }\n        }\n\n        _tokenApprovals[tokenId] = to;\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Requirements:\n     * - operator can't be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n        if (operator == address(0)) {\n            revert ERC721InvalidOperator(operator);\n        }\n        _operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n     * Returns the owner.\n     *\n     * Overrides to ownership logic should be done to {_ownerOf}.\n     */\n    function _requireOwned(uint256 tokenId) internal view returns (address) {\n        address owner = _ownerOf(tokenId);\n        if (owner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n        return owner;\n    }\n}\n"},"@openzeppelin/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC-721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n     *   {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity >=0.5.0;\n\n/**\n * @title ERC-721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC-721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n     * reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"},"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/utils/ERC721Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721Receiver} from \"../IERC721Receiver.sol\";\nimport {IERC721Errors} from \"../../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Library that provide common ERC-721 utility functions.\n *\n * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].\n *\n * _Available since v5.1._\n */\nlibrary ERC721Utils {\n    /**\n     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}\n     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).\n     *\n     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).\n     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept\n     * the transfer.\n     */\n    function checkOnERC721Received(\n        address operator,\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) internal {\n        if (to.code.length > 0) {\n            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {\n                if (retval != IERC721Receiver.onERC721Received.selector) {\n                    // Token rejected\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    // non-IERC721Receiver implementer\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                } else {\n                    assembly (\"memory-safe\") {\n                        revert(add(reason, 0x20), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n}\n"},"@openzeppelin/contracts/token/common/ERC2981.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/common/ERC2981.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC2981} from \"../../interfaces/IERC2981.sol\";\nimport {IERC165, ERC165} from \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.\n *\n * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for\n * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.\n *\n * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the\n * fee is specified in basis points by default.\n *\n * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See\n * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the ERC. Marketplaces are expected to\n * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.\n */\nabstract contract ERC2981 is IERC2981, ERC165 {\n    struct RoyaltyInfo {\n        address receiver;\n        uint96 royaltyFraction;\n    }\n\n    RoyaltyInfo private _defaultRoyaltyInfo;\n    mapping(uint256 tokenId => RoyaltyInfo) private _tokenRoyaltyInfo;\n\n    /**\n     * @dev The default royalty set is invalid (eg. (numerator / denominator) >= 1).\n     */\n    error ERC2981InvalidDefaultRoyalty(uint256 numerator, uint256 denominator);\n\n    /**\n     * @dev The default royalty receiver is invalid.\n     */\n    error ERC2981InvalidDefaultRoyaltyReceiver(address receiver);\n\n    /**\n     * @dev The royalty set for a specific `tokenId` is invalid (eg. (numerator / denominator) >= 1).\n     */\n    error ERC2981InvalidTokenRoyalty(uint256 tokenId, uint256 numerator, uint256 denominator);\n\n    /**\n     * @dev The royalty receiver for `tokenId` is invalid.\n     */\n    error ERC2981InvalidTokenRoyaltyReceiver(uint256 tokenId, address receiver);\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {\n        return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /// @inheritdoc IERC2981\n    function royaltyInfo(\n        uint256 tokenId,\n        uint256 salePrice\n    ) public view virtual returns (address receiver, uint256 amount) {\n        RoyaltyInfo storage _royaltyInfo = _tokenRoyaltyInfo[tokenId];\n        address royaltyReceiver = _royaltyInfo.receiver;\n        uint96 royaltyFraction = _royaltyInfo.royaltyFraction;\n\n        if (royaltyReceiver == address(0)) {\n            royaltyReceiver = _defaultRoyaltyInfo.receiver;\n            royaltyFraction = _defaultRoyaltyInfo.royaltyFraction;\n        }\n\n        uint256 royaltyAmount = (salePrice * royaltyFraction) / _feeDenominator();\n\n        return (royaltyReceiver, royaltyAmount);\n    }\n\n    /**\n     * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a\n     * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an\n     * override.\n     */\n    function _feeDenominator() internal pure virtual returns (uint96) {\n        return 10000;\n    }\n\n    /**\n     * @dev Sets the royalty information that all ids in this contract will default to.\n     *\n     * Requirements:\n     *\n     * - `receiver` cannot be the zero address.\n     * - `feeNumerator` cannot be greater than the fee denominator.\n     */\n    function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {\n        uint256 denominator = _feeDenominator();\n        if (feeNumerator > denominator) {\n            // Royalty fee will exceed the sale price\n            revert ERC2981InvalidDefaultRoyalty(feeNumerator, denominator);\n        }\n        if (receiver == address(0)) {\n            revert ERC2981InvalidDefaultRoyaltyReceiver(address(0));\n        }\n\n        _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);\n    }\n\n    /**\n     * @dev Removes default royalty information.\n     */\n    function _deleteDefaultRoyalty() internal virtual {\n        delete _defaultRoyaltyInfo;\n    }\n\n    /**\n     * @dev Sets the royalty information for a specific token id, overriding the global default.\n     *\n     * Requirements:\n     *\n     * - `receiver` cannot be the zero address.\n     * - `feeNumerator` cannot be greater than the fee denominator.\n     */\n    function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual {\n        uint256 denominator = _feeDenominator();\n        if (feeNumerator > denominator) {\n            // Royalty fee will exceed the sale price\n            revert ERC2981InvalidTokenRoyalty(tokenId, feeNumerator, denominator);\n        }\n        if (receiver == address(0)) {\n            revert ERC2981InvalidTokenRoyaltyReceiver(tokenId, address(0));\n        }\n\n        _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);\n    }\n\n    /**\n     * @dev Resets royalty information for the token id back to the global default.\n     */\n    function _resetTokenRoyalty(uint256 tokenId) internal virtual {\n        delete _tokenRoyaltyInfo[tokenId];\n    }\n}\n"},"@openzeppelin/contracts/utils/Base64.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Base64.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n */\nlibrary Base64 {\n    /**\n     * @dev Base64 Encoding/Decoding Table\n     * See sections 4 and 5 of https://datatracker.ietf.org/doc/html/rfc4648\n     */\n    string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n    string internal constant _TABLE_URL = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n    /**\n     * @dev Converts a `bytes` to its Bytes64 `string` representation.\n     */\n    function encode(bytes memory data) internal pure returns (string memory) {\n        return _encode(data, _TABLE, true);\n    }\n\n    /**\n     * @dev Converts a `bytes` to its Bytes64Url `string` representation.\n     * Output is not padded with `=` as specified in https://www.rfc-editor.org/rfc/rfc4648[rfc4648].\n     */\n    function encodeURL(bytes memory data) internal pure returns (string memory) {\n        return _encode(data, _TABLE_URL, false);\n    }\n\n    /**\n     * @dev Internal table-agnostic conversion\n     */\n    function _encode(bytes memory data, string memory table, bool withPadding) private pure returns (string memory) {\n        /**\n         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n         */\n        if (data.length == 0) return \"\";\n\n        // If padding is enabled, the final length should be `bytes` data length divided by 3 rounded up and then\n        // multiplied by 4 so that it leaves room for padding the last chunk\n        // - `data.length + 2`  -> Prepare for division rounding up\n        // - `/ 3`              -> Number of 3-bytes chunks (rounded up)\n        // - `4 *`              -> 4 characters for each chunk\n        // This is equivalent to: 4 * Math.ceil(data.length / 3)\n        //\n        // If padding is disabled, the final length should be `bytes` data length multiplied by 4/3 rounded up as\n        // opposed to when padding is required to fill the last chunk.\n        // - `4 * data.length`  -> 4 characters for each chunk\n        // - ` + 2`             -> Prepare for division rounding up\n        // - `/ 3`              -> Number of 3-bytes chunks (rounded up)\n        // This is equivalent to: Math.ceil((4 * data.length) / 3)\n        uint256 resultLength = withPadding ? 4 * ((data.length + 2) / 3) : (4 * data.length + 2) / 3;\n\n        string memory result = new string(resultLength);\n\n        assembly (\"memory-safe\") {\n            // Prepare the lookup table (skip the first \"length\" byte)\n            let tablePtr := add(table, 1)\n\n            // Prepare result pointer, jump over length\n            let resultPtr := add(result, 0x20)\n            let dataPtr := data\n            let endPtr := add(data, mload(data))\n\n            // In some cases, the last iteration will read bytes after the end of the data. We cache the value, and\n            // set it to zero to make sure no dirty bytes are read in that section.\n            let afterPtr := add(endPtr, 0x20)\n            let afterCache := mload(afterPtr)\n            mstore(afterPtr, 0x00)\n\n            // Run over the input, 3 bytes at a time\n            for {} lt(dataPtr, endPtr) {} {\n                // Advance 3 bytes\n                dataPtr := add(dataPtr, 3)\n                let input := mload(dataPtr)\n\n                // To write each character, shift the 3 byte (24 bits) chunk\n                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n                // and apply logical AND with 0x3F to bitmask the least significant 6 bits.\n                // Use this as an index into the lookup table, mload an entire word\n                // so the desired character is in the least significant byte, and\n                // mstore8 this least significant byte into the result and continue.\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n            }\n\n            // Reset the value that was cached\n            mstore(afterPtr, afterCache)\n\n            if withPadding {\n                // When data `bytes` is not exactly 3 bytes long\n                // it is padded with `=` characters at the end\n                switch mod(mload(data), 3)\n                case 1 {\n                    mstore8(sub(resultPtr, 1), 0x3d)\n                    mstore8(sub(resultPtr, 2), 0x3d)\n                }\n                case 2 {\n                    mstore8(sub(resultPtr, 1), 0x3d)\n                }\n            }\n        }\n\n        return result;\n    }\n}\n"},"@openzeppelin/contracts/utils/Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"@openzeppelin/contracts/utils/Panic.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    uint256 private _status;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if (_status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        _status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == ENTERED;\n    }\n}\n"},"@openzeppelin/contracts/utils/ShortStrings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/ShortStrings.sol)\n\npragma solidity ^0.8.20;\n\nimport {StorageSlot} from \"./StorageSlot.sol\";\n\n// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |\n// | length  | 0x                                                              BB |\ntype ShortString is bytes32;\n\n/**\n * @dev This library provides functions to convert short memory strings\n * into a `ShortString` type that can be used as an immutable variable.\n *\n * Strings of arbitrary length can be optimized using this library if\n * they are short enough (up to 31 bytes) by packing them with their\n * length (1 byte) in a single EVM word (32 bytes). Additionally, a\n * fallback mechanism can be used for every other case.\n *\n * Usage example:\n *\n * ```solidity\n * contract Named {\n *     using ShortStrings for *;\n *\n *     ShortString private immutable _name;\n *     string private _nameFallback;\n *\n *     constructor(string memory contractName) {\n *         _name = contractName.toShortStringWithFallback(_nameFallback);\n *     }\n *\n *     function name() external view returns (string memory) {\n *         return _name.toStringWithFallback(_nameFallback);\n *     }\n * }\n * ```\n */\nlibrary ShortStrings {\n    // Used as an identifier for strings longer than 31 bytes.\n    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;\n\n    error StringTooLong(string str);\n    error InvalidShortString();\n\n    /**\n     * @dev Encode a string of at most 31 chars into a `ShortString`.\n     *\n     * This will trigger a `StringTooLong` error is the input string is too long.\n     */\n    function toShortString(string memory str) internal pure returns (ShortString) {\n        bytes memory bstr = bytes(str);\n        if (bstr.length > 31) {\n            revert StringTooLong(str);\n        }\n        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));\n    }\n\n    /**\n     * @dev Decode a `ShortString` back to a \"normal\" string.\n     */\n    function toString(ShortString sstr) internal pure returns (string memory) {\n        uint256 len = byteLength(sstr);\n        // using `new string(len)` would work locally but is not memory safe.\n        string memory str = new string(32);\n        assembly (\"memory-safe\") {\n            mstore(str, len)\n            mstore(add(str, 0x20), sstr)\n        }\n        return str;\n    }\n\n    /**\n     * @dev Return the length of a `ShortString`.\n     */\n    function byteLength(ShortString sstr) internal pure returns (uint256) {\n        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;\n        if (result > 31) {\n            revert InvalidShortString();\n        }\n        return result;\n    }\n\n    /**\n     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.\n     */\n    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {\n        if (bytes(value).length < 32) {\n            return toShortString(value);\n        } else {\n            StorageSlot.getStringSlot(store).value = value;\n            return ShortString.wrap(FALLBACK_SENTINEL);\n        }\n    }\n\n    /**\n     * @dev Decode a string that was encoded to `ShortString` or written to storage using {toShortStringWithFallback}.\n     */\n    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {\n        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {\n            return toString(value);\n        } else {\n            return store;\n        }\n    }\n\n    /**\n     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using\n     * {toShortStringWithFallback}.\n     *\n     * WARNING: This will return the \"byte length\" of the string. This may not reflect the actual length in terms of\n     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.\n     */\n    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {\n        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {\n            return byteLength(value);\n        } else {\n            return bytes(store).length;\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/StorageSlot.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SafeCast} from \"./math/SafeCast.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    using SafeCast for *;\n\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n    uint256 private constant SPECIAL_CHARS_LOOKUP =\n        (1 << 0x08) | // backspace\n            (1 << 0x09) | // tab\n            (1 << 0x0a) | // newline\n            (1 << 0x0c) | // form feed\n            (1 << 0x0d) | // carriage return\n            (1 << 0x22) | // double quote\n            (1 << 0x5c); // backslash\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev The string being parsed contains characters that are not in scope of the given base.\n     */\n    error StringsInvalidChar();\n\n    /**\n     * @dev The string being parsed is not a properly formatted address.\n     */\n    error StringsInvalidAddressFormat();\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(add(buffer, 0x20), length)\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input) internal pure returns (uint256) {\n        return parseUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        uint256 result = 0;\n        for (uint256 i = begin; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 9) return (false, 0);\n            result *= 10;\n            result += chr;\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `int256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input) internal pure returns (int256) {\n        return parseInt(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {\n        (bool success, int256 value) = tryParseInt(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if\n     * the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {\n        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    uint256 private constant ABS_MIN_INT256 = 2 ** 255;\n\n    /**\n     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character or if the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, int256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseIntUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseIntUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, int256 value) {\n        bytes memory buffer = bytes(input);\n\n        // Check presence of a negative sign.\n        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        bool positiveSign = sign == bytes1(\"+\");\n        bool negativeSign = sign == bytes1(\"-\");\n        uint256 offset = (positiveSign || negativeSign).toUint();\n\n        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);\n\n        if (absSuccess && absValue < ABS_MIN_INT256) {\n            return (true, negativeSign ? -int256(absValue) : int256(absValue));\n        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {\n            return (true, type(int256).min);\n        } else return (false, 0);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input) internal pure returns (uint256) {\n        return parseHexUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseHexUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an\n     * invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseHexUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseHexUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        // skip 0x prefix if present\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 offset = hasPrefix.toUint() * 2;\n\n        uint256 result = 0;\n        for (uint256 i = begin + offset; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 15) return (false, 0);\n            result *= 16;\n            unchecked {\n                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).\n                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.\n                result += chr;\n            }\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as an `address`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input) internal pure returns (address) {\n        return parseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {\n        (bool success, address value) = tryParseAddress(input, begin, end);\n        if (!success) revert StringsInvalidAddressFormat();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly\n     * formatted address. See {parseAddress-string} requirements.\n     */\n    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {\n        return tryParseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly\n     * formatted address. See {parseAddress-string-uint256-uint256} requirements.\n     */\n    function tryParseAddress(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, address value) {\n        if (end > bytes(input).length || begin > end) return (false, address(0));\n\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;\n\n        // check that input is the correct length\n        if (end - begin == expectedLength) {\n            // length guarantees that this does not overflow, and value is at most type(uint160).max\n            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);\n            return (s, address(uint160(v)));\n        } else {\n            return (false, address(0));\n        }\n    }\n\n    function _tryParseChr(bytes1 chr) private pure returns (uint8) {\n        uint8 value = uint8(chr);\n\n        // Try to parse `chr`:\n        // - Case 1: [0-9]\n        // - Case 2: [a-f]\n        // - Case 3: [A-F]\n        // - otherwise not supported\n        unchecked {\n            if (value > 47 && value < 58) value -= 48;\n            else if (value > 96 && value < 103) value -= 87;\n            else if (value > 64 && value < 71) value -= 55;\n            else return type(uint8).max;\n        }\n\n        return value;\n    }\n\n    /**\n     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.\n     *\n     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.\n     *\n     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of\n     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode\n     * characters that are not in this range, but other tooling may provide different results.\n     */\n    function escapeJSON(string memory input) internal pure returns (string memory) {\n        bytes memory buffer = bytes(input);\n        bytes memory output = new bytes(2 * buffer.length); // worst case scenario\n        uint256 outputLength = 0;\n\n        for (uint256 i; i < buffer.length; ++i) {\n            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));\n            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {\n                output[outputLength++] = \"\\\\\";\n                if (char == 0x08) output[outputLength++] = \"b\";\n                else if (char == 0x09) output[outputLength++] = \"t\";\n                else if (char == 0x0a) output[outputLength++] = \"n\";\n                else if (char == 0x0c) output[outputLength++] = \"f\";\n                else if (char == 0x0d) output[outputLength++] = \"r\";\n                else if (char == 0x5c) output[outputLength++] = \"\\\\\";\n                else if (char == 0x22) {\n                    // solhint-disable-next-line quotes\n                    output[outputLength++] = '\"';\n                }\n            } else {\n                output[outputLength++] = char;\n            }\n        }\n        // write the actual length and deallocate unused memory\n        assembly (\"memory-safe\") {\n            mstore(output, outputLength)\n            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))\n        }\n\n        return string(output);\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/cryptography/ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS\n    }\n\n    /**\n     * @dev The signature derives the `address(0)`.\n     */\n    error ECDSAInvalidSignature();\n\n    /**\n     * @dev The signature has an invalid length.\n     */\n    error ECDSAInvalidSignatureLength(uint256 length);\n\n    /**\n     * @dev The signature has an S value that is in the upper half order.\n     */\n    error ECDSAInvalidSignatureS(bytes32 s);\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not\n     * return address(0) without also returning an error description. Errors are documented using an enum (error type)\n     * and a bytes32 providing additional information about the error.\n     *\n     * If no error is returned, then the address can be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes memory signature\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            assembly (\"memory-safe\") {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        unchecked {\n            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n            // We do not check for an overflow here since the shift operation results in 0 or 1.\n            uint8 v = uint8((uint256(vs) >> 255) + 27);\n            return tryRecover(hash, v, r, s);\n        }\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS, s);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature, bytes32(0));\n        }\n\n        return (signer, RecoverError.NoError, bytes32(0));\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.\n     */\n    function _throwError(RecoverError error, bytes32 errorArg) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert ECDSAInvalidSignature();\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert ECDSAInvalidSignatureLength(uint256(errorArg));\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert ECDSAInvalidSignatureS(errorArg);\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/cryptography/EIP712.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.20;\n\nimport {MessageHashUtils} from \"./MessageHashUtils.sol\";\nimport {ShortStrings, ShortString} from \"../ShortStrings.sol\";\nimport {IERC5267} from \"../../interfaces/IERC5267.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose\n * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract\n * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to\n * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain\n * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the\n * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.\n *\n * @custom:oz-upgrades-unsafe-allow state-variable-immutable\n */\nabstract contract EIP712 is IERC5267 {\n    using ShortStrings for *;\n\n    bytes32 private constant TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to\n    // invalidate the cached domain separator if the chain id changes.\n    bytes32 private immutable _cachedDomainSeparator;\n    uint256 private immutable _cachedChainId;\n    address private immutable _cachedThis;\n\n    bytes32 private immutable _hashedName;\n    bytes32 private immutable _hashedVersion;\n\n    ShortString private immutable _name;\n    ShortString private immutable _version;\n    // slither-disable-next-line constable-states\n    string private _nameFallback;\n    // slither-disable-next-line constable-states\n    string private _versionFallback;\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    constructor(string memory name, string memory version) {\n        _name = name.toShortStringWithFallback(_nameFallback);\n        _version = version.toShortStringWithFallback(_versionFallback);\n        _hashedName = keccak256(bytes(name));\n        _hashedVersion = keccak256(bytes(version));\n\n        _cachedChainId = block.chainid;\n        _cachedDomainSeparator = _buildDomainSeparator();\n        _cachedThis = address(this);\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {\n            return _cachedDomainSeparator;\n        } else {\n            return _buildDomainSeparator();\n        }\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /// @inheritdoc IERC5267\n    function eip712Domain()\n        public\n        view\n        virtual\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        return (\n            hex\"0f\", // 01111\n            _EIP712Name(),\n            _EIP712Version(),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n\n    /**\n     * @dev The name parameter for the EIP712 domain.\n     *\n     * NOTE: By default this function reads _name which is an immutable value.\n     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function _EIP712Name() internal view returns (string memory) {\n        return _name.toStringWithFallback(_nameFallback);\n    }\n\n    /**\n     * @dev The version parameter for the EIP712 domain.\n     *\n     * NOTE: By default this function reads _version which is an immutable value.\n     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function _EIP712Version() internal view returns (string memory) {\n        return _version.toStringWithFallback(_versionFallback);\n    }\n}\n"},"@openzeppelin/contracts/utils/cryptography/Hashes.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library of standard hash functions.\n *\n * _Available since v5.1._\n */\nlibrary Hashes {\n    /**\n     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.\n     *\n     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].\n     */\n    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {\n        return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);\n    }\n\n    /**\n     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.\n     */\n    function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, a)\n            mstore(0x20, b)\n            value := keccak256(0x00, 0x40)\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)\n// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.\n\npragma solidity ^0.8.20;\n\nimport {Hashes} from \"./Hashes.sol\";\n\n/**\n * @dev These functions deal with verification of Merkle Tree proofs.\n *\n * The tree and the proofs can be generated using our\n * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].\n * You will find a quickstart guide in the readme.\n *\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\n * hashing, or use a hash function other than keccak256 for hashing leaves.\n * This is because the concatenation of a sorted pair of internal nodes in\n * the Merkle tree could be reinterpreted as a leaf value.\n * OpenZeppelin's JavaScript library generates Merkle trees that are safe\n * against this attack out of the box.\n *\n * IMPORTANT: Consider memory side-effects when using custom hashing functions\n * that access memory in an unsafe way.\n *\n * NOTE: This library supports proof verification for merkle trees built using\n * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving\n * leaf inclusion in trees built using non-commutative hashing functions requires\n * additional logic that is not supported by this library.\n */\nlibrary MerkleProof {\n    /**\n     *@dev The multiproof provided is not valid.\n     */\n    error MerkleProofInvalidMultiproof();\n\n    /**\n     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n     * defined by `root`. For this, a `proof` must be provided, containing\n     * sibling hashes on the branch from the leaf to the root of the tree. Each\n     * pair of leaves and each pair of pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in memory with the default hashing function.\n     */\n    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {\n        return processProof(proof, leaf) == root;\n    }\n\n    /**\n     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n     * hash matches the root of the tree. When processing the proof, the pairs\n     * of leaves & pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in memory with the default hashing function.\n     */\n    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i < proof.length; i++) {\n            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);\n        }\n        return computedHash;\n    }\n\n    /**\n     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n     * defined by `root`. For this, a `proof` must be provided, containing\n     * sibling hashes on the branch from the leaf to the root of the tree. Each\n     * pair of leaves and each pair of pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in memory with a custom hashing function.\n     */\n    function verify(\n        bytes32[] memory proof,\n        bytes32 root,\n        bytes32 leaf,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bool) {\n        return processProof(proof, leaf, hasher) == root;\n    }\n\n    /**\n     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n     * hash matches the root of the tree. When processing the proof, the pairs\n     * of leaves & pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in memory with a custom hashing function.\n     */\n    function processProof(\n        bytes32[] memory proof,\n        bytes32 leaf,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i < proof.length; i++) {\n            computedHash = hasher(computedHash, proof[i]);\n        }\n        return computedHash;\n    }\n\n    /**\n     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n     * defined by `root`. For this, a `proof` must be provided, containing\n     * sibling hashes on the branch from the leaf to the root of the tree. Each\n     * pair of leaves and each pair of pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in calldata with the default hashing function.\n     */\n    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {\n        return processProofCalldata(proof, leaf) == root;\n    }\n\n    /**\n     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n     * hash matches the root of the tree. When processing the proof, the pairs\n     * of leaves & pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in calldata with the default hashing function.\n     */\n    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i < proof.length; i++) {\n            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);\n        }\n        return computedHash;\n    }\n\n    /**\n     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n     * defined by `root`. For this, a `proof` must be provided, containing\n     * sibling hashes on the branch from the leaf to the root of the tree. Each\n     * pair of leaves and each pair of pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in calldata with a custom hashing function.\n     */\n    function verifyCalldata(\n        bytes32[] calldata proof,\n        bytes32 root,\n        bytes32 leaf,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bool) {\n        return processProofCalldata(proof, leaf, hasher) == root;\n    }\n\n    /**\n     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n     * hash matches the root of the tree. When processing the proof, the pairs\n     * of leaves & pre-images are assumed to be sorted.\n     *\n     * This version handles proofs in calldata with a custom hashing function.\n     */\n    function processProofCalldata(\n        bytes32[] calldata proof,\n        bytes32 leaf,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i < proof.length; i++) {\n            computedHash = hasher(computedHash, proof[i]);\n        }\n        return computedHash;\n    }\n\n    /**\n     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by\n     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n     *\n     * This version handles multiproofs in memory with the default hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     *\n     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.\n     * The `leaves` must be validated independently. See {processMultiProof}.\n     */\n    function multiProofVerify(\n        bytes32[] memory proof,\n        bool[] memory proofFlags,\n        bytes32 root,\n        bytes32[] memory leaves\n    ) internal pure returns (bool) {\n        return processMultiProof(proof, proofFlags, leaves) == root;\n    }\n\n    /**\n     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n     * respectively.\n     *\n     * This version handles multiproofs in memory with the default hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n     *\n     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,\n     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not\n     * validating the leaves elsewhere.\n     */\n    function processMultiProof(\n        bytes32[] memory proof,\n        bool[] memory proofFlags,\n        bytes32[] memory leaves\n    ) internal pure returns (bytes32 merkleRoot) {\n        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n        // the Merkle tree.\n        uint256 leavesLen = leaves.length;\n        uint256 proofFlagsLen = proofFlags.length;\n\n        // Check proof validity.\n        if (leavesLen + proof.length != proofFlagsLen + 1) {\n            revert MerkleProofInvalidMultiproof();\n        }\n\n        // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n        bytes32[] memory hashes = new bytes32[](proofFlagsLen);\n        uint256 leafPos = 0;\n        uint256 hashPos = 0;\n        uint256 proofPos = 0;\n        // At each step, we compute the next hash using two values:\n        // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n        //   get the next hash.\n        // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n        //   `proof` array.\n        for (uint256 i = 0; i < proofFlagsLen; i++) {\n            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n            bytes32 b = proofFlags[i]\n                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n                : proof[proofPos++];\n            hashes[i] = Hashes.commutativeKeccak256(a, b);\n        }\n\n        if (proofFlagsLen > 0) {\n            if (proofPos != proof.length) {\n                revert MerkleProofInvalidMultiproof();\n            }\n            unchecked {\n                return hashes[proofFlagsLen - 1];\n            }\n        } else if (leavesLen > 0) {\n            return leaves[0];\n        } else {\n            return proof[0];\n        }\n    }\n\n    /**\n     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by\n     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n     *\n     * This version handles multiproofs in memory with a custom hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     *\n     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.\n     * The `leaves` must be validated independently. See {processMultiProof}.\n     */\n    function multiProofVerify(\n        bytes32[] memory proof,\n        bool[] memory proofFlags,\n        bytes32 root,\n        bytes32[] memory leaves,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bool) {\n        return processMultiProof(proof, proofFlags, leaves, hasher) == root;\n    }\n\n    /**\n     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n     * respectively.\n     *\n     * This version handles multiproofs in memory with a custom hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n     *\n     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,\n     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not\n     * validating the leaves elsewhere.\n     */\n    function processMultiProof(\n        bytes32[] memory proof,\n        bool[] memory proofFlags,\n        bytes32[] memory leaves,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bytes32 merkleRoot) {\n        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n        // the Merkle tree.\n        uint256 leavesLen = leaves.length;\n        uint256 proofFlagsLen = proofFlags.length;\n\n        // Check proof validity.\n        if (leavesLen + proof.length != proofFlagsLen + 1) {\n            revert MerkleProofInvalidMultiproof();\n        }\n\n        // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n        bytes32[] memory hashes = new bytes32[](proofFlagsLen);\n        uint256 leafPos = 0;\n        uint256 hashPos = 0;\n        uint256 proofPos = 0;\n        // At each step, we compute the next hash using two values:\n        // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n        //   get the next hash.\n        // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n        //   `proof` array.\n        for (uint256 i = 0; i < proofFlagsLen; i++) {\n            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n            bytes32 b = proofFlags[i]\n                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n                : proof[proofPos++];\n            hashes[i] = hasher(a, b);\n        }\n\n        if (proofFlagsLen > 0) {\n            if (proofPos != proof.length) {\n                revert MerkleProofInvalidMultiproof();\n            }\n            unchecked {\n                return hashes[proofFlagsLen - 1];\n            }\n        } else if (leavesLen > 0) {\n            return leaves[0];\n        } else {\n            return proof[0];\n        }\n    }\n\n    /**\n     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by\n     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n     *\n     * This version handles multiproofs in calldata with the default hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     *\n     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.\n     * The `leaves` must be validated independently. See {processMultiProofCalldata}.\n     */\n    function multiProofVerifyCalldata(\n        bytes32[] calldata proof,\n        bool[] calldata proofFlags,\n        bytes32 root,\n        bytes32[] memory leaves\n    ) internal pure returns (bool) {\n        return processMultiProofCalldata(proof, proofFlags, leaves) == root;\n    }\n\n    /**\n     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n     * respectively.\n     *\n     * This version handles multiproofs in calldata with the default hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n     *\n     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,\n     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not\n     * validating the leaves elsewhere.\n     */\n    function processMultiProofCalldata(\n        bytes32[] calldata proof,\n        bool[] calldata proofFlags,\n        bytes32[] memory leaves\n    ) internal pure returns (bytes32 merkleRoot) {\n        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n        // the Merkle tree.\n        uint256 leavesLen = leaves.length;\n        uint256 proofFlagsLen = proofFlags.length;\n\n        // Check proof validity.\n        if (leavesLen + proof.length != proofFlagsLen + 1) {\n            revert MerkleProofInvalidMultiproof();\n        }\n\n        // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n        bytes32[] memory hashes = new bytes32[](proofFlagsLen);\n        uint256 leafPos = 0;\n        uint256 hashPos = 0;\n        uint256 proofPos = 0;\n        // At each step, we compute the next hash using two values:\n        // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n        //   get the next hash.\n        // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n        //   `proof` array.\n        for (uint256 i = 0; i < proofFlagsLen; i++) {\n            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n            bytes32 b = proofFlags[i]\n                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n                : proof[proofPos++];\n            hashes[i] = Hashes.commutativeKeccak256(a, b);\n        }\n\n        if (proofFlagsLen > 0) {\n            if (proofPos != proof.length) {\n                revert MerkleProofInvalidMultiproof();\n            }\n            unchecked {\n                return hashes[proofFlagsLen - 1];\n            }\n        } else if (leavesLen > 0) {\n            return leaves[0];\n        } else {\n            return proof[0];\n        }\n    }\n\n    /**\n     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by\n     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n     *\n     * This version handles multiproofs in calldata with a custom hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     *\n     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.\n     * The `leaves` must be validated independently. See {processMultiProofCalldata}.\n     */\n    function multiProofVerifyCalldata(\n        bytes32[] calldata proof,\n        bool[] calldata proofFlags,\n        bytes32 root,\n        bytes32[] memory leaves,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bool) {\n        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;\n    }\n\n    /**\n     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n     * respectively.\n     *\n     * This version handles multiproofs in calldata with a custom hashing function.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n     *\n     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,\n     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not\n     * validating the leaves elsewhere.\n     */\n    function processMultiProofCalldata(\n        bytes32[] calldata proof,\n        bool[] calldata proofFlags,\n        bytes32[] memory leaves,\n        function(bytes32, bytes32) view returns (bytes32) hasher\n    ) internal view returns (bytes32 merkleRoot) {\n        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n        // the Merkle tree.\n        uint256 leavesLen = leaves.length;\n        uint256 proofFlagsLen = proofFlags.length;\n\n        // Check proof validity.\n        if (leavesLen + proof.length != proofFlagsLen + 1) {\n            revert MerkleProofInvalidMultiproof();\n        }\n\n        // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n        bytes32[] memory hashes = new bytes32[](proofFlagsLen);\n        uint256 leafPos = 0;\n        uint256 hashPos = 0;\n        uint256 proofPos = 0;\n        // At each step, we compute the next hash using two values:\n        // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n        //   get the next hash.\n        // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n        //   `proof` array.\n        for (uint256 i = 0; i < proofFlagsLen; i++) {\n            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n            bytes32 b = proofFlags[i]\n                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n                : proof[proofPos++];\n            hashes[i] = hasher(a, b);\n        }\n\n        if (proofFlagsLen > 0) {\n            if (proofPos != proof.length) {\n                revert MerkleProofInvalidMultiproof();\n            }\n            unchecked {\n                return hashes[proofFlagsLen - 1];\n            }\n        } else if (leavesLen > 0) {\n            return leaves[0];\n        } else {\n            return proof[0];\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.20;\n\nimport {Strings} from \"../Strings.sol\";\n\n/**\n * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.\n *\n * The library provides methods for generating a hash of a message that conforms to the\n * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing a bytes32 `messageHash` with\n     * `\"\\x19Ethereum Signed Message:\\n32\"` and hashing the result. It corresponds with the\n     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with\n     * keccak256, although any bytes32 value can be safely used because the final digest will\n     * be re-hashed.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\") // 32 is the bytes-length of messageHash\n            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix\n            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing an arbitrary `message` with\n     * `\"\\x19Ethereum Signed Message:\\n\" + len(message)` and hashing the result. It corresponds with the\n     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {\n        return\n            keccak256(bytes.concat(\"\\x19Ethereum Signed Message:\\n\", bytes(Strings.toString(message.length)), message));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x00` (data with intended validator).\n     *\n     * The digest is calculated by prefixing an arbitrary `data` with `\"\\x19\\x00\"` and the intended\n     * `validator` address. Then hashing the result.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(hex\"19_00\", validator, data));\n    }\n\n    /**\n     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.\n     */\n    function toDataWithIntendedValidatorHash(\n        address validator,\n        bytes32 messageHash\n    ) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, hex\"19_00\")\n            mstore(0x02, shl(96, validator))\n            mstore(0x16, messageHash)\n            digest := keccak256(0x00, 0x36)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).\n     *\n     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with\n     * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            mstore(ptr, hex\"19_01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            digest := keccak256(ptr, 0x42)\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/introspection/ERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165 is IERC165 {\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"@openzeppelin/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"@openzeppelin/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2²⁵⁶ + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},"@openzeppelin/contracts/utils/math/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"},"@uniswap/v4-core/src/interfaces/IExtsload.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n    /// @notice Called by external contracts to access granular pool state\n    /// @param slot Key of slot to sload\n    /// @return value The value of the slot as bytes32\n    function extsload(bytes32 slot) external view returns (bytes32 value);\n\n    /// @notice Called by external contracts to access granular pool state\n    /// @param startSlot Key of slot to start sloading from\n    /// @param nSlots Number of slots to load into return value\n    /// @return values List of loaded values.\n    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n    /// @notice Called by external contracts to access sparse pool state\n    /// @param slots List of slots to SLOAD from.\n    /// @return values List of loaded values.\n    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n"},"@uniswap/v4-core/src/interfaces/IExttload.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n    /// @notice Called by external contracts to access transient storage of the contract\n    /// @param slot Key of slot to tload\n    /// @return value The value of the slot as bytes32\n    function exttload(bytes32 slot) external view returns (bytes32 value);\n\n    /// @notice Called by external contracts to access sparse transient pool state\n    /// @param slots List of slots to tload\n    /// @return values List of loaded values\n    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n"},"@uniswap/v4-core/src/interfaces/IHooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n    /// @notice The hook called before the state of a pool is initialized\n    /// @param sender The initial msg.sender for the initialize call\n    /// @param key The key for the pool being initialized\n    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n    /// @return bytes4 The function selector for the hook\n    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n    /// @notice The hook called after the state of a pool is initialized\n    /// @param sender The initial msg.sender for the initialize call\n    /// @param key The key for the pool being initialized\n    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n    /// @param tick The current tick after the state of a pool is initialized\n    /// @return bytes4 The function selector for the hook\n    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n        external\n        returns (bytes4);\n\n    /// @notice The hook called before liquidity is added\n    /// @param sender The initial msg.sender for the add liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for adding liquidity\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after liquidity is added\n    /// @param sender The initial msg.sender for the add liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for adding liquidity\n    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n    /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external returns (bytes4, BalanceDelta);\n\n    /// @notice The hook called before liquidity is removed\n    /// @param sender The initial msg.sender for the remove liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for removing liquidity\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after liquidity is removed\n    /// @param sender The initial msg.sender for the remove liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for removing liquidity\n    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n    /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external returns (bytes4, BalanceDelta);\n\n    /// @notice The hook called before a swap\n    /// @param sender The initial msg.sender for the swap call\n    /// @param key The key for the pool\n    /// @param params The parameters for the swap\n    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)\n    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n        external\n        returns (bytes4, BeforeSwapDelta, uint24);\n\n    /// @notice The hook called after a swap\n    /// @param sender The initial msg.sender for the swap call\n    /// @param key The key for the pool\n    /// @param params The parameters for the swap\n    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterSwap(\n        address sender,\n        PoolKey calldata key,\n        SwapParams calldata params,\n        BalanceDelta delta,\n        bytes calldata hookData\n    ) external returns (bytes4, int128);\n\n    /// @notice The hook called before donate\n    /// @param sender The initial msg.sender for the donate call\n    /// @param key The key for the pool\n    /// @param amount0 The amount of token0 being donated\n    /// @param amount1 The amount of token1 being donated\n    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after donate\n    /// @param sender The initial msg.sender for the donate call\n    /// @param key The key for the pool\n    /// @param amount0 The amount of token0 being donated\n    /// @param amount1 The amount of token1 being donated\n    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function afterDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external returns (bytes4);\n}\n"},"@uniswap/v4-core/src/interfaces/IPoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n    /// @notice Thrown when a currency is not netted out after the contract is unlocked\n    error CurrencyNotSettled();\n\n    /// @notice Thrown when trying to interact with a non-initialized pool\n    error PoolNotInitialized();\n\n    /// @notice Thrown when unlock is called, but the contract is already unlocked\n    error AlreadyUnlocked();\n\n    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n    error ManagerLocked();\n\n    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n    error TickSpacingTooLarge(int24 tickSpacing);\n\n    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n    error TickSpacingTooSmall(int24 tickSpacing);\n\n    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n    /// or on a pool that does not have a dynamic swap fee.\n    error UnauthorizedDynamicLPFeeUpdate();\n\n    /// @notice Thrown when trying to swap amount of 0\n    error SwapAmountCannotBeZero();\n\n    ///@notice Thrown when native currency is passed to a non native settlement\n    error NonzeroNativeValue();\n\n    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n    error MustClearExactPositiveDelta();\n\n    /// @notice Emitted when a new pool is initialized\n    /// @param id The abi encoded hash of the pool key struct for the new pool\n    /// @param currency0 The first currency of the pool by address sort order\n    /// @param currency1 The second currency of the pool by address sort order\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks\n    /// @param hooks The hooks contract address for the pool, or address(0) if none\n    /// @param sqrtPriceX96 The price of the pool on initialization\n    /// @param tick The initial tick of the pool corresponding to the initialized price\n    event Initialize(\n        PoolId indexed id,\n        Currency indexed currency0,\n        Currency indexed currency1,\n        uint24 fee,\n        int24 tickSpacing,\n        IHooks hooks,\n        uint160 sqrtPriceX96,\n        int24 tick\n    );\n\n    /// @notice Emitted when a liquidity position is modified\n    /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n    /// @param sender The address that modified the pool\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param liquidityDelta The amount of liquidity that was added or removed\n    /// @param salt The extra data to make positions unique\n    event ModifyLiquidity(\n        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n    );\n\n    /// @notice Emitted for swaps between currency0 and currency1\n    /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param amount0 The delta of the currency0 balance of the pool\n    /// @param amount1 The delta of the currency1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of the price of the pool after the swap\n    /// @param fee The swap fee in hundredths of a bip\n    event Swap(\n        PoolId indexed id,\n        address indexed sender,\n        int128 amount0,\n        int128 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick,\n        uint24 fee\n    );\n\n    /// @notice Emitted for donations\n    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n    /// @param sender The address that initiated the donate call\n    /// @param amount0 The amount donated in currency0\n    /// @param amount1 The amount donated in currency1\n    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n    function unlock(bytes calldata data) external returns (bytes memory);\n\n    /// @notice Initialize the state for a given pool ID\n    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n    /// @param key The pool key for the pool to initialize\n    /// @param sqrtPriceX96 The initial square root price\n    /// @return tick The initial tick of the pool\n    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n    /// @notice Modify the liquidity for the given pool\n    /// @dev Poke by calling with a zero liquidityDelta\n    /// @param key The pool to modify liquidity in\n    /// @param params The parameters for modifying the liquidity\n    /// @param hookData The data to pass through to the add/removeLiquidity hooks\n    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n        external\n        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n    /// @notice Swap against the given pool\n    /// @param key The pool to swap in\n    /// @param params The parameters for swapping\n    /// @param hookData The data to pass through to the swap hooks\n    /// @return swapDelta The balance delta of the address swapping\n    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n        external\n        returns (BalanceDelta swapDelta);\n\n    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n    /// Donors should keep this in mind when designing donation mechanisms.\n    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to\n    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n    /// Read the comments in `Pool.swap()` for more information about this.\n    /// @param key The key of the pool to donate to\n    /// @param amount0 The amount of currency0 to donate\n    /// @param amount1 The amount of currency1 to donate\n    /// @param hookData The data to pass through to the donate hooks\n    /// @return BalanceDelta The delta of the caller after the donate\n    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        external\n        returns (BalanceDelta);\n\n    /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n    /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n    /// for native tokens because the amount to settle is determined by the sent value.\n    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n    /// native funds, this function can be called with the native currency to then be able to settle the native currency\n    function sync(Currency currency) external;\n\n    /// @notice Called by the user to net out some value owed to the user\n    /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n    /// @dev Can also be used as a mechanism for free flash loans\n    /// @param currency The currency to withdraw from the pool manager\n    /// @param to The address to withdraw to\n    /// @param amount The amount of currency to withdraw\n    function take(Currency currency, address to, uint256 amount) external;\n\n    /// @notice Called by the user to pay what is owed\n    /// @return paid The amount of currency settled\n    function settle() external payable returns (uint256 paid);\n\n    /// @notice Called by the user to pay on behalf of another address\n    /// @param recipient The address to credit for the payment\n    /// @return paid The amount of currency settled\n    function settleFor(address recipient) external payable returns (uint256 paid);\n\n    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n    /// @dev This could be used to clear a balance that is considered dust.\n    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n    function clear(Currency currency, uint256 amount) external;\n\n    /// @notice Called by the user to move value into ERC6909 balance\n    /// @param to The address to mint the tokens to\n    /// @param id The currency address to mint to ERC6909s, as a uint256\n    /// @param amount The amount of currency to mint\n    /// @dev The id is converted to a uint160 to correspond to a currency address\n    /// If the upper 12 bytes are not 0, they will be 0-ed out\n    function mint(address to, uint256 id, uint256 amount) external;\n\n    /// @notice Called by the user to move value from ERC6909 balance\n    /// @param from The address to burn the tokens from\n    /// @param id The currency address to burn from ERC6909s, as a uint256\n    /// @param amount The amount of currency to burn\n    /// @dev The id is converted to a uint160 to correspond to a currency address\n    /// If the upper 12 bytes are not 0, they will be 0-ed out\n    function burn(address from, uint256 id, uint256 amount) external;\n\n    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n    /// @param key The key of the pool to update dynamic LP fees for\n    /// @param newDynamicLPFee The new dynamic pool LP fee\n    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n"},"@uniswap/v4-core/src/interfaces/IProtocolFees.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n    /// @notice Thrown when protocol fee is set too high\n    error ProtocolFeeTooLarge(uint24 fee);\n\n    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n    error InvalidCaller();\n\n    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n    error ProtocolFeeCurrencySynced();\n\n    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n    /// @notice Emitted when the protocol fee is updated for a pool.\n    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n    /// @notice Given a currency address, returns the protocol fees accrued in that currency\n    /// @param currency The currency to check\n    /// @return amount The amount of protocol fees accrued in the currency\n    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n    /// @notice Sets the protocol fee for the given pool\n    /// @param key The key of the pool to set a protocol fee for\n    /// @param newProtocolFee The fee to set\n    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n    /// @notice Sets the protocol fee controller\n    /// @param controller The new protocol fee controller\n    function setProtocolFeeController(address controller) external;\n\n    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n    /// @dev This will revert if the contract is unlocked\n    /// @param recipient The address to receive the protocol fees\n    /// @param currency The currency to withdraw\n    /// @param amount The amount of currency to withdraw\n    /// @return amountCollected The amount of currency successfully withdrawn\n    function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n        external\n        returns (uint256 amountCollected);\n\n    /// @notice Returns the current protocol fee controller address\n    /// @return address The current protocol fee controller address\n    function protocolFeeController() external view returns (address);\n}\n"},"@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n    /// @notice Returns an account's balance in the token\n    /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n    /// @return The number of tokens held by the account\n    function balanceOf(address account) external view returns (uint256);\n\n    /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n    /// @param recipient The account that will receive the amount transferred\n    /// @param amount The number of tokens to send from the sender to the recipient\n    /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Returns the current allowance given to a spender by an owner\n    /// @param owner The account of the token owner\n    /// @param spender The account of the token spender\n    /// @return The current allowance granted by `owner` to `spender`\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n    /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n    /// @param amount The amount of tokens allowed to be used by `spender`\n    /// @return Returns true for a successful approval, false for unsuccessful\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n    /// @param sender The account from which the transfer will be initiated\n    /// @param recipient The recipient of the transfer\n    /// @param amount The amount of the transfer\n    /// @return Returns true for a successful transfer, false for unsuccessful\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n    /// @param from The account from which the tokens were sent, i.e. the balance decreased\n    /// @param to The account to which the tokens were sent, i.e. the balance increased\n    /// @param value The amount of tokens that were transferred\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n    /// @param owner The account that approved spending of its tokens\n    /// @param spender The account for which the spending allowance was modified\n    /// @param value The new allowance from the owner to the spender\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                                 FUNCTIONS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Owner balance of an id.\n    /// @param owner The address of the owner.\n    /// @param id The id of the token.\n    /// @return amount The balance of the token.\n    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n    /// @notice Spender allowance of an id.\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @param id The id of the token.\n    /// @return amount The allowance of the token.\n    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n    /// @notice Checks if a spender is approved by an owner as an operator\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @return approved The approval status.\n    function isOperator(address owner, address spender) external view returns (bool approved);\n\n    /// @notice Transfers an amount of an id from the caller to a receiver.\n    /// @param receiver The address of the receiver.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always, unless the function reverts\n    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Transfers an amount of an id from a sender to a receiver.\n    /// @param sender The address of the sender.\n    /// @param receiver The address of the receiver.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always, unless the function reverts\n    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Approves an amount of an id to a spender.\n    /// @param spender The address of the spender.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always\n    function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Sets or removes an operator for the caller.\n    /// @param operator The address of the operator.\n    /// @param approved The approval status.\n    /// @return bool True, always\n    function setOperator(address operator, bool approved) external returns (bool);\n}\n"},"@uniswap/v4-core/src/libraries/CustomRevert.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n    /// @dev ERC-7751 error for wrapping bubbled up reverts\n    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n    /// @dev Reverts with the selector of a custom error in the scratch space\n    function revertWith(bytes4 selector) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            revert(0, 0x04)\n        }\n    }\n\n    /// @dev Reverts with a custom error with an address argument in the scratch space\n    function revertWith(bytes4 selector, address addr) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with an int24 argument in the scratch space\n    function revertWith(bytes4 selector, int24 value) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, signextend(2, value))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n    function revertWith(bytes4 selector, uint160 value) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two int24 arguments\n    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), signextend(2, value1))\n            mstore(add(fmp, 0x24), signextend(2, value2))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two uint160 arguments\n    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two address arguments\n    function revertWith(bytes4 selector, address value1, address value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n    /// @dev this method can be vulnerable to revert data bombs\n    function bubbleUpAndRevertWith(\n        address revertingContract,\n        bytes4 revertingFunctionSelector,\n        bytes4 additionalContext\n    ) internal pure {\n        bytes4 wrappedErrorSelector = WrappedError.selector;\n        assembly (\"memory-safe\") {\n            // Ensure the size of the revert data is a multiple of 32 bytes\n            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n            let fmp := mload(0x40)\n\n            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n            mstore(fmp, wrappedErrorSelector)\n            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(\n                add(fmp, 0x24),\n                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n            )\n            // offset revert reason\n            mstore(add(fmp, 0x44), 0x80)\n            // offset additional context\n            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n            // size revert reason\n            mstore(add(fmp, 0x84), returndatasize())\n            // revert reason\n            returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n            // size additional context\n            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n            // additional context\n            mstore(\n                add(fmp, add(0xc4, encodedDataSize)),\n                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n            )\n            revert(fmp, add(0xe4, encodedDataSize))\n        }\n    }\n}\n"},"@uniswap/v4-core/src/libraries/Hooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\nimport {LPFeeLibrary} from \"./LPFeeLibrary.sol\";\nimport {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from \"../types/BalanceDelta.sol\";\nimport {BeforeSwapDelta, BeforeSwapDeltaLibrary} from \"../types/BeforeSwapDelta.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {ParseBytes} from \"./ParseBytes.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\nlibrary Hooks {\n    using LPFeeLibrary for uint24;\n    using Hooks for IHooks;\n    using SafeCast for int256;\n    using BeforeSwapDeltaLibrary for BeforeSwapDelta;\n    using ParseBytes for bytes;\n    using CustomRevert for bytes4;\n\n    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);\n\n    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;\n    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;\n\n    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;\n    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;\n\n    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;\n    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;\n\n    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;\n    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;\n\n    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;\n    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;\n\n    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;\n    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;\n    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;\n    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;\n\n    struct Permissions {\n        bool beforeInitialize;\n        bool afterInitialize;\n        bool beforeAddLiquidity;\n        bool afterAddLiquidity;\n        bool beforeRemoveLiquidity;\n        bool afterRemoveLiquidity;\n        bool beforeSwap;\n        bool afterSwap;\n        bool beforeDonate;\n        bool afterDonate;\n        bool beforeSwapReturnDelta;\n        bool afterSwapReturnDelta;\n        bool afterAddLiquidityReturnDelta;\n        bool afterRemoveLiquidityReturnDelta;\n    }\n\n    /// @notice Thrown if the address will not lead to the specified hook calls being called\n    /// @param hooks The address of the hooks contract\n    error HookAddressNotValid(address hooks);\n\n    /// @notice Hook did not return its selector\n    error InvalidHookResponse();\n\n    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails\n    error HookCallFailed();\n\n    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa\n    error HookDeltaExceedsSwapAmount();\n\n    /// @notice Utility function intended to be used in hook constructors to ensure\n    /// the deployed hooks address causes the intended hooks to be called\n    /// @param permissions The hooks that are intended to be called\n    /// @dev permissions param is memory as the function will be called from constructors\n    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {\n        if (\n            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)\n                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)\n                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)\n                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)\n                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)\n                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)\n                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)\n                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)\n                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)\n                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)\n                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)\n                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)\n                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)\n                || permissions.afterRemoveLiquidityReturnDelta\n                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)\n        ) {\n            HookAddressNotValid.selector.revertWith(address(self));\n        }\n    }\n\n    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address\n    /// @param self The hook to verify\n    /// @param fee The fee of the pool the hook is used with\n    /// @return bool True if the hook address is valid\n    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {\n        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag\n        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;\n        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;\n        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))\n        {\n            return false;\n        }\n        if (\n            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)\n                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)\n        ) return false;\n\n        // If there is no hook contract set, then fee cannot be dynamic\n        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee\n        return address(self) == address(0)\n            ? !fee.isDynamicFee()\n            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());\n    }\n\n    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta\n    /// @return result The complete data returned by the hook\n    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {\n        bool success;\n        assembly (\"memory-safe\") {\n            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)\n        }\n        // Revert with FailedHookCall, containing any error message to bubble up\n        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);\n\n        // The call was successful, fetch the returned data\n        assembly (\"memory-safe\") {\n            // allocate result byte array from the free memory pointer\n            result := mload(0x40)\n            // store new free memory pointer at the end of the array padded to 32 bytes\n            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))\n            // store length in memory\n            mstore(result, returndatasize())\n            // copy return data to result\n            returndatacopy(add(result, 0x20), 0, returndatasize())\n        }\n\n        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.\n        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {\n            InvalidHookResponse.selector.revertWith();\n        }\n    }\n\n    /// @notice performs a hook call using the given calldata on the given hook\n    /// @return int256 The delta returned by the hook\n    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {\n        bytes memory result = callHook(self, data);\n\n        // If this hook wasn't meant to return something, default to 0 delta\n        if (!parseReturn) return 0;\n\n        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta\n        if (result.length != 64) InvalidHookResponse.selector.revertWith();\n        return result.parseReturnDelta();\n    }\n\n    /// @notice modifier to prevent calling a hook if they initiated the action\n    modifier noSelfCall(IHooks self) {\n        if (msg.sender != address(self)) {\n            _;\n        }\n    }\n\n    /// @notice calls beforeInitialize hook if permissioned and validates return value\n    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {\n        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));\n        }\n    }\n\n    /// @notice calls afterInitialize hook if permissioned and validates return value\n    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)\n        internal\n        noSelfCall(self)\n    {\n        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));\n        }\n    }\n\n    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value\n    function beforeModifyLiquidity(\n        IHooks self,\n        PoolKey memory key,\n        ModifyLiquidityParams memory params,\n        bytes calldata hookData\n    ) internal noSelfCall(self) {\n        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));\n        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));\n        }\n    }\n\n    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value\n    function afterModifyLiquidity(\n        IHooks self,\n        PoolKey memory key,\n        ModifyLiquidityParams memory params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {\n        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);\n\n        callerDelta = delta;\n        if (params.liquidityDelta > 0) {\n            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {\n                hookDelta = BalanceDelta.wrap(\n                    self.callHookWithReturnDelta(\n                        abi.encodeCall(\n                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)\n                        ),\n                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)\n                    )\n                );\n                callerDelta = callerDelta - hookDelta;\n            }\n        } else {\n            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {\n                hookDelta = BalanceDelta.wrap(\n                    self.callHookWithReturnDelta(\n                        abi.encodeCall(\n                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)\n                        ),\n                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)\n                    )\n                );\n                callerDelta = callerDelta - hookDelta;\n            }\n        }\n    }\n\n    /// @notice calls beforeSwap hook if permissioned and validates return value\n    function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n        internal\n        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)\n    {\n        amountToSwap = params.amountSpecified;\n        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);\n\n        if (self.hasPermission(BEFORE_SWAP_FLAG)) {\n            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));\n\n            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee\n            if (result.length != 96) InvalidHookResponse.selector.revertWith();\n\n            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag\n            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used\n            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();\n\n            // skip this logic for the case where the hook return is 0\n            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {\n                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());\n\n                // any return in unspecified is passed to the afterSwap hook for handling\n                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();\n\n                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)\n                if (hookDeltaSpecified != 0) {\n                    bool exactInput = amountToSwap < 0;\n                    amountToSwap += hookDeltaSpecified;\n                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {\n                        HookDeltaExceedsSwapAmount.selector.revertWith();\n                    }\n                }\n            }\n        }\n    }\n\n    /// @notice calls afterSwap hook if permissioned and validates return value\n    function afterSwap(\n        IHooks self,\n        PoolKey memory key,\n        SwapParams memory params,\n        BalanceDelta swapDelta,\n        bytes calldata hookData,\n        BeforeSwapDelta beforeSwapHookReturn\n    ) internal returns (BalanceDelta, BalanceDelta) {\n        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);\n\n        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();\n        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();\n\n        if (self.hasPermission(AFTER_SWAP_FLAG)) {\n            hookDeltaUnspecified += self.callHookWithReturnDelta(\n                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),\n                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)\n            ).toInt128();\n        }\n\n        BalanceDelta hookDelta;\n        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {\n            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)\n                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)\n                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);\n\n            // the caller has to pay for (or receive) the hook's delta\n            swapDelta = swapDelta - hookDelta;\n        }\n        return (swapDelta, hookDelta);\n    }\n\n    /// @notice calls beforeDonate hook if permissioned and validates return value\n    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        internal\n        noSelfCall(self)\n    {\n        if (self.hasPermission(BEFORE_DONATE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));\n        }\n    }\n\n    /// @notice calls afterDonate hook if permissioned and validates return value\n    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        internal\n        noSelfCall(self)\n    {\n        if (self.hasPermission(AFTER_DONATE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));\n        }\n    }\n\n    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {\n        return uint160(address(self)) & flag != 0;\n    }\n}\n"},"@uniswap/v4-core/src/libraries/LPFeeLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @notice Library of helper functions for a pools LP fee\nlibrary LPFeeLibrary {\n    using LPFeeLibrary for uint24;\n    using CustomRevert for bytes4;\n\n    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.\n    error LPFeeTooLarge(uint24 fee);\n\n    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE\n    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;\n\n    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap\n    // only dynamic-fee pools can return a fee via the beforeSwap hook\n    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;\n\n    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook\n    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;\n\n    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%\n    uint24 public constant MAX_LP_FEE = 1000000;\n\n    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee\n    /// @param self The fee to check\n    /// @return bool True of the fee is dynamic\n    function isDynamicFee(uint24 self) internal pure returns (bool) {\n        return self == DYNAMIC_FEE_FLAG;\n    }\n\n    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee\n    /// @param self The fee to check\n    /// @return bool True of the fee is valid\n    function isValid(uint24 self) internal pure returns (bool) {\n        return self <= MAX_LP_FEE;\n    }\n\n    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid\n    /// @param self The fee to validate\n    function validate(uint24 self) internal pure {\n        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);\n    }\n\n    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.\n    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook\n    /// @param self The fee to get the initial LP from\n    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)\n    function getInitialLPFee(uint24 self) internal pure returns (uint24) {\n        // the initial fee for a dynamic fee pool is 0\n        if (self.isDynamicFee()) return 0;\n        self.validate();\n        return self;\n    }\n\n    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)\n    /// @param self The fee to check\n    /// @return bool True of the fee has the override flag set\n    function isOverride(uint24 self) internal pure returns (bool) {\n        return self & OVERRIDE_FEE_FLAG != 0;\n    }\n\n    /// @notice returns a fee with the override flag removed\n    /// @param self The fee to remove the override flag from\n    /// @return fee The fee without the override flag set\n    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {\n        return self & REMOVE_OVERRIDE_MASK;\n    }\n\n    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)\n    /// @param self The fee to remove the override flag from, and then validate\n    /// @return fee The fee without the override flag set (if valid)\n    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {\n        fee = self.removeOverrideFlag();\n        fee.validate();\n    }\n}\n"},"@uniswap/v4-core/src/libraries/ParseBytes.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.\n/// @dev parseSelector also is used to parse the expected selector\n/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).\nlibrary ParseBytes {\n    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {\n        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));\n        assembly (\"memory-safe\") {\n            selector := mload(add(result, 0x20))\n        }\n    }\n\n    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {\n        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));\n        assembly (\"memory-safe\") {\n            lpFee := mload(add(result, 0x60))\n        }\n    }\n\n    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {\n        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));\n        assembly (\"memory-safe\") {\n            hookReturn := mload(add(result, 0x40))\n        }\n    }\n}\n"},"@uniswap/v4-core/src/libraries/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n    using CustomRevert for bytes4;\n\n    error SafeCastOverflow();\n\n    /// @notice Cast a uint256 to a uint160, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return y The downcasted integer, now type uint160\n    function toUint160(uint256 x) internal pure returns (uint160 y) {\n        y = uint160(x);\n        if (y != x) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a uint128, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return y The downcasted integer, now type uint128\n    function toUint128(uint256 x) internal pure returns (uint128 y) {\n        y = uint128(x);\n        if (x != y) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n    /// @param x The int128 to be casted\n    /// @return y The casted integer, now type uint128\n    function toUint128(int128 x) internal pure returns (uint128 y) {\n        if (x < 0) SafeCastOverflow.selector.revertWith();\n        y = uint128(x);\n    }\n\n    /// @notice Cast a int256 to a int128, revert on overflow or underflow\n    /// @param x The int256 to be downcasted\n    /// @return y The downcasted integer, now type int128\n    function toInt128(int256 x) internal pure returns (int128 y) {\n        y = int128(x);\n        if (y != x) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a int256, revert on overflow\n    /// @param x The uint256 to be casted\n    /// @return y The casted integer, now type int256\n    function toInt256(uint256 x) internal pure returns (int256 y) {\n        y = int256(x);\n        if (y < 0) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a int128, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return The downcasted integer, now type int128\n    function toInt128(uint256 x) internal pure returns (int128) {\n        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n        return int128(int256(x));\n    }\n}\n"},"@uniswap/v4-core/src/types/BalanceDelta.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n    assembly (\"memory-safe\") {\n        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n    }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n    int256 res0;\n    int256 res1;\n    assembly (\"memory-safe\") {\n        let a0 := sar(128, a)\n        let a1 := signextend(15, a)\n        let b0 := sar(128, b)\n        let b1 := signextend(15, b)\n        res0 := add(a0, b0)\n        res1 := add(a1, b1)\n    }\n    return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n    int256 res0;\n    int256 res1;\n    assembly (\"memory-safe\") {\n        let a0 := sar(128, a)\n        let a1 := signextend(15, a)\n        let b0 := sar(128, b)\n        let b1 := signextend(15, b)\n        res0 := sub(a0, b0)\n        res1 := sub(a1, b1)\n    }\n    return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n    /// @notice A BalanceDelta of 0\n    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n        assembly (\"memory-safe\") {\n            _amount0 := sar(128, balanceDelta)\n        }\n    }\n\n    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n        assembly (\"memory-safe\") {\n            _amount1 := signextend(15, balanceDelta)\n        }\n    }\n}\n"},"@uniswap/v4-core/src/types/BeforeSwapDelta.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n    pure\n    returns (BeforeSwapDelta beforeSwapDelta)\n{\n    assembly (\"memory-safe\") {\n        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n    }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n    /// @notice A BeforeSwapDelta of 0\n    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n    /// returned by beforeSwap\n    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n        assembly (\"memory-safe\") {\n            deltaSpecified := sar(128, delta)\n        }\n    }\n\n    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n    /// returned by beforeSwap and afterSwap\n    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n        assembly (\"memory-safe\") {\n            deltaUnspecified := signextend(15, delta)\n        }\n    }\n}\n"},"@uniswap/v4-core/src/types/Currency.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n    error NativeTransferFailed();\n\n    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n    error ERC20TransferFailed();\n\n    /// @notice A constant to represent the native currency\n    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n    function transfer(Currency currency, address to, uint256 amount) internal {\n        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n        // modified custom error selectors\n\n        bool success;\n        if (currency.isAddressZero()) {\n            assembly (\"memory-safe\") {\n                // Transfer the ETH and revert if it fails.\n                success := call(gas(), to, amount, 0, 0, 0, 0)\n            }\n            // revert with NativeTransferFailed, containing the bubbled up error as an argument\n            if (!success) {\n                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n            }\n        } else {\n            assembly (\"memory-safe\") {\n                // Get a pointer to some free memory.\n                let fmp := mload(0x40)\n\n                // Write the abi-encoded calldata into memory, beginning with the function selector.\n                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n                mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n                success :=\n                    and(\n                        // Set success to whether the call reverted, if not we check it either\n                        // returned exactly 1 (can't just be non-zero data), or had no return data.\n                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                        // Counterintuitively, this call must be positioned second to the or() call in the\n                        // surrounding and() call or else returndatasize() will be zero during the computation.\n                        call(gas(), currency, 0, fmp, 68, 0, 32)\n                    )\n\n                // Now clean the memory we used\n                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n            }\n            // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n            if (!success) {\n                CustomRevert.bubbleUpAndRevertWith(\n                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n                );\n            }\n        }\n    }\n\n    function balanceOfSelf(Currency currency) internal view returns (uint256) {\n        if (currency.isAddressZero()) {\n            return address(this).balance;\n        } else {\n            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n        }\n    }\n\n    function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n        if (currency.isAddressZero()) {\n            return owner.balance;\n        } else {\n            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n        }\n    }\n\n    function isAddressZero(Currency currency) internal pure returns (bool) {\n        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n    }\n\n    function toId(Currency currency) internal pure returns (uint256) {\n        return uint160(Currency.unwrap(currency));\n    }\n\n    // If the upper 12 bytes are non-zero, they will be zero-ed out\n    // Therefore, fromId() and toId() are not inverses of each other\n    function fromId(uint256 id) internal pure returns (Currency) {\n        return Currency.wrap(address(uint160(id)));\n    }\n}\n"},"@uniswap/v4-core/src/types/PoolId.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n    /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n        assembly (\"memory-safe\") {\n            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n            poolId := keccak256(poolKey, 0xa0)\n        }\n    }\n}\n"},"dice-integration/DiceRecoveryEntropy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {IRandomnessConsumer} from \"../v2/IRandomnessProvider.sol\";\n\ninterface IDiceCoordinator {\n    struct ProviderInfo {\n        uint128 feeInWei;uint128 accruedFeesInWei;bytes32 originalCommitment;\n        uint64 originalCommitmentSequenceNumber;bytes commitmentMetadata;bytes uri;\n        uint64 endSequenceNumber;uint64 sequenceNumber;bytes32 currentCommitment;\n        uint64 currentCommitmentSequenceNumber;address feeManager;uint32 maxNumHashes;uint32 defaultGasLimit;\n    }\n    struct OracleRequest {\n        address provider;uint64 sequenceNumber;uint32 numHashes;bytes32 commitment;\n        uint64 blockNumber;address requester;bool useBlockhash;uint8 callbackStatus;\n        uint16 gasLimit10k;uint128 feePaid;\n    }\n    function getFeeV2(address provider,uint32 gasLimit) external view returns(uint128);\n    function getRequestV2(address provider,uint64 sequence) external view returns(OracleRequest memory);\n    function getProviderInfoV2(address provider) external view returns(ProviderInfo memory);\n    function requestV2(address provider,bytes32 contribution,uint32 gasLimit) external payable returns(uint64);\n    function revealWithCallback(address provider,uint64 sequence,bytes32 contribution,bytes32 providerContribution) external;\n    function refundRequest(address provider,uint64 sequence) external;\n}\n\n/// Isolated QUACKS candidate. Requester entropy is supplied atomically by the\n/// game caller's CSPRNG, never derived solely from public chain/game state.\n/// Provider secrecy, ordering and withholding remain external trust assumptions.\ncontract DiceRecoveryEntropy is Ownable,ReentrancyGuard {\n    IDiceCoordinator public immutable coordinator;\n    address public immutable provider;\n    uint256 public immutable timeout;\n    uint256 public immutable feeCeiling;\n    uint32 public constant CALLBACK_GAS=250000;\n    uint32 public constant MAX_PROOF_HASHES=4096;\n    mapping(address=>bool) public consumers;\n    address public paidConsumer;\n    mapping(uint256=>address) public feePayers;\n    mapping(address=>uint256) public feeRefunds;\n    uint256 public totalFeeRefunds;\n    mapping(bytes32=>bool) public usedContribution;\n    bool public frozen;\n    uint256 public requested;\n    uint256 public nextDelivery=1;\n    struct Request {\n        address consumer;uint64 sequence;uint64 createdAt;\n        bool ready;bool delivered;bool cancelled;bool feeRecovered;\n        uint256 seed;bytes32 contribution;bytes32 commitment;uint32 numHashes;\n    }\n    mapping(uint256=>Request) public requests;\n    mapping(uint64=>uint256) public sequenceToRequest;\n    event Requested(uint256 indexed id,address indexed consumer,uint64 indexed sequence,uint256 context,bytes32 contribution);\n    event Ready(uint256 indexed id,uint256 seed);\n    event Delivered(uint256 indexed id,uint256 seed);\n    event Cancelled(uint256 indexed id);\n    event FeeRecovered(uint256 indexed id,uint256 amount);\n    event FeePaid(uint256 indexed id,address indexed payer,uint256 amount);\n    event FeeRefundCredited(uint256 indexed id,address indexed payer,uint256 amount);\n    event FeeRefundWithdrawn(address indexed payer,address indexed recipient,uint256 amount);\n    event ProofRecovered(uint256 indexed id);\n    error Unauthorized();error Unavailable();error ContributionRequired();\n    error FeeMismatch(uint256 expected,uint256 supplied);\n    constructor(address coordinator_,address provider_,uint256 timeout_,uint256 ceiling_) Ownable(msg.sender) {\n        if(coordinator_.code.length==0||provider_==address(0)||timeout_<1 days||ceiling_==0)revert Unavailable();\n        coordinator=IDiceCoordinator(coordinator_);provider=provider_;timeout=timeout_;feeCeiling=ceiling_;\n    }\n    receive() external payable{}\n    function configureConsumers(address nft,address draw) external onlyOwner {\n        if(frozen||nft.code.length==0||draw.code.length==0||nft==draw)revert Unavailable();\n        consumers[nft]=true;consumers[draw]=true;paidConsumer=nft;frozen=true;\n    }\n    function fee() public view returns(uint256){return coordinator.getFeeV2(provider,CALLBACK_GAS);}\n    // Explicit fail-closed compatibility selector: no predictable legacy path.\n    function request(uint256) external pure returns(uint256){revert ContributionRequired();}\n    function requestWithContribution(uint256 context,bytes32 contribution) external nonReentrant returns(uint256 id){\n        // Genesis keeps its existing reserve-funded path. User refund credits\n        // are liabilities, never available for new sponsored requests.\n        uint256 cost=fee();if(cost>address(this).balance-totalFeeRefunds)revert Unavailable();\n        return _request(context,contribution,cost);\n    }\n    function requestWithPayment(uint256 context,bytes32 contribution,address payer) external payable nonReentrant returns(uint256 id){\n        if(msg.sender!=paidConsumer||payer==address(0))revert Unauthorized();\n        uint256 cost=fee();if(msg.value!=cost)revert FeeMismatch(cost,msg.value);\n        id=_request(context,contribution,cost);feePayers[id]=payer;emit FeePaid(id,payer,cost);\n    }\n    function _request(uint256 context,bytes32 contribution,uint256 cost) internal returns(uint256 id){\n        if(!consumers[msg.sender])revert Unauthorized();\n        if(contribution==bytes32(0)||usedContribution[contribution])revert ContributionRequired();\n        if(cost>feeCeiling)revert Unavailable();\n        usedContribution[contribution]=true;id=++requested;\n        bytes32 word=keccak256(abi.encode(block.chainid,address(this),msg.sender,id,context,contribution));\n        uint64 sequence=coordinator.requestV2{value:cost}(provider,word,CALLBACK_GAS);\n        if(sequence==0||sequenceToRequest[sequence]!=0)revert Unavailable();\n        IDiceCoordinator.OracleRequest memory original=coordinator.getRequestV2(provider,sequence);\n        if(original.requester!=address(this)||original.provider!=provider||original.sequenceNumber!=sequence||original.useBlockhash||original.numHashes==0||original.numHashes>MAX_PROOF_HASHES)revert Unavailable();\n        sequenceToRequest[sequence]=id;\n        requests[id]=Request(msg.sender,sequence,uint64(block.timestamp),false,false,false,false,0,word,original.commitment,original.numHashes);\n        emit Requested(id,msg.sender,sequence,context,word);\n    }\n    function _entropyCallback(uint64 sequence,address provider_,bytes32 word) external {\n        if(msg.sender!=address(coordinator)||provider_!=provider)revert Unauthorized();\n        uint256 id=sequenceToRequest[sequence];Request storage r=requests[id];\n        if(id==0||r.cancelled)revert Unavailable();if(r.ready)return;\n        r.seed=uint256(word);r.ready=true;emit Ready(id,r.seed);\n    }\n    function cancel(uint256 id) external {\n        Request storage r=requests[id];if(r.consumer!=msg.sender)revert Unauthorized();\n        if(r.ready||r.delivered||r.cancelled||block.timestamp<r.createdAt+timeout)revert Unavailable();\n        // A later hash-chain reveal exposes proofs for earlier requests too.\n        // Once a valid proof is public, preserve that outcome even if its callback failed.\n        if(coordinator.getProviderInfoV2(provider).currentCommitmentSequenceNumber>=r.sequence)revert Unavailable();\n        r.cancelled=true;emit Cancelled(id);\n    }\n    /// Recover the SAME Dice word against the original coordinator commitment.\n    /// Works even if Dice cleared a failed callback. No owner-selected seed,\n    /// new request, alternate oracle or block randomness is involved.\n    function recoverFromProof(uint256 id,bytes32 providerContribution) external {\n        Request storage r=requests[id];\n        if(r.consumer==address(0)||r.cancelled||r.ready||r.delivered)revert Unavailable();\n        bytes32 anchor=providerContribution;\n        for(uint256 i;i<r.numHashes;i++)anchor=keccak256(abi.encodePacked(anchor));\n        if(keccak256(abi.encodePacked(keccak256(abi.encodePacked(r.contribution)),anchor))!=r.commitment)revert Unavailable();\n        r.seed=uint256(keccak256(abi.encodePacked(r.contribution,providerContribution,bytes32(0))));r.ready=true;\n        emit ProofRecovered(id);emit Ready(id,r.seed);\n    }\n    function advanceCancelled(uint256 limit) public {\n        if(limit>100)revert Unavailable();\n        for(uint256 i;i<limit&&nextDelivery<=requested&&requests[nextDelivery].cancelled;i++)nextDelivery++;\n    }\n    function deliverNext() external nonReentrant {\n        advanceCancelled(100);uint256 id=nextDelivery;Request storage r=requests[id];\n        if(!r.ready||r.delivered||r.cancelled)revert Unavailable();\n        r.delivered=true;nextDelivery++;IRandomnessConsumer(r.consumer).fulfillEntropy(id,r.seed);emit Delivered(id,r.seed);\n    }\n    /// Dice retries require the provider proof, obtainable from a failed reveal.\n    /// No invented Quiver-style retryCallback(address,uint64) coordinator API.\n    function retryCallback(uint256 id,bytes32 providerContribution) external nonReentrant {\n        Request storage r=requests[id];\n        if(r.consumer==address(0)||r.cancelled||r.ready||r.delivered)revert Unavailable();\n        coordinator.revealWithCallback(provider,r.sequence,r.contribution,providerContribution);\n    }\n    /// Separate from game cancellation: failed/unavailable oracle refunds cannot\n    /// block a BREAD refund or replacement retry. User-paid refunds belong to\n    /// the original payer; reserve-funded Genesis refunds replenish its reserve.\n    function recoverFee(uint256 id) external nonReentrant {\n        Request storage r=requests[id];if(!r.cancelled||r.feeRecovered)revert Unavailable();\n        r.feeRecovered=true;uint256 beforeBalance=address(this).balance;\n        coordinator.refundRequest(provider,r.sequence);\n        uint256 amount=address(this).balance-beforeBalance;address payer=feePayers[id];\n        if(payer!=address(0)){feeRefunds[payer]+=amount;totalFeeRefunds+=amount;emit FeeRefundCredited(id,payer,amount);}\n        emit FeeRecovered(id,amount);\n    }\n    function withdrawFeeRefund(address payable recipient) external nonReentrant {\n        uint256 amount=feeRefunds[msg.sender];if(amount==0||recipient==address(0)||recipient==address(this))revert Unavailable();\n        feeRefunds[msg.sender]=0;totalFeeRefunds-=amount;\n        (bool success,)=recipient.call{value:amount}(\"\");if(!success)revert Unavailable();\n        emit FeeRefundWithdrawn(msg.sender,recipient,amount);\n    }\n}\n"},"dice-integration/Fixtures.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {DiceRecoveryEntropy} from \"./DiceRecoveryEntropy.sol\";\ncontract DiceBoundaryConsumer {\n    DiceRecoveryEntropy public immutable adapter;bool public fail;\n    mapping(uint256=>uint256) public seeds;\n    constructor(address a){adapter=DiceRecoveryEntropy(payable(a));}\n    function request(bytes32 word) external returns(uint256){return adapter.requestWithContribution(1,word);}\n    function cancel(uint256 id) external {adapter.cancel(id);}\n    function setFail(bool value) external {fail=value;}\n    function fulfillEntropy(uint256 id,uint256 seed) external {require(msg.sender==address(adapter)&&!fail);seeds[id]=seed;}\n}\n"},"dice-integration/GenesisDrawDice.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.28;\r\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport {MerkleProof} from \"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol\";\r\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\nimport {EIP712} from \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\r\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\r\ninterface IGenesisQuacks {function mintGenesis(address to,uint256 id,uint256 seed) external;function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256);}\r\ninterface IDrawEntropy {function requestWithContribution(uint256 roundId,bytes32 contribution) external returns(uint256);function cancel(uint256 requestId) external;}\r\n\r\n/// @notice Phased whitelist/public draws with frozen eligibility and asynchronous entropy.\ncontract GenesisDrawDice is ReentrancyGuard,EIP712,Ownable {\r\n    uint256 public constant INTERVAL=30 minutes;\r\n    uint256 public constant CLAIM_WINDOW=24 hours;\r\n    bytes32 public eligibilityRoot;\n    bytes32 public publicEligibilityRoot;\n    uint256 public whitelistWinLimit;\n    uint256 public whitelistWins;\n    bool public stagedEligibility;\n    uint256 public communityWinLimit;\n    uint256 public regularWhitelistWinLimit;\n    event StagesConfigured(uint256 communityWins,uint256 regularWins);\n    event RegistrationStageOpened(uint256 stage);\n    event WhitelistConfigured(uint256 wins,bytes32 whitelistRoot,bytes32 publicRoot);\n    event PublicRegistrationOpened(uint256 whitelistWins);\n    event EmptyRoundRestarted(uint256 nextDrawAt);\n    bool public configurationFrozen;bool public paused;bool public oneWinPerWallet=true;\r\n    uint256 public claimedCount;uint256 public pendingClaimCount;\r\n    event ConfigurationFrozen();event PauseChanged(bool paused);\r\n    address public immutable eligibilitySigner;\r\n    bytes32 public constant ENTRY_TYPEHASH=keccak256(\"Entry(address wallet,uint256 deadline)\");\r\n    IGenesisQuacks public immutable quacks;\r\n    IDrawEntropy public immutable entropy;\r\n    uint256 public nextDrawAt;\r\n    uint256 public rounds;\r\n    uint256 public pendingRequest;\r\n    uint256 public snapshotSize;\r\n    uint256 public selectedToken;\r\n    mapping(uint256=>bool) public usedRequest;\r\n    address[] public entrants;\r\n    uint256[] public pool;\r\n    mapping(address=>bool) public registered;\r\n    mapping(address=>uint256) public pendingAward;\r\n    mapping(address=>bool) public hasClaimed;\r\n    struct Award {address winner;uint64 deadline;uint256 seed;bool claimed;}\r\n    mapping(uint256=>Award) public awards;\r\n    event Registered(address indexed guest);\r\n    event DrawRequested(uint256 indexed round,uint256 indexed requestId,uint256 indexed tokenId,uint256 entrants);\r\n    event Awarded(uint256 indexed tokenId,address indexed winner,uint256 deadline);\r\n    event Returned(uint256 indexed tokenId);\r\n    event Claimed(uint256 indexed tokenId,address indexed winner);\r\n    constructor(address nft,address rng,bytes32 root,uint256 startAt,address signer) EIP712(\"Quacks Genesis\",\"2\") Ownable(msg.sender){\r\n        require(nft.code.length>0 && rng.code.length>0 && (root!=bytes32(0) || signer!=address(0)) && startAt>block.timestamp,\"Invalid setup\");\r\n        quacks=IGenesisQuacks(nft);entropy=IDrawEntropy(rng);eligibilityRoot=root;eligibilitySigner=signer;nextDrawAt=startAt;\r\n        for(uint256 i=333;i>0;i--)pool.push(i);\r\n    }\r\n    function register(bytes32[] calldata proof) external {\n        require(!stagedEligibility,\"Use staged proof\");\n        bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\n        require(eligibilityRoot!=bytes32(0)&&MerkleProof.verifyCalldata(proof,eligibilityRoot,leaf),\"Not eligible\");_register();\n    }\n    function registrationStage() public view returns(uint256){\n        if(publicRegistrationOpen())return 2;\n        return stagedEligibility&&whitelistWins<communityWinLimit?0:1;\n    }\n    function configureStages(uint256 communityWins,uint256 regularWins) external onlyOwner {\n        require(!configurationFrozen,\"Frozen\");\n        require(communityWins>0&&regularWins>0&&communityWins+regularWins<333,\"Invalid stage allocations\");\n        require(eligibilityRoot!=bytes32(0)&&eligibilitySigner!=address(0),\"Missing staged eligibility\");\n        stagedEligibility=true;communityWinLimit=communityWins;regularWhitelistWinLimit=regularWins;\n        whitelistWinLimit=communityWins+regularWins;publicEligibilityRoot=bytes32(0);\n        emit StagesConfigured(communityWins,regularWins);\n    }\n    function registerStage(uint256 stage,bytes32[] calldata proof) external {\n        require(stagedEligibility&&stage<2&&stage<=registrationStage(),\"Stage not open\");\n        bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender,stage))));\n        require(MerkleProof.verifyCalldata(proof,eligibilityRoot,leaf),\"Not eligible\");_register();\n    }\n    function publicRegistrationOpen() public view returns(bool){return whitelistWins>=whitelistWinLimit;}\n    /// @notice Zero public root and signer means permissionless public registration.\n    function registerPublic(bytes32[] calldata proof) external {\n        require(publicRegistrationOpen(),\"Whitelist phase\");\n        if(publicEligibilityRoot!=bytes32(0)){\n            bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\n            require(MerkleProof.verifyCalldata(proof,publicEligibilityRoot,leaf),\"Not eligible\");\n        }else require(eligibilitySigner==address(0),\"Public ticket required\");\n        _register();\n    }\n    function registerWithTicket(uint256 deadline,bytes calldata signature) external {\n        require(publicRegistrationOpen(),\"Whitelist phase\");\n        require(!registered[msg.sender] && eligibilitySigner!=address(0) && block.timestamp<=deadline,\"Entry unavailable\");\n        bytes32 digest=_hashTypedDataV4(keccak256(abi.encode(ENTRY_TYPEHASH,msg.sender,deadline)));\n        require(ECDSA.recover(digest,signature)==eligibilitySigner,\"Not eligible\");_register();\n    }\n    function _register() internal {\n        require(configurationFrozen&&!paused,\"Entry paused or not frozen\");\n        require(!registered[msg.sender],\"Already registered\");\n        require(pool.length>0||pendingRequest!=0||pendingClaimCount>0,\"Genesis complete\");\n        registered[msg.sender]=true;entrants.push(msg.sender);emit Registered(msg.sender);\n    }\n    function configureWhitelist(uint256 wins,bytes32 publicRoot) external onlyOwner {\n        require(!stagedEligibility,\"Use stage allocations\");\n        require(!configurationFrozen,\"Frozen\");require(wins<=333&&(wins==0||eligibilityRoot!=bytes32(0)),\"Invalid whitelist\");\n        whitelistWinLimit=wins;publicEligibilityRoot=publicRoot;emit WhitelistConfigured(wins,eligibilityRoot,publicRoot);\n    }\r\n    function configureEligibility(bytes32 root,bool singleWin) external onlyOwner {require(!configurationFrozen,\"Frozen\");require(root!=bytes32(0)||eligibilitySigner!=address(0),\"No eligibility\");eligibilityRoot=root;oneWinPerWallet=singleWin;}\r\n    function freezeEconomicConfiguration() external onlyOwner {require(!configurationFrozen,\"Frozen\");require(whitelistWinLimit==0||eligibilityRoot!=bytes32(0),\"No whitelist root\");configurationFrozen=true;emit ConfigurationFrozen();}\n    function setPaused(bool value) external onlyOwner {paused=value;emit PauseChanged(value);}\r\n    function entrantCount() external view returns(uint256){return entrants.length;}\r\n    function poolCount() external view returns(uint256){return pool.length;}\r\n    function requestDraw(bytes32 contribution) external nonReentrant {\r\n        require(configurationFrozen&&!paused&&block.timestamp>=nextDrawAt && pendingRequest==0 && pool.length>0,\"Draw unavailable\");\n        if(entrants.length==0){nextDrawAt=block.timestamp+INTERVAL;emit EmptyRoundRestarted(nextDrawAt);return;}\n        selectedToken=pool[pool.length-1];pool.pop();snapshotSize=entrants.length;rounds++;nextDrawAt=block.timestamp+INTERVAL;\r\n        uint256 requestId=entropy.requestWithContribution(rounds,contribution);require(requestId>0 && !usedRequest[requestId],\"Bad request\");usedRequest[requestId]=true;pendingRequest=requestId;\r\n        emit DrawRequested(rounds,requestId,selectedToken,snapshotSize);\r\n    }\r\n    function fulfillEntropy(uint256 requestId,uint256 seed) external nonReentrant {\r\n        require(msg.sender==address(entropy) && requestId==pendingRequest && requestId!=0,\"Invalid fulfillment\");\r\n        uint256 index=seed%snapshotSize;address winner=entrants[index];entrants[index]=entrants[entrants.length-1];entrants.pop();\r\n        uint256 token=selectedToken;pendingRequest=0;selectedToken=0;snapshotSize=0;\r\n        quacks.reserveGenesisArtwork(token,seed);pendingAward[winner]=token;\r\n        pendingClaimCount++;awards[token]=Award(winner,uint64(block.timestamp+CLAIM_WINDOW),seed,false);emit Awarded(token,winner,block.timestamp+CLAIM_WINDOW);\n        if(whitelistWins<whitelistWinLimit){whitelistWins++;if(stagedEligibility&&whitelistWins==communityWinLimit)emit RegistrationStageOpened(1);if(whitelistWins==whitelistWinLimit)emit PublicRegistrationOpened(whitelistWins);}\n    }\r\n    function claim(uint256 token) external nonReentrant {\r\n        Award storage award=awards[token];require(award.winner==msg.sender && !award.claimed && block.timestamp<award.deadline,\"Claim unavailable\");\r\n        claimedCount++;pendingClaimCount--;award.claimed=true;pendingAward[msg.sender]=0;hasClaimed[msg.sender]=true;quacks.mintGenesis(msg.sender,token,award.seed);if(!oneWinPerWallet)entrants.push(msg.sender);emit Claimed(token,msg.sender);\r\n    }\r\n    function recoverStalledDraw() external nonReentrant {require(pendingRequest!=0,\"No request\");entropy.cancel(pendingRequest);pool.push(selectedToken);pendingRequest=0;selectedToken=0;snapshotSize=0;}\r\n    function recycle(uint256 token) external {\r\n        Award memory award=awards[token];require(award.winner!=address(0) && !award.claimed && block.timestamp>=award.deadline,\"Not expired\");\r\n        pendingClaimCount--;delete awards[token];pool.push(token);pendingAward[award.winner]=0;entrants.push(award.winner);emit Returned(token);\r\n    }\r\n}\r\n"},"dice-integration/QuacksDice.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {ERC721} from \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport {ERC2981} from \"@openzeppelin/contracts/token/common/ERC2981.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {EconomicConfig} from \"../v2/EconomicConfig.sol\";\nimport {Bread} from \"../v2/Bread.sol\";\nimport {TraitInventory} from \"../v2/TraitInventory.sol\";\nimport {IRandomnessProvider} from \"../v2/IRandomnessProvider.sol\";\ninterface IDiceRequests {function fee() external view returns(uint256);function requestWithPayment(uint256 context,bytes32 contribution,address payer) external payable returns(uint256);}\ninterface IRendererV2 {function tokenURI(uint256,bool,uint8,uint256) external view returns(string memory);function burnedTokenURI(uint256,uint256) external view returns(string memory);}\n\ncontract QuacksDice is ERC721,ERC2981,Ownable,ReentrancyGuard {\n    uint256 public constant MAX_SUPPLY=3333;uint256 public constant GENESIS_SUPPLY=333;\n    uint256 public constant INCUBATION=7 days;uint256 public immutable recoveryDelay;\n    EconomicConfig public immutable economics;Bread public immutable bread;\n    TraitInventory public immutable traits;IRandomnessProvider public entropy;IRendererV2 public renderer;\n    address public draw;bool public configured;bool public rendererFrozen;bool public hatchingPaused;\n    uint256 public expansionMinted;uint256 public genesisMinted;uint256 public totalQuacksBurned;\n    mapping(uint256=>uint256) public transferNonce;\n    mapping(uint256=>bool) public revealed;mapping(uint256=>uint256) public artworkOf;\n    mapping(uint256=>bool) public wasBurned;mapping(uint256=>address) public burnedBy;mapping(uint256=>uint256) public replacementOf;\n    struct Egg {uint64 readyAt;uint64 requestedAt;uint8 mode;bool paid;bool cancelled;uint256 requestId;}\n    mapping(uint256=>Egg) public eggs;mapping(uint256=>uint256) public requestToken;mapping(uint256=>bool) public usedRequest;\n    event EggMinted(uint256 indexed tokenId,address indexed owner,uint256 cost,uint8 mode,uint256 readyAt);\n    event HatchModeAdjusted(uint256 indexed tokenId,uint8 requestedMode,uint256 premiumRefund);\n    event HatchRequested(uint256 indexed tokenId,uint256 indexed requestId);\n    event QuackGenerated(uint256 indexed tokenId,uint256 indexed artwork,address indexed owner);\n    event QuackBurned(uint256 indexed tokenId,address indexed owner);\n    event ReplacementGenerated(uint256 indexed burnedId,uint256 indexed replacementId);\n    event HatchRecovered(uint256 indexed tokenId,address indexed owner);\n    event MetadataUpdate(uint256 tokenId);\n    event RendererFrozen(address renderer);event HatchingPauseChanged(bool paused);\n    error Unavailable();error Unauthorized();error SoldOut();error InvalidConfiguration();error InvalidRequest();\n    constructor(address token,address config,address inventory,uint256 timeout) ERC721(\"Quacks\",\"QUACKS\") Ownable(msg.sender){\n        if(token.code.length==0||config.code.length==0||inventory.code.length==0||timeout<1 days) revert InvalidConfiguration();\n        bread=Bread(token);economics=EconomicConfig(config);traits=TraitInventory(inventory);recoveryDelay=timeout;\n    }\n    function configure(address draws,address rng,address art) external onlyOwner {\n        if(configured||draws.code.length==0||rng.code.length==0||art.code.length==0) revert InvalidConfiguration();\n        draw=draws;entropy=IRandomnessProvider(rng);renderer=IRendererV2(art);configured=true;\n    }\n    function setRenderer(address art) external onlyOwner {if(rendererFrozen||art.code.length==0) revert InvalidConfiguration();renderer=IRendererV2(art);}\n    function freezeRenderer() public virtual onlyOwner {if(rendererFrozen||address(renderer)==address(0)||!economics.frozen()) revert InvalidConfiguration();rendererFrozen=true;_setDefaultRoyalty(economics.treasury(),500);emit RendererFrozen(address(renderer));}\n    function setHatchingPaused(bool value) external onlyOwner {hatchingPaused=value;emit HatchingPauseChanged(value);}\n    function isGenesis(uint256 id) public pure returns(bool){return id>0&&id<=333;}\n    function lifetimeGenerated() public view returns(uint256){return genesisMinted+expansionMinted;}\n    /// @notice Reserved Genesis slots plus used expansion slots. Claims cannot hold back unlocks.\n    /// This is distinct from minted/live supply and never decreases after a burn or refund.\n    function generationProgress() public view returns(uint256){return GENESIS_SUPPLY+expansionMinted;}\n    function totalSupply() external view returns(uint256){return lifetimeGenerated()-totalQuacksBurned;}\n    function remainingGenerationSlots() external view returns(uint256){return 3333-lifetimeGenerated();}\n    function currentHatchCost() public view returns(uint256){return economics.cost(334+expansionMinted,0);}\n    function randomnessFee() external view returns(uint256){return IDiceRequests(address(entropy)).fee();}\n    function hatchCost(uint8 mode) public view returns(uint256){\n        uint256 cost=economics.cost(334+expansionMinted,mode);\n        if(mode>0&&!traits.hasModeAdvantage(generationProgress()+1,mode))revert Unavailable();return cost;\n    }\n    function _ready() internal view {if(!configured||!rendererFrozen||!traits.frozen()||!bread.frozen()||!economics.frozen()) revert Unavailable();}\n    function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256){\n        _ready();if(msg.sender!=draw||!isGenesis(id)) revert Unauthorized();\n        if(artworkOf[id]==0)artworkOf[id]=traits.assign(seed,generationProgress(),0);return artworkOf[id];\n    }\n    function mintGenesis(address to,uint256 id,uint256) external nonReentrant {\n        _ready();if(msg.sender!=draw||!isGenesis(id)||artworkOf[id]==0||revealed[id]||wasBurned[id]) revert Unauthorized();\n        genesisMinted++;revealed[id]=true;_safeMint(to,id);emit QuackGenerated(id,artworkOf[id],to);\n    }\n    function mintEgg(uint8 mode,uint256 maxCost) external nonReentrant returns(uint256 id){\n        _ready();if(hatchingPaused) revert Unavailable();if(expansionMinted>=3000) revert SoldOut();\n        uint256 cost=hatchCost(mode);if(cost>maxCost||cost>type(uint128).max) revert Unavailable();\n        id=334+expansionMinted++;eggs[id]=Egg(uint64(block.timestamp+INCUBATION),0,mode,true,false,0);\n        bread.payHatch(id,msg.sender,uint128(cost));_safeMint(msg.sender,id);emit EggMinted(id,msg.sender,cost,mode,block.timestamp+INCUBATION);\n    }\n    function hatch(uint256 id,bytes32 contribution) external payable nonReentrant {\n        if(ownerOf(id)!=msg.sender||revealed[id]||block.timestamp<eggs[id].readyAt) revert Unavailable();_request(id,contribution);\n    }\n    function _request(uint256 id,bytes32 contribution) internal {\n        Egg storage e=eggs[id];if(e.requestId!=0||e.cancelled) revert InvalidRequest();\n        e.requestedAt=uint64(block.timestamp);uint256 request=IDiceRequests(address(entropy)).requestWithPayment{value:msg.value}(id,contribution,msg.sender);\n        if(request==0||usedRequest[request]) revert InvalidRequest();usedRequest[request]=true;e.requestId=request;requestToken[request]=id;emit HatchRequested(id,request);\n    }\n    function fulfillEntropy(uint256 request,uint256 seed) external nonReentrant {\n        if(msg.sender!=address(entropy)) revert Unauthorized();uint256 id=requestToken[request];if(id==0) revert InvalidRequest();\n        delete requestToken[request];Egg storage e=eggs[id];uint256 refund;\n        if(e.paid&&e.mode>0&&!traits.hasModeAdvantage(generationProgress(),e.mode)){\n            (,uint128 paid,)=bread.hatchPayments(id);refund=paid-economics.cost(id,0);\n            emit HatchModeAdjusted(id,e.mode,refund);e.mode=0;\n        }\n        artworkOf[id]=traits.assign(seed,generationProgress(),e.mode);revealed[id]=true;\n        if(e.paid){if(refund>0)bread.resolveHatchPaymentPartial(id,ownerOf(id),uint128(refund));else bread.resolveHatchPayment(id,address(0));}\n        emit MetadataUpdate(id);emit QuackGenerated(id,artworkOf[id],ownerOf(id));\n    }\n    function burnForMint(uint256 id,bytes32 contribution) external payable nonReentrant returns(uint256 replacement){\n        _ready();if(hatchingPaused||ownerOf(id)!=msg.sender||!revealed[id]) revert Unavailable();if(expansionMinted>=3000) revert SoldOut();\n        _destroy(id);replacement=334+expansionMinted++;replacementOf[id]=replacement;eggs[replacement]=Egg(uint64(block.timestamp),0,0,false,false,0);\n        _request(replacement,contribution);_safeMint(msg.sender,replacement);emit ReplacementGenerated(id,replacement);\n    }\n    /// @notice Refund an expired paid request only after the provider atomically cancels it.\n    /// The burned egg's lifetime slot is not recycled; no ID or known random outcome is reused.\n    function recoverFailedHatch(uint256 id) external nonReentrant {\n        Egg storage e=eggs[id];if(ownerOf(id)!=msg.sender||revealed[id]||!e.paid||block.timestamp<(e.requestId==0?e.readyAt:e.requestedAt)+recoveryDelay) revert Unavailable();\n        if(e.requestId!=0){entropy.cancel(e.requestId);delete requestToken[e.requestId];}e.cancelled=true;_destroy(id);bread.resolveHatchPayment(id,msg.sender);emit HatchRecovered(id,msg.sender);\n    }\n    function retryFailedReplacement(uint256 id,bytes32 contribution) external payable nonReentrant {\n        Egg storage e=eggs[id];if(ownerOf(id)!=msg.sender||revealed[id]||e.paid||e.requestId==0||block.timestamp<e.requestedAt+recoveryDelay) revert Unavailable();\n        entropy.cancel(e.requestId);delete requestToken[e.requestId];e.requestId=0;_request(id,contribution);\n    }\n    function _destroy(uint256 id) internal {wasBurned[id]=true;burnedBy[id]=msg.sender;_burn(id);totalQuacksBurned++;emit QuackBurned(id,msg.sender);emit MetadataUpdate(id);}\n    function stage(uint256 id) public view returns(uint8){uint256 ready=eggs[id].readyAt;if(ready==0||block.timestamp>=ready)return 7;return uint8((INCUBATION-(ready-block.timestamp))/1 days);}\n    function tokenURI(uint256 id) public view override returns(string memory){\n        if(wasBurned[id])return renderer.burnedTokenURI(id,artworkOf[id]);\n        _requireOwned(id);return renderer.tokenURI(id,revealed[id],stage(id),artworkOf[id]);\n    }\n    function _update(address to,uint256 id,address auth) internal virtual override returns(address){transferNonce[id]++;return super._update(to,id,auth);}\n    function supportsInterface(bytes4 id) public view virtual override(ERC721,ERC2981) returns(bool){return id==0x49064906||super.supportsInterface(id);}\n}\n"},"dice-integration/RoyaltyQuacksDice.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {QuacksDice} from \"./QuacksDice.sol\";\n\ninterface IQuacksTransferValidator {\n    function validateTransfer(address caller,address from,address to,uint256 tokenId) external view;\n}\ninterface IQuacksRoyaltyStaking {function quacks() external view returns(address);function bread() external view returns(address);}\ninterface IQuacksCreatorToken {\n    event TransferValidatorUpdated(address oldValidator,address newValidator);\n    function getTransferValidator() external view returns(address);\n    function getTransferValidationFunction() external view returns(bytes4,bool);\n    function setTransferValidator(address validator) external;\n}\n\n/// Creator-token hook documented by OpenSea. The production validator and its\n/// marketplace authorization policy MUST be verified on the deployment chain.\n/// ERC-2981 alone reports 5%; the validator authorizes royalty-compliant sales.\ncontract RoyaltyQuacksDice is QuacksDice,IQuacksCreatorToken {\n    uint96 public constant ROYALTY_BPS=500;\n    address private transferValidator;\n    address public royaltyStaking;\n    event RoyaltyStakingConfigured(address indexed staking);\n    event RoyaltyPolicyFrozen(address indexed validator,address indexed receiver,uint96 bps);\n    constructor(address token,address config,address generator,uint256 timeout)\n        QuacksDice(token,config,generator,timeout) {}\n\n    function getTransferValidator() external view returns(address){return transferValidator;}\n    function getTransferValidationFunction() external pure returns(bytes4,bool){\n        return (IQuacksTransferValidator.validateTransfer.selector,true);\n    }\n    function setTransferValidator(address validator) external onlyOwner {\n        if(rendererFrozen||validator.code.length==0||validator==address(this))revert InvalidConfiguration();\n        emit TransferValidatorUpdated(transferValidator,validator);transferValidator=validator;\n    }\n    /// Fixed custody exception: only the bound staking contract can move tokens\n    /// into or out of its own custody. It cannot authorize marketplace transfers.\n    function setRoyaltyStaking(address staking) external onlyOwner {\n        if(rendererFrozen||royaltyStaking!=address(0)||staking.code.length==0)revert InvalidConfiguration();\n        if(IQuacksRoyaltyStaking(staking).quacks()!=address(this)||IQuacksRoyaltyStaking(staking).bread()!=address(bread))revert InvalidConfiguration();\n        royaltyStaking=staking;emit RoyaltyStakingConfigured(staking);\n    }\n    function freezeRenderer() public override onlyOwner {\n        if(transferValidator.code.length==0)revert InvalidConfiguration();\n        super.freezeRenderer();\n        emit RoyaltyPolicyFrozen(transferValidator,economics.treasury(),ROYALTY_BPS);\n    }\n    function _update(address to,uint256 id,address auth) internal override returns(address){\n        if(!rendererFrozen||transferValidator.code.length==0)revert InvalidConfiguration();\n        address from=_ownerOf(id);\n        // Every real transfer is validated, including owner calls and both\n        // safeTransferFrom overloads. Only mint and burn bypass sale validation.\n        bool custody=msg.sender==royaltyStaking&&(from==royaltyStaking||to==royaltyStaking);\n        if(from!=address(0)&&to!=address(0)&&!custody)\n            IQuacksTransferValidator(transferValidator).validateTransfer(msg.sender,from,to,id);\n        return super._update(to,id,auth);\n    }\n    function supportsInterface(bytes4 id) public view override returns(bool){\n        return id==type(IQuacksCreatorToken).interfaceId||super.supportsInterface(id);\n    }\n}\n"},"dice-integration/UserFeeFixtures.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\n// Local payment tests only; never used as production renderer or wallet.\ncontract FeeTestRenderer {\n    function tokenURI(uint256,bool,uint8,uint256) external pure returns(string memory){return \"test-only\";}\n    function burnedTokenURI(uint256,uint256) external pure returns(string memory){return \"burned-test-only\";}\n}\ncontract RejectFeeRefund { receive() external payable {revert();} }\n"},"roster-repair/GenesisRosterDraw.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.28;\r\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport {MerkleProof} from \"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol\";\r\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\nimport {EIP712} from \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\r\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\r\ninterface IGenesisQuacks {function mintGenesis(address to,uint256 id,uint256 seed) external;function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256);function artworkOf(uint256 id) external view returns(uint256);function ownerOf(uint256 id) external view returns(address);function releaseGenesisPrize(address to,uint256 id) external;}\ninterface IDrawEntropy {function requestWithContribution(uint256 roundId,bytes32 contribution) external returns(uint256);function cancel(uint256 requestId) external;}\r\n\r\n/// @notice Phased whitelist/public draws with frozen eligibility and asynchronous entropy.\r\ncontract GenesisRosterDraw is ReentrancyGuard,EIP712,Ownable {\r\n    uint256 public constant INTERVAL=30 minutes;\r\n    uint256 public constant CLAIM_WINDOW=24 hours;\r\n    bytes32 public eligibilityRoot;\r\n    bytes32 public publicEligibilityRoot;\r\n    uint256 public whitelistWinLimit;\r\n    uint256 public whitelistWins;\r\n    uint256[2] public rosterExpected;\r\n    uint256[2] public rosterImported;\r\n    bool public automaticRosterConfigured;\r\n    uint256 public constant MAX_ROSTER_BATCH=100;\r\n    event RosterConfigured(uint256 whitelistWallets,uint256 communityWallets);\r\n    event RosterImported(uint256 indexed stage,uint256 imported,uint256 expected);\r\n\r\n    /// @notice Counts and eligibilityRoot are frozen before anyone can import.\r\n    function configureAutomaticRoster(uint256 whitelistWallets,uint256 communityWallets) external onlyOwner {\r\n        require(!configurationFrozen&&stagedEligibility,\"Configure stages first\");\r\n        require(whitelistWallets>=communityWinLimit&&communityWallets>0,\"Insufficient roster\");\r\n        require(whitelistWallets+communityWallets>=whitelistWinLimit,\"Insufficient combined roster\");\r\n        rosterExpected=[whitelistWallets,communityWallets];automaticRosterConfigured=true;\r\n        emit RosterConfigured(whitelistWallets,communityWallets);\r\n    }\r\n    function activeRosterReady() public view returns(bool) {\r\n        if(!automaticRosterConfigured||rosterImported[0]!=rosterExpected[0])return false;\r\n        return registrationStage()==0||rosterImported[1]==rosterExpected[1];\r\n    }\r\n    /// @notice Anyone can relay the committed roster; listed wallets never sign or register.\r\n    /// Retries are idempotent. Community wallets cannot enter before the first 111 awards.\r\n    function importRosterBatch(uint256 stage,address[] calldata wallets,bytes32[][] calldata proofs) external {\n        require(wallets.length>0&&wallets.length<=MAX_ROSTER_BATCH&&wallets.length==proofs.length,\"Invalid batch\");\r\n        for(uint256 i;i<wallets.length;i++)_importRosterWallet(stage,wallets[i],proofs[i]);\r\n        emit RosterImported(stage,rosterImported[stage],rosterExpected[stage]);\n    }\n    function rosterRegistered(address[] calldata wallets) external view returns(bool[] memory flags) {\n        require(wallets.length<=MAX_ROSTER_BATCH,\"Invalid batch\");\n        flags=new bool[](wallets.length);\n        for(uint256 i;i<wallets.length;i++)flags[i]=registered[wallets[i]];\n    }\n    function _importRosterWallet(uint256 stage,address wallet,bytes32[] calldata proof) internal {\r\n        require(configurationFrozen&&automaticRosterConfigured&&stage<2&&stage<=registrationStage(),\"Roster stage not open\");\r\n        require(wallet!=address(0)&&proof.length<=32,\"Invalid roster wallet\");\r\n        bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(wallet,stage))));\r\n        require(MerkleProof.verifyCalldata(proof,eligibilityRoot,leaf),\"Not in approved roster\");\r\n        if(registered[wallet])return;\r\n        require(rosterImported[stage]<rosterExpected[stage],\"Roster full\");\r\n        rosterImported[stage]++;registered[wallet]=true;entrants.push(wallet);emit Registered(wallet);\r\n    }\r\n\r\n    bool public stagedEligibility;\r\n    uint256 public communityWinLimit;\r\n    uint256 public regularWhitelistWinLimit;\r\n    event StagesConfigured(uint256 communityWins,uint256 regularWins);\r\n    event RegistrationStageOpened(uint256 stage);\r\n    event WhitelistConfigured(uint256 wins,bytes32 whitelistRoot,bytes32 publicRoot);\r\n    event PublicRegistrationOpened(uint256 whitelistWins);\r\n    event EmptyRoundRestarted(uint256 nextDrawAt);\r\n    bool public configurationFrozen;bool public paused=true;bool public oneWinPerWallet=true;\n    uint256 public claimedCount;uint256 public pendingClaimCount;\r\n    event ConfigurationFrozen();event PauseChanged(bool paused);\r\n    address public immutable eligibilitySigner;\r\n    bytes32 public constant ENTRY_TYPEHASH=keccak256(\"Entry(address wallet,uint256 deadline)\");\r\n    IGenesisQuacks public immutable quacks;\r\n    IDrawEntropy public immutable entropy;\r\n    uint256 public nextDrawAt;\r\n    uint256 public rounds;\r\n    uint256 public pendingRequest;\r\n    uint256 public snapshotSize;\r\n    uint256 public selectedToken;\n    uint256 public currentPrize;\n    uint256 public preparations;\n    // 0=none, 1=prize artwork, 2=winner. Independent oracle requests.\n    uint8 public pendingKind;\n    event PrizeRequested(uint256 indexed tokenId,uint256 indexed requestId);\n    event PrizeReady(uint256 indexed tokenId,uint256 artwork,uint256 nextDrawAt);\n    mapping(uint256=>bool) public usedRequest;\r\n    address[] public entrants;\r\n    uint256[] public pool;\r\n    mapping(address=>bool) public registered;\r\n    mapping(address=>uint256) public pendingAward;\r\n    mapping(address=>bool) public hasClaimed;\r\n    struct Award {address winner;uint64 deadline;uint256 seed;bool claimed;}\r\n    mapping(uint256=>Award) public awards;\r\n    event Registered(address indexed guest);\r\n    event DrawRequested(uint256 indexed round,uint256 indexed requestId,uint256 indexed tokenId,uint256 entrants);\r\n    event Awarded(uint256 indexed tokenId,address indexed winner,uint256 deadline);\r\n    event Returned(uint256 indexed tokenId);\r\n    event Claimed(uint256 indexed tokenId,address indexed winner);\r\n    constructor(address nft,address rng,bytes32 root,uint256 startAt,address signer) EIP712(\"Quacks Genesis\",\"2\") Ownable(msg.sender){\r\n        require(nft.code.length>0 && rng.code.length>0 && (root!=bytes32(0) || signer!=address(0)) && startAt>0,\"Invalid setup\");\n        quacks=IGenesisQuacks(nft);entropy=IDrawEntropy(rng);eligibilityRoot=root;eligibilitySigner=signer;\n        for(uint256 i=333;i>0;i--)pool.push(i);\r\n    }\r\n    function register(bytes32[] calldata proof) external {\r\n        require(!stagedEligibility,\"Use staged proof\");\r\n        bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\r\n        require(eligibilityRoot!=bytes32(0)&&MerkleProof.verifyCalldata(proof,eligibilityRoot,leaf),\"Not eligible\");_register();\r\n    }\r\n    function registrationStage() public view returns(uint256){\r\n        if(publicRegistrationOpen())return 2;\r\n        return stagedEligibility&&whitelistWins<communityWinLimit?0:1;\r\n    }\r\n    function configureStages(uint256 communityWins,uint256 regularWins) external onlyOwner {\r\n        require(!configurationFrozen,\"Frozen\");\r\n        require(communityWins>0&&regularWins>0&&communityWins+regularWins<333,\"Invalid stage allocations\");\r\n        require(eligibilityRoot!=bytes32(0)&&eligibilitySigner!=address(0),\"Missing staged eligibility\");\r\n        stagedEligibility=true;communityWinLimit=communityWins;regularWhitelistWinLimit=regularWins;\r\n        whitelistWinLimit=communityWins+regularWins;publicEligibilityRoot=bytes32(0);\r\n        emit StagesConfigured(communityWins,regularWins);\r\n    }\r\n    function registerStage(uint256 stage,bytes32[] calldata proof) external {\r\n        _importRosterWallet(stage,msg.sender,proof);\r\n    }\r\n    function publicRegistrationOpen() public view returns(bool){return whitelistWins>=whitelistWinLimit;}\r\n    /// @notice Zero public root and signer means permissionless public registration.\r\n    function registerPublic(bytes32[] calldata proof) external {\r\n        require(publicRegistrationOpen(),\"Whitelist phase\");\r\n        if(publicEligibilityRoot!=bytes32(0)){\r\n            bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\r\n            require(MerkleProof.verifyCalldata(proof,publicEligibilityRoot,leaf),\"Not eligible\");\r\n        }else require(eligibilitySigner==address(0),\"Public ticket required\");\r\n        _register();\r\n    }\r\n    function registerWithTicket(uint256 deadline,bytes calldata signature) external {\r\n        require(publicRegistrationOpen(),\"Whitelist phase\");\r\n        require(!registered[msg.sender] && eligibilitySigner!=address(0) && block.timestamp<=deadline,\"Entry unavailable\");\r\n        bytes32 digest=_hashTypedDataV4(keccak256(abi.encode(ENTRY_TYPEHASH,msg.sender,deadline)));\r\n        require(ECDSA.recover(digest,signature)==eligibilitySigner,\"Not eligible\");_register();\r\n    }\r\n    function _register() internal {\r\n        require(publicRegistrationOpen(),\"Public phase only\");\r\n        require(configurationFrozen&&!paused,\"Entry paused or not frozen\");\r\n        require(!registered[msg.sender],\"Already registered\");\r\n        require(pool.length>0||currentPrize!=0||pendingRequest!=0||pendingClaimCount>0,\"Genesis complete\");\n        registered[msg.sender]=true;entrants.push(msg.sender);emit Registered(msg.sender);\r\n    }\r\n    function configureWhitelist(uint256 wins,bytes32 publicRoot) external onlyOwner {\r\n        require(!stagedEligibility,\"Use stage allocations\");\r\n        require(!configurationFrozen,\"Frozen\");require(wins<=333&&(wins==0||eligibilityRoot!=bytes32(0)),\"Invalid whitelist\");\r\n        whitelistWinLimit=wins;publicEligibilityRoot=publicRoot;emit WhitelistConfigured(wins,eligibilityRoot,publicRoot);\r\n    }\r\n    function configureEligibility(bytes32 root,bool singleWin) external onlyOwner {require(!configurationFrozen,\"Frozen\");require(root!=bytes32(0)||eligibilitySigner!=address(0),\"No eligibility\");eligibilityRoot=root;oneWinPerWallet=singleWin;}\r\n    function freezeEconomicConfiguration() external onlyOwner {require(!configurationFrozen,\"Frozen\");require(stagedEligibility&&automaticRosterConfigured,\"Automatic roster required\");require(rosterExpected[0]>=communityWinLimit&&rosterExpected[0]+rosterExpected[1]>=whitelistWinLimit,\"Insufficient roster\");require(whitelistWinLimit==0||eligibilityRoot!=bytes32(0),\"No whitelist root\");configurationFrozen=true;emit ConfigurationFrozen();}\r\n    function setPaused(bool value) external onlyOwner {paused=value;emit PauseChanged(value);}\r\n    function entrantCount() external view returns(uint256){return entrants.length;}\r\n    function poolCount() external view returns(uint256){return pool.length;}\n    function prepareNextPrize(bytes32 contribution) external nonReentrant {\n        require(configurationFrozen&&!paused&&activeRosterReady()&&pendingRequest==0&&currentPrize==0&&pool.length>0&&entrants.length>0,\"Prize unavailable\");\n        uint256 token=pool[pool.length-1];pool.pop();\n        if(quacks.artworkOf(token)!=0){\n            require(quacks.ownerOf(token)==address(this),\"Prize custody missing\");\n            currentPrize=token;nextDrawAt=block.timestamp+INTERVAL;\n            emit PrizeReady(token,quacks.artworkOf(token),nextDrawAt);return;\n        }\n        selectedToken=token;pendingKind=1;preparations++;\n        uint256 requestId=entropy.requestWithContribution(preparations,contribution);\n        require(requestId>0&&!usedRequest[requestId],\"Bad request\");usedRequest[requestId]=true;pendingRequest=requestId;\n        emit PrizeRequested(token,requestId);\n    }\n    function onERC721Received(address operator,address from,uint256 token,bytes calldata) external view returns(bytes4){\n        require(msg.sender==address(quacks)&&operator==address(this)&&from==address(0)&&token==selectedToken,\"Unexpected NFT\");\n        return this.onERC721Received.selector;\n    }\n    function requestDraw(bytes32 contribution) external nonReentrant {\n        require(activeRosterReady(),\"Current phase roster incomplete\");\n        require(configurationFrozen&&!paused&&currentPrize!=0&&block.timestamp>=nextDrawAt&&pendingRequest==0&&entrants.length>0,\"Draw unavailable\");\n        selectedToken=currentPrize;snapshotSize=entrants.length;rounds++;pendingKind=2;\n        uint256 requestId=entropy.requestWithContribution(rounds,contribution);require(requestId>0 && !usedRequest[requestId],\"Bad request\");usedRequest[requestId]=true;pendingRequest=requestId;\r\n        emit DrawRequested(rounds,requestId,selectedToken,snapshotSize);\r\n    }\r\n    function fulfillEntropy(uint256 requestId,uint256 seed) external nonReentrant {\n        require(msg.sender==address(entropy) && requestId==pendingRequest && requestId!=0,\"Invalid fulfillment\");\n        if(pendingKind==1){\n            uint256 token=selectedToken;uint256 artwork=quacks.reserveGenesisArtwork(token,seed);\n            quacks.mintGenesis(address(this),token,seed);\n            pendingRequest=0;selectedToken=0;pendingKind=0;currentPrize=token;nextDrawAt=block.timestamp+INTERVAL;\n            emit PrizeReady(token,artwork,nextDrawAt);return;\n        }\n        require(pendingKind==2,\"Invalid request kind\");\n        uint256 index=seed%snapshotSize;address winner=entrants[index];entrants[index]=entrants[entrants.length-1];entrants.pop();\n        uint256 token=selectedToken;pendingRequest=0;selectedToken=0;snapshotSize=0;pendingKind=0;currentPrize=0;nextDrawAt=0;\n        pendingAward[winner]=token;\n        pendingClaimCount++;awards[token]=Award(winner,uint64(block.timestamp+CLAIM_WINDOW),seed,false);emit Awarded(token,winner,block.timestamp+CLAIM_WINDOW);\r\n        if(whitelistWins<whitelistWinLimit){whitelistWins++;if(stagedEligibility&&whitelistWins==communityWinLimit)emit RegistrationStageOpened(1);if(whitelistWins==whitelistWinLimit)emit PublicRegistrationOpened(whitelistWins);}\r\n    }\r\n    function claim(uint256 token) external nonReentrant {\r\n        Award storage award=awards[token];require(award.winner==msg.sender && !award.claimed && block.timestamp<award.deadline,\"Claim unavailable\");\r\n        claimedCount++;pendingClaimCount--;award.claimed=true;pendingAward[msg.sender]=0;hasClaimed[msg.sender]=true;quacks.releaseGenesisPrize(msg.sender,token);if(!oneWinPerWallet)entrants.push(msg.sender);emit Claimed(token,msg.sender);\n    }\n    function recoverStalledDraw() external nonReentrant {require(pendingRequest!=0,\"No request\");entropy.cancel(pendingRequest);if(pendingKind==1){pool.push(selectedToken);nextDrawAt=0;}pendingRequest=0;selectedToken=0;snapshotSize=0;pendingKind=0;}\n    function recycle(uint256 token) external {\r\n        Award memory award=awards[token];require(award.winner!=address(0) && !award.claimed && block.timestamp>=award.deadline,\"Not expired\");\r\n        pendingClaimCount--;delete awards[token];pool.push(token);pendingAward[award.winner]=0;entrants.push(award.winner);emit Returned(token);\r\n    }\r\n}\r\n"},"roster-repair/RaffleQuacks.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.28;\r\nimport {QuacksDice} from \"../dice-integration/QuacksDice.sol\";\r\n\r\ninterface IQuacksTransferValidator {\r\n    function validateTransfer(address caller,address from,address to,uint256 tokenId) external view;\r\n}\r\ninterface IQuacksRoyaltyStaking {function quacks() external view returns(address);function bread() external view returns(address);}\r\ninterface IQuacksCreatorToken {\r\n    event TransferValidatorUpdated(address oldValidator,address newValidator);\r\n    function getTransferValidator() external view returns(address);\r\n    function getTransferValidationFunction() external view returns(bytes4,bool);\r\n    function setTransferValidator(address validator) external;\r\n}\r\n\r\n/// Creator-token hook documented by OpenSea. The production validator and its\r\n/// marketplace authorization policy MUST be verified on the deployment chain.\r\n/// ERC-2981 alone reports 5%; the validator authorizes royalty-compliant sales.\r\ncontract RaffleQuacks is QuacksDice,IQuacksCreatorToken {\r\n    uint96 public constant ROYALTY_BPS=500;\r\n    address private transferValidator;\r\n    address public royaltyStaking;\r\n    event RoyaltyStakingConfigured(address indexed staking);\r\n    event RoyaltyPolicyFrozen(address indexed validator,address indexed receiver,uint96 bps);\r\n    constructor(address token,address config,address generator,uint256 timeout)\r\n        QuacksDice(token,config,generator,timeout) {}\r\n\r\n    function getTransferValidator() external view returns(address){return transferValidator;}\r\n    function getTransferValidationFunction() external pure returns(bytes4,bool){\r\n        return (IQuacksTransferValidator.validateTransfer.selector,true);\r\n    }\r\n    function setTransferValidator(address validator) external onlyOwner {\r\n        if(rendererFrozen||validator.code.length==0||validator==address(this))revert InvalidConfiguration();\r\n        emit TransferValidatorUpdated(transferValidator,validator);transferValidator=validator;\r\n    }\r\n    /// Fixed custody exception: only the bound staking contract can move tokens\r\n    /// into or out of its own custody. It cannot authorize marketplace transfers.\r\n    function setRoyaltyStaking(address staking) external onlyOwner {\r\n        if(rendererFrozen||royaltyStaking!=address(0)||staking.code.length==0)revert InvalidConfiguration();\r\n        if(IQuacksRoyaltyStaking(staking).quacks()!=address(this)||IQuacksRoyaltyStaking(staking).bread()!=address(bread))revert InvalidConfiguration();\r\n        royaltyStaking=staking;emit RoyaltyStakingConfigured(staking);\r\n    }\r\n    function freezeRenderer() public override onlyOwner {\r\n        if(transferValidator.code.length==0)revert InvalidConfiguration();\r\n        super.freezeRenderer();\r\n        emit RoyaltyPolicyFrozen(transferValidator,economics.treasury(),ROYALTY_BPS);\r\n    }\r\n    function _update(address to,uint256 id,address auth) internal override returns(address){\r\n        if(!rendererFrozen||transferValidator.code.length==0)revert InvalidConfiguration();\r\n        address from=_ownerOf(id);\r\n        // Every real transfer is validated, including owner calls and both\r\n        // safeTransferFrom overloads. Only mint and burn bypass sale validation.\r\n        bool custody=(msg.sender==royaltyStaking&&(from==royaltyStaking||to==royaltyStaking))||(msg.sender==draw&&from==draw&&isGenesis(id));\r\n        if(from!=address(0)&&to!=address(0)&&!custody)\r\n            IQuacksTransferValidator(transferValidator).validateTransfer(msg.sender,from,to,id);\r\n        return super._update(to,id,auth);\r\n    }\r\n    /// Only the bound raffle can release its own pre-minted Genesis prize.\r\n    function releaseGenesisPrize(address to,uint256 id) external nonReentrant {\r\n        if(msg.sender!=draw||ownerOf(id)!=draw||!isGenesis(id)||!revealed[id]||to==address(0)||to==draw)revert Unauthorized();\r\n        _safeTransfer(draw,to,id,\"\");\r\n    }\r\n    function supportsInterface(bytes4 id) public view override returns(bool){\r\n        return id==type(IQuacksCreatorToken).interfaceId||super.supportsInterface(id);\r\n    }\r\n}\r\n"},"roster-repair/WithdrawableDiceEntropy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {DiceRecoveryEntropy} from \"../dice-integration/DiceRecoveryEntropy.sol\";\ninterface IRaffleNFT {function draw() external view returns(address);}\ninterface IPausableRaffle {function paused() external view returns(bool);}\n\n/// Unused sponsored funds remain owner-recoverable; user refund credits are protected.\ncontract WithdrawableDiceEntropy is DiceRecoveryEntropy {\n    event ReserveWithdrawn(address indexed recipient,uint256 amount);\n    constructor(address coordinator_,address provider_,uint256 timeout_,uint256 ceiling_)\n        DiceRecoveryEntropy(coordinator_,provider_,timeout_,ceiling_) {}\n    function availableReserve() public view returns(uint256){return address(this).balance-totalFeeRefunds;}\n    function withdrawReserve(address payable recipient,uint256 amount) external onlyOwner nonReentrant {\n        if(recipient==address(0)||recipient==address(this)||amount==0||amount>availableReserve())revert Unavailable();\n        if(frozen&&!IPausableRaffle(IRaffleNFT(paidConsumer).draw()).paused())revert Unavailable();\n        (bool success,)=recipient.call{value:amount}(\"\");if(!success)revert Unavailable();\n        emit ReserveWithdrawn(recipient,amount);\n    }\n}\n"},"src/ArtBlob.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\n/// @notice Immutable bytecode storage. STOP prefix makes this data non-executable.\ncontract ArtBlob {\n    constructor(bytes memory data){require(data.length>0 && data.length<=24000,\"Blob size\");bytes memory runtime=bytes.concat(hex\"00\",data);assembly{return(add(runtime,32),mload(runtime))}}\n}\n"},"src/BreadPond.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\ninterface IStakeableQuacks is IERC721 {function revealed(uint256 id) external view returns(bool);}\n\n/// @notice No owner minting: all BREAD is earned by custodial staking.\ncontract BreadPond is ERC20, ERC20Burnable, ReentrancyGuard {\n    IStakeableQuacks public immutable quacks;\n    uint256 public constant DAILY_REWARD = 1 ether;\n    struct Deposit {address owner; uint64 since;}\n    mapping(uint256 => Deposit) public deposits;\n    event Staked(address indexed owner,uint256 indexed id);\n    event Unstaked(address indexed owner,uint256 indexed id);\n    constructor(address collection) ERC20(\"Quacks Bread\",\"BREAD\") {require(collection!=address(0));quacks=IStakeableQuacks(collection);}\n    function stake(uint256[] calldata ids) external nonReentrant {\n        require(ids.length>0 && ids.length<=25,\"Batch size\");\n        for(uint256 i;i<ids.length;i++){\n            uint256 id=ids[i];require(quacks.ownerOf(id)==msg.sender && quacks.revealed(id),\"Not a revealed owned Quack\");\n            require(deposits[id].owner==address(0),\"Already staked\");\n            deposits[id]=Deposit(msg.sender,uint64(block.timestamp));\n            quacks.transferFrom(msg.sender,address(this),id);emit Staked(msg.sender,id);\n        }\n    }\n    function pending(uint256 id) public view returns(uint256){Deposit memory d=deposits[id];return d.owner==address(0)?0:(block.timestamp-d.since)*DAILY_REWARD/1 days;}\n    function claim(uint256[] calldata ids) external nonReentrant { _claim(ids,false); }\n    function unstake(uint256[] calldata ids) external nonReentrant { _claim(ids,true); }\n    function _claim(uint256[] calldata ids,bool exit) internal {\n        require(ids.length>0 && ids.length<=25,\"Batch size\");uint256 reward;\n        for(uint256 i;i<ids.length;i++){\n            uint256 id=ids[i];require(deposits[id].owner==msg.sender,\"Not depositor\");reward+=pending(id);\n            if(exit){delete deposits[id];quacks.safeTransferFrom(address(this),msg.sender,id);emit Unstaked(msg.sender,id);}\n            else deposits[id].since=uint64(block.timestamp);\n        }\n        if(reward>0)_mint(msg.sender,reward);\n    }\n}\n"},"src/GenesisDraw.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {MerkleProof} from \"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {EIP712} from \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\ninterface IGenesisQuacks {function mintGenesis(address to,uint256 id,uint256 seed) external;function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256);}\ninterface IDrawEntropy {function request(uint256 roundId) external returns(uint256);}\n\n/// @notice First-pass draw coordinator: fixed eligibility root, verifiable-provider boundary.\ncontract GenesisDraw is ReentrancyGuard,EIP712 {\n    uint256 public constant INTERVAL=30 minutes;\n    uint256 public constant CLAIM_WINDOW=24 hours;\n    bytes32 public immutable eligibilityRoot;\n    address public immutable eligibilitySigner;\n    bytes32 public constant ENTRY_TYPEHASH=keccak256(\"Entry(address wallet,uint256 deadline)\");\n    IGenesisQuacks public immutable quacks;\n    IDrawEntropy public immutable entropy;\n    uint256 public nextDrawAt;\n    uint256 public rounds;\n    uint256 public pendingRequest;\n    uint256 public snapshotSize;\n    uint256 public selectedToken;\n    mapping(uint256=>bool) public usedRequest;\n    address[] public entrants;\n    uint256[] public pool;\n    mapping(address=>bool) public registered;\n    mapping(address=>uint256) public pendingAward;\n    mapping(address=>bool) public hasClaimed;\n    struct Award {address winner;uint64 deadline;uint256 seed;bool claimed;}\n    mapping(uint256=>Award) public awards;\n    event Registered(address indexed guest);\n    event DrawRequested(uint256 indexed round,uint256 indexed requestId,uint256 indexed tokenId,uint256 entrants);\n    event Awarded(uint256 indexed tokenId,address indexed winner,uint256 deadline);\n    event Returned(uint256 indexed tokenId);\n    event Claimed(uint256 indexed tokenId,address indexed winner);\n    constructor(address nft,address rng,bytes32 root,uint256 startAt,address signer) EIP712(\"Quacks Genesis\",\"1\"){\n        require(nft.code.length>0 && rng.code.length>0 && (root!=bytes32(0) || signer!=address(0)) && startAt>block.timestamp,\"Invalid setup\");\n        quacks=IGenesisQuacks(nft);entropy=IDrawEntropy(rng);eligibilityRoot=root;eligibilitySigner=signer;nextDrawAt=startAt;\n        for(uint256 i=333;i>0;i--)pool.push(i);\n    }\n    function register(bytes32[] calldata proof) external {\n        require(!registered[msg.sender],\"Already registered\");\n        bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\n        require(MerkleProof.verifyCalldata(proof,eligibilityRoot,leaf),\"Not eligible\");registered[msg.sender]=true;entrants.push(msg.sender);emit Registered(msg.sender);\n    }\n    function registerWithTicket(uint256 deadline,bytes calldata signature) external {\n        require(!registered[msg.sender] && eligibilitySigner!=address(0) && block.timestamp<=deadline,\"Entry unavailable\");\n        bytes32 digest=_hashTypedDataV4(keccak256(abi.encode(ENTRY_TYPEHASH,msg.sender,deadline)));\n        require(ECDSA.recover(digest,signature)==eligibilitySigner,\"Not eligible\");registered[msg.sender]=true;entrants.push(msg.sender);emit Registered(msg.sender);\n    }\n    function entrantCount() external view returns(uint256){return entrants.length;}\n    function poolCount() external view returns(uint256){return pool.length;}\n    function requestDraw() external nonReentrant {\n        require(block.timestamp>=nextDrawAt && pendingRequest==0 && entrants.length>0 && pool.length>0,\"Draw unavailable\");\n        selectedToken=pool[pool.length-1];pool.pop();snapshotSize=entrants.length;rounds++;nextDrawAt=block.timestamp+INTERVAL;\n        uint256 requestId=entropy.request(rounds);require(requestId>0 && !usedRequest[requestId],\"Bad request\");usedRequest[requestId]=true;pendingRequest=requestId;\n        emit DrawRequested(rounds,requestId,selectedToken,snapshotSize);\n    }\n    function fulfillEntropy(uint256 requestId,uint256 seed) external nonReentrant {\n        require(msg.sender==address(entropy) && requestId==pendingRequest && requestId!=0,\"Invalid fulfillment\");\n        uint256 index=seed%snapshotSize;address winner=entrants[index];entrants[index]=entrants[entrants.length-1];entrants.pop();\n        uint256 token=selectedToken;pendingRequest=0;selectedToken=0;snapshotSize=0;\n        quacks.reserveGenesisArtwork(token,seed);pendingAward[winner]=token;\n        awards[token]=Award(winner,uint64(block.timestamp+CLAIM_WINDOW),seed,false);emit Awarded(token,winner,block.timestamp+CLAIM_WINDOW);\n    }\n    function claim(uint256 token) external nonReentrant {\n        Award storage award=awards[token];require(award.winner==msg.sender && !award.claimed && block.timestamp<award.deadline,\"Claim unavailable\");\n        award.claimed=true;pendingAward[msg.sender]=0;hasClaimed[msg.sender]=true;quacks.mintGenesis(msg.sender,token,award.seed);emit Claimed(token,msg.sender);\n    }\n    function recycle(uint256 token) external {\n        Award memory award=awards[token];require(award.winner!=address(0) && !award.claimed && block.timestamp>=award.deadline,\"Not expired\");\n        delete awards[token];pool.push(token);pendingAward[award.winner]=0;entrants.push(award.winner);emit Returned(token);\n    }\n}\n"},"src/QuacksCore.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {ERC721} from \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\ninterface IBread {function burnFrom(address from,uint256 amount) external;}\ninterface IQuacksEntropy {function request(uint256 tokenId) external returns(uint256 requestId);}\ninterface IQuacksRenderer {\n    function tokenURI(uint256 id,bool hatched,uint8 stage,uint256 seed) external view returns(string memory);\n    function burnedTokenURI(uint256 id,uint256 artwork) external view returns(string memory);\n}\n\n/// @notice Development core. Requires audited entropy and final immutable renderer before launch.\ncontract QuacksCore is ERC721, Ownable, ReentrancyGuard {\n    uint256 public constant MAX_SUPPLY=3333;\n    uint256 public constant GENESIS_SUPPLY=333;\n    uint256 public constant INCUBATION=7 days;\n    uint256 public expansionMinted;\n    uint256 public genesisMinted;\n    uint256 public burned;\n    uint256 public remainingArt=3333;\n    mapping(uint256=>uint256) private artSwaps;\n    mapping(uint256=>uint256) public artworkOf;\n    bool public configured;\n    address public draw;\n    IBread public bread;\n    IQuacksEntropy public entropy;\n    IQuacksRenderer public renderer;\n    struct Egg {uint64 readyAt; bool hasSeed; uint256 seed;}\n    mapping(uint256=>Egg) public eggs;\n    mapping(uint256=>bool) public revealed;\n    mapping(uint256=>uint256) public requestToken;\n    mapping(uint256=>bool) public entropyRequested;\n    mapping(uint256=>bool) public usedRequest;\n    mapping(uint256=>bool) public wasBurned;\n    mapping(uint256=>address) public burnedBy;\n    mapping(uint256=>uint256) public replacementOf;\n    event MetadataUpdate(uint256 tokenId);\n    event EggMinted(uint256 indexed tokenId,address indexed owner,uint256 readyAt);\n    event Sacrificed(uint256 indexed burnedId,uint256 indexed replacementId);\n    constructor() ERC721(\"Quacks\",\"QUACKS\") Ownable(msg.sender) {}\n    /// @dev Wiring is one-time; owner cannot change economics, renderer or provider afterward.\n    function configure(address token,address draws,address rng,address art) external onlyOwner {\n        require(!configured && token.code.length>0 && draws.code.length>0 && rng.code.length>0 && art.code.length>0,\"Invalid configuration\");\n        bread=IBread(token);draw=draws;entropy=IQuacksEntropy(rng);renderer=IQuacksRenderer(art);configured=true;\n    }\n    function currentBreadCost() public view returns(uint256){require(expansionMinted<3000,\"Sold out\");return (1+expansionMinted/750)*1 ether;}\n    function mintGenesis(address to,uint256 id,uint256 seed) external nonReentrant {\n        require(configured && msg.sender==draw && id>0 && id<=333 && _ownerOf(id)==address(0),\"Invalid Genesis mint\");\n        // The draw keeps a permanent claimed flag; burned IDs are never reissued.\n        require(!revealed[id] && artworkOf[id]!=0,\"Already issued or unreserved\");genesisMinted++;revealed[id]=true;eggs[id]=Egg(0,true,seed);_safeMint(to,id);\n    }\n    function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256){require(configured && msg.sender==draw && id>0 && id<=333,\"Only draw\");if(artworkOf[id]==0)_assignArt(id,seed);return artworkOf[id];}\n    function _assignArt(uint256 id,uint256 seed) internal {\n        require(remainingArt>0 && artworkOf[id]==0,\"No artwork\");uint256 index=uint256(keccak256(abi.encode(seed,id)))%remainingArt;\n        artworkOf[id]=artSwaps[index]==0?index+1:artSwaps[index];uint256 last=remainingArt-1;artSwaps[index]=artSwaps[last]==0?last+1:artSwaps[last];delete artSwaps[last];remainingArt=last;\n    }\n    function mintEgg(uint256 maxCost) external nonReentrant returns(uint256 id){\n        require(configured,\"Not configured\");uint256 cost=currentBreadCost();require(cost<=maxCost,\"Price changed\");\n        bread.burnFrom(msg.sender,cost);return _expansion(msg.sender,true);\n    }\n    function burnForMint(uint256 id) external nonReentrant returns(uint256 replacement){\n        require(configured && ownerOf(id)==msg.sender && revealed[id],\"Not a revealed owned Quack\");\n        require(expansionMinted<3000,\"Sold out\");\n        wasBurned[id]=true;burnedBy[id]=msg.sender;\n        _burn(id);burned++;replacement=_expansion(msg.sender,false);replacementOf[id]=replacement;\n        emit Sacrificed(id,replacement);emit MetadataUpdate(id);\n    }\n    function _expansion(address to,bool incubate) internal returns(uint256 id){\n        require(expansionMinted<3000,\"Sold out\");id=334+expansionMinted++;uint64 ready=uint64(block.timestamp+(incubate?INCUBATION:0));eggs[id]=Egg(ready,false,0);\n        if(!incubate)_requestEntropy(id);\n        _safeMint(to,id);emit EggMinted(id,to,ready);\n    }\n    function _requestEntropy(uint256 id) internal {\n        require(!entropyRequested[id],\"Already requested\");entropyRequested[id]=true;\n        uint256 requestId=entropy.request(id);require(requestId!=0 && !usedRequest[requestId],\"Bad request\");usedRequest[requestId]=true;requestToken[requestId]=id;\n    }\n    function fulfillEntropy(uint256 requestId,uint256 seed) external {\n        require(msg.sender==address(entropy),\"Only entropy\");uint256 id=requestToken[requestId];require(id!=0,\"Unknown request\");delete requestToken[requestId];_assignArt(id,seed);eggs[id].seed=seed;eggs[id].hasSeed=true;revealed[id]=true;\n        emit MetadataUpdate(id);\n    }\n    function hatch(uint256 id) external nonReentrant {\n        require(ownerOf(id)==msg.sender && !revealed[id],\"Not a hatchable owned egg\");require(block.timestamp>=eggs[id].readyAt,\"Not ready\");_requestEntropy(id);\n    }\n    function stage(uint256 id) public view returns(uint8){\n        _requireOwned(id);uint256 ready=eggs[id].readyAt;if(ready==0 || block.timestamp>=ready)return 7;\n        uint256 remaining=ready-block.timestamp;return remaining>=INCUBATION?0:uint8((INCUBATION-remaining)/1 days);\n    }\n    function tokenURI(uint256 id) public view override returns(string memory){\n        // Preserve a burned token's historical artwork without restoring ownership.\n        if(wasBurned[id])return renderer.burnedTokenURI(id,artworkOf[id]);\n        _requireOwned(id);return renderer.tokenURI(id,revealed[id],stage(id),revealed[id]?artworkOf[id]:0);\n    }\n    function totalIssued() external view returns(uint256){return genesisMinted+expansionMinted;}\n    function totalSupply() external view returns(uint256){return genesisMinted+expansionMinted-burned;}\n    function supportsInterface(bytes4 id) public view override returns(bool){return id==0x49064906 || super.supportsInterface(id);}\n}\n"},"src/QuacksLens.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {QuacksCore} from \"./QuacksCore.sol\";\nimport {BreadPond} from \"./BreadPond.sol\";\nimport {GenesisDraw} from \"./GenesisDraw.sol\";\n/// @notice Bounded read batches for the website and keeper. No custody or admin powers.\ncontract QuacksLens {\n    function poolPage(GenesisDraw draw,uint256 start,uint256 count) external view returns(uint256[] memory result){require(count<=64 && start+count<=draw.poolCount(),\"Page bounds\");result=new uint256[](count);for(uint256 i;i<count;i++)result[i]=draw.pool(start+i);}\n    struct AwardView {uint256 id;address winner;uint64 deadline;bool claimed;uint256 artwork;}\n    function awardsPage(GenesisDraw draw,QuacksCore quacks,uint256 start,uint256 count) external view returns(AwardView[] memory result){\n        require(start>=1 && start<=333 && count<=64 && start+count<=334,\"Page bounds\");result=new AwardView[](count);\n        for(uint256 i;i<count;i++){uint256 id=start+i;(address winner,uint64 deadline,,bool claimed)=draw.awards(id);result[i]=AwardView(id,winner,deadline,claimed,quacks.artworkOf(id));}\n    }\n    struct WalletToken {uint256 id;bool staked;bool revealed;uint8 stage;uint256 reward;uint256 artwork;}\n    function walletPage(QuacksCore quacks,BreadPond bread,address wallet,uint256 start,uint256 count) external view returns(WalletToken[] memory result){\n        require(wallet!=address(0) && start>=1 && count<=128 && start+count<=3334,\"Page bounds\");result=new WalletToken[](count);\n        for(uint256 i;i<count;i++){uint256 id=start+i;bool owned;try quacks.ownerOf(id) returns(address owner){owned=owner==wallet;}catch{}(address depositor,)=bread.deposits(id);bool staked=depositor==wallet;\n            if(owned||staked)result[i]=WalletToken(id,staked,quacks.revealed(id),quacks.stage(id),bread.pending(id),quacks.artworkOf(id));\n        }\n    }\n}\n"},"src/QuacksRenderer.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Base64} from \"@openzeppelin/contracts/utils/Base64.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\n\n/// @notice Immutable native 32x32 PNG art, attributes and eight egg stages, entirely on-chain.\ncontract QuacksRenderer {\n    using Strings for uint256;\n    address[] public pages;\n    address public immutable indexBlob;\n    address public immutable traitsBlob;\n    address public immutable eggsBlob;\n    uint256 public immutable traitCount;\n    bytes32 public immutable manifestHash;\n    uint256 public constant ART_COUNT=3333;\n    constructor(address[] memory artPages,address index_,address traits_,address eggs_,uint256 traitsCount_,bytes32 hash_){\n        require(artPages.length>0 && artPages.length<256 && index_.code.length==16666 && traits_.code.length>1 && eggs_.code.length>1 && traitsCount_>0 && traitsCount_<256,\"Invalid art\");\n        for(uint256 i;i<artPages.length;i++)require(artPages[i].code.length>1 && artPages[i].code.length<=24001,\"Invalid page\");\n        pages=artPages;indexBlob=index_;traitsBlob=traits_;eggsBlob=eggs_;traitCount=traitsCount_;manifestHash=hash_;\n    }\n    function _read(address blob,uint256 offset,uint256 length) internal view returns(bytes memory data){require(offset+length+1<=blob.code.length,\"Art bounds\");data=new bytes(length);assembly{extcodecopy(blob,add(data,32),add(offset,1),length)}}\n    function _u16(bytes memory b,uint256 at) internal pure returns(uint256){return uint8(b[at])*256+uint8(b[at+1]);}\n    function record(uint256 artwork) public view returns(bytes memory){require(artwork>0 && artwork<=ART_COUNT,\"Art ID\");bytes memory pointer=_read(indexBlob,(artwork-1)*5,5);return _read(pages[uint8(pointer[0])],_u16(pointer,1),_u16(pointer,3));}\n    function _slice(bytes memory b,uint256 start,uint256 length) internal pure returns(bytes memory result){require(start+length<=b.length,\"Slice\");result=new bytes(length);for(uint256 i;i<length;i++)result[i]=b[start+i];}\n    function _trait(uint256 id) internal view returns(bytes memory){require(id<traitCount,\"Trait ID\");bytes memory p=_read(traitsBlob,id*4,4);return _read(traitsBlob,traitCount*4+_u16(p,0),_u16(p,2));}\n    /// @notice Original on-chain PNG with a native-grid flame, retained after ERC-721 destruction.\n    function burnedTokenURI(uint256 id,uint256 artwork) external view returns(string memory){\n        bytes memory data=record(artwork);uint256 pngLength=_u16(data,0);\n        bytes memory svg=abi.encodePacked(\n            '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" shape-rendering=\"crispEdges\">',\n            '<image width=\"32\" height=\"32\" style=\"image-rendering:pixelated\" href=\"data:image/png;base64,',Base64.encode(_slice(data,2,pngLength)),'\"/>',\n            '<g id=\"burned-icon\"><path fill=\"#ff3038\" d=\"M1 31V25h1v-2h1v2h1v-1h1v2h1v5zM1 22h1v1H1zM3 21h1v1H3zM4 22h1v1H4z\"/>',\n            '<path fill=\"#ff941f\" d=\"M2 31v-4h1v-1h2v5z\"/><path fill=\"#ffdc2c\" d=\"M3 31v-3h1v-1h1v4z\"/></g></svg>'\n        );\n        bytes memory attributes=bytes('[');\n        for(uint256 i=2+pngLength;i<data.length;i++)attributes=bytes.concat(attributes,i==2+pngLength?bytes(''):bytes(','),_trait(uint8(data[i])));\n        attributes=bytes.concat(attributes,data.length>2+pngLength?bytes(','):bytes(''),bytes('{\"trait_type\":\"Status\",\"value\":\"Burned\"}]'));\n        return string.concat('data:application/json;base64,',Base64.encode(abi.encodePacked(\n            '{\"name\":\"Quacks #',id.toString(),'\",\"description\":\"This Quack was permanently burned for a replacement. Its original artwork is preserved with a pixel flame. It cannot be owned, transferred or staked.\",\"image\":\"data:image/svg+xml;base64,',Base64.encode(svg),'\",\"attributes\":',attributes,'}'\n        )));\n    }\n    function tokenURI(uint256 id,bool hatched,uint8 day,uint256 artwork) external view returns(string memory){\n        bytes memory image;bytes memory attributes;string memory name;\n        if(hatched){\n            bytes memory data=record(artwork);uint256 pngLength=_u16(data,0);image=bytes.concat(bytes('data:image/png;base64,'),bytes(Base64.encode(_slice(data,2,pngLength))));\n            attributes=bytes('[');for(uint256 i=2+pngLength;i<data.length;i++)attributes=bytes.concat(attributes,i==2+pngLength?bytes(''):bytes(','),_trait(uint8(data[i])));attributes=bytes.concat(attributes,bytes(']'));name=string.concat('Quacks #',id.toString());\n        }else{\n            require(day<=7,\"Egg stage\");bytes memory p=_read(eggsBlob,uint256(day)*4,4);bytes memory svg=_read(eggsBlob,32+_u16(p,0),_u16(p,2));\n            image=bytes.concat(bytes('data:image/png;base64,'),bytes(Base64.encode(svg)));name=string.concat('Quacks Egg #',id.toString());\n            attributes=bytes(string.concat('[{\"trait_type\":\"Incubation day\",\"value\":',uint256(day).toString(),'}]'));\n        }\n        return string.concat('data:application/json;base64,',Base64.encode(abi.encodePacked('{\"name\":\"',name,'\",\"description\":\"Quacks. Small ducks. Big personalities.\",\"image\":\"',image,'\",\"attributes\":',attributes,'}')));\n    }\n}\n"},"src/QuiverEntropy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\ninterface IQuiverCoordinator {\n    function getFee(address provider) external view returns(uint128);\n    function requestWithCallback(address provider,bytes32 userRandomNumber) external payable returns(uint64);\n    function retryCallback(address provider,uint64 sequenceNumber) external;\n}\ninterface IEntropyReceiver {function fulfillEntropy(uint256 requestId,uint256 seed) external;}\n\n/// @notice Fixed Quiver integration with funded fees and strict FIFO settlement.\n/// @dev Quiver push flow trusts provider liveness and secrecy; this is not Chainlink VRF.\ncontract QuiverEntropy is Ownable,ReentrancyGuard {\n    IQuiverCoordinator public immutable coordinator;\n    address public immutable provider;\n    uint256 public immutable maxFee;\n    bool public configured;\n    mapping(address=>bool) public consumers;\n    uint256 public requested;\n    uint256 public nextDelivery=1;\n    mapping(uint64=>uint256) public sequenceToRequest;\n    struct Request {address consumer;uint64 sequence;bool ready;bool delivered;uint256 seed;}\n    mapping(uint256=>Request) public requests;\n    event Requested(uint256 indexed requestId,address indexed consumer,uint256 context,uint64 sequence);\n    event Ready(uint256 indexed requestId);\n    event Delivered(uint256 indexed requestId);\n    constructor(address coordinator_,address provider_,uint256 feeCeiling) Ownable(msg.sender){require(coordinator_.code.length>0 && provider_!=address(0),\"Invalid coordinator\");coordinator=IQuiverCoordinator(coordinator_);provider=provider_;maxFee=feeCeiling;}\n    receive() external payable {}\n    function configureConsumers(address nft,address draw) external onlyOwner {require(!configured && nft.code.length>0 && draw.code.length>0,\"Invalid consumers\");configured=true;consumers[nft]=true;consumers[draw]=true;}\n    function request(uint256 context) external nonReentrant returns(uint256 id){\n        require(consumers[msg.sender],\"Unauthorized consumer\");uint256 fee=coordinator.getFee(provider);require(fee<=maxFee && address(this).balance>=fee,\"Fund randomness fees\");\n        id=++requested;\n        bytes32 contribution=keccak256(abi.encode(block.chainid,address(this),msg.sender,id,context,blockhash(block.number-1)));\n        uint64 sequence=coordinator.requestWithCallback{value:fee}(provider,contribution);require(sequenceToRequest[sequence]==0,\"Duplicate sequence\");\n        sequenceToRequest[sequence]=id;requests[id]=Request(msg.sender,sequence,false,false,0);emit Requested(id,msg.sender,context,sequence);\n    }\n    function quiverCallback(uint64 sequence,address provider_,bytes32 randomNumber) external {\n        require(msg.sender==address(coordinator) && provider_==provider,\"Unauthorized callback\");uint256 id=sequenceToRequest[sequence];require(id!=0,\"Unknown sequence\");Request storage r=requests[id];\n        if(r.ready)return;r.seed=uint256(randomNumber);r.ready=true;emit Ready(id);\n    }\n    /// @notice Delivery cannot be reordered to manipulate the remaining-art pool.\n    /// A failed consumer may retry this same immutable result; there is no re-request/skip.\n    function deliverNext() external nonReentrant {\n        uint256 id=nextDelivery;Request storage r=requests[id];require(r.ready && !r.delivered,\"Not ready\");r.delivered=true;nextDelivery=id+1;\n        IEntropyReceiver(r.consumer).fulfillEntropy(id,r.seed);emit Delivered(id);\n    }\n    function retryCoordinator(uint64 sequence) external {require(sequenceToRequest[sequence]!=0,\"Unknown sequence\");coordinator.retryCallback(provider,sequence);}\n}\n"},"v2/Bread.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/// @notice Standard transfers; no pool detection or transfer taxes.\ncontract Bread is ERC20,ERC20Burnable,Ownable {\n    address public staking;address public quacks;\n    uint256 public totalMinted;uint256 public totalBurned;\n    bool public frozen;bool public bootstrapUsed;\n    struct Receipt {address payer;uint128 amount;bool resolved;}\n    mapping(uint256=>Receipt) public hatchPayments;\n    event BootstrapMinted(address indexed receiver,uint256 amount);\n    event HatchPaymentBurned(uint256 indexed tokenId,address indexed payer,uint256 amount);\n    event HatchPaymentRefunded(uint256 indexed tokenId,address indexed receiver,uint256 amount);\n    error Unauthorized();error InvalidConfiguration();error InvalidPayment();\n    constructor() ERC20(\"Quacks Bread\",\"BREAD\") Ownable(msg.sender){}\n    function configure(address pond,address collection) external onlyOwner {\n        if(frozen||pond.code.length==0||collection.code.length==0) revert InvalidConfiguration();staking=pond;quacks=collection;\n    }\n    function bootstrap(address to,uint256 amount) external onlyOwner {\n        if(frozen||bootstrapUsed||to==address(0)) revert InvalidConfiguration();bootstrapUsed=true;_mint(to,amount);emit BootstrapMinted(to,amount);\n    }\n    function freezeEconomicConfiguration() external onlyOwner {\n        if(frozen||staking==address(0)||quacks==address(0)) revert InvalidConfiguration();frozen=true;\n    }\n    function mintRewards(address to,uint256 amount) external {if(msg.sender!=staking||!frozen) revert Unauthorized();_mint(to,amount);}\n    function payHatch(uint256 id,address payer,uint128 amount) external {\n        if(msg.sender!=quacks||!frozen) revert Unauthorized();\n        if(hatchPayments[id].payer!=address(0)||amount==0) revert InvalidPayment();\n        _spendAllowance(payer,msg.sender,amount);hatchPayments[id]=Receipt(payer,amount,false);_burn(payer,amount);emit HatchPaymentBurned(id,payer,amount);\n    }\n    function resolveHatchPayment(uint256 id,address refundTo) external {\n        if(msg.sender!=quacks) revert Unauthorized();Receipt storage r=hatchPayments[id];\n        if(r.payer==address(0)||r.resolved) revert InvalidPayment();r.resolved=true;\n        if(refundTo!=address(0)){_mint(refundTo,r.amount);emit HatchPaymentRefunded(id,refundTo,r.amount);}\n    }\n    function resolveHatchPaymentPartial(uint256 id,address refundTo,uint128 amount) external {\n        if(msg.sender!=quacks)revert Unauthorized();Receipt storage r=hatchPayments[id];\n        if(r.payer==address(0)||r.resolved||amount>r.amount||refundTo==address(0))revert InvalidPayment();\n        r.resolved=true;if(amount>0){_mint(refundTo,amount);emit HatchPaymentRefunded(id,refundTo,amount);}\n    }\n    function _update(address from,address to,uint256 value) internal override {\n        if(from==address(0))totalMinted+=value;if(to==address(0))totalBurned+=value;super._update(from,to,value);\n    }\n}\n"},"v2/BreadTradingHook.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {IHooks} from \"@uniswap/v4-core/src/interfaces/IHooks.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {SwapParams} from \"@uniswap/v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"@uniswap/v4-core/src/types/BalanceDelta.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {Hooks} from \"@uniswap/v4-core/src/libraries/Hooks.sol\";\n\n/// @notice Official-pool protocol fee, additional to the configured Uniswap LP fee.\n/// Exact-input swaps pay from output; exact-output swaps add to input (v4 unspecified currency).\ncontract BreadTradingHook {\n    IPoolManager public immutable manager;address public immutable bread;address public immutable quote;address public immutable treasury;\n    uint24 public immutable lpFee;int24 public immutable tickSpacing;\n    mapping(address=>uint256) public protocolFees;uint256 public breadVolume;uint256 public quoteVolume;\n    event TradingFee(bool indexed buyBread,address indexed currency,uint256 amount);\n    error Unauthorized();error InvalidPool();\n    constructor(address manager_,address bread_,address quote_,address treasury_,uint24 fee,int24 spacing){\n        require(manager_.code.length>0&&bread_.code.length>0&&treasury_!=address(0)&&bread_!=quote_&&fee<1000000&&spacing>0);\n        manager=IPoolManager(manager_);bread=bread_;quote=quote_;treasury=treasury_;lpFee=fee;tickSpacing=spacing;\n        Hooks.Permissions memory p;p.beforeInitialize=true;p.afterSwap=true;p.afterSwapReturnDelta=true;Hooks.validateHookPermissions(IHooks(address(this)),p);\n    }\n    function _check(PoolKey calldata key) internal view {\n        if(msg.sender!=address(manager))revert Unauthorized();\n        address a=Currency.unwrap(key.currency0);address b=Currency.unwrap(key.currency1);\n        if(!((a==bread&&b==quote)||(a==quote&&b==bread))||key.fee!=lpFee||key.tickSpacing!=tickSpacing||address(key.hooks)!=address(this))revert InvalidPool();\n    }\n    function beforeInitialize(address,PoolKey calldata key,uint160) external view returns(bytes4){_check(key);return IHooks.beforeInitialize.selector;}\n    function afterSwap(address,PoolKey calldata key,SwapParams calldata params,BalanceDelta delta,bytes calldata) external returns(bytes4,int128){\n        _check(key);bool breadIs0=Currency.unwrap(key.currency0)==bread;bool buying=breadIs0?!params.zeroForOne:params.zeroForOne;\n        bool specifiedIs0=(params.amountSpecified<0)==params.zeroForOne;\n        Currency currency=specifiedIs0?key.currency1:key.currency0;\n        int256 amount=specifiedIs0?int256(delta.amount1()):int256(delta.amount0());\n        uint256 fee=uint256(amount<0?-amount:amount)*(buying?100:200)/10000;\n        int256 b=breadIs0?int256(delta.amount0()):int256(delta.amount1());int256 q=breadIs0?int256(delta.amount1()):int256(delta.amount0());\n        breadVolume+=uint256(b<0?-b:b);quoteVolume+=uint256(q<0?-q:q);\n        if(fee!=0){protocolFees[Currency.unwrap(currency)]+=fee;manager.take(currency,treasury,fee);emit TradingFee(buying,Currency.unwrap(currency),fee);}\n        return(IHooks.afterSwap.selector,int128(int256(fee)));\n    }\n}\n"},"v2/Create2Factory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\ncontract Create2Factory {\n    event Deployed(address indexed deployment,bytes32 salt);\n    function deploy(bytes32 salt,bytes calldata initCode) external returns(address deployed){\n        bytes memory code=initCode;assembly{deployed:=create2(0,add(code,32),mload(code),salt)}require(deployed!=address(0),\"Create2 failed\");emit Deployed(deployed,salt);\n    }\n}\n"},"v2/EconomicConfig.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract EconomicConfig is Ownable {\n    struct Tier { uint16 throughId; uint128 breadCost; }\n    Tier[] public tiers;\n    uint16[3] public modeBps;\n    bool[3] public modeEnabled;\n    address public treasury;\n    bool public frozen;\n    event EconomicConfigurationChanged();\n    event EconomicConfigurationFrozen(bytes32 configurationHash);\n    error Frozen(); error InvalidConfiguration(); error SoldOut(); error ModeUnavailable();\n    constructor(address treasury_) Ownable(msg.sender) { treasury=treasury_; }\n    function configure(Tier[] calldata next, uint16[3] calldata multipliers, bool[3] calldata enabled, address treasury_) external onlyOwner {\n        if(frozen) revert Frozen();\n        if(treasury_==address(0)||next.length==0||next.length>16||!enabled[0]||multipliers[0]!=10000) revert InvalidConfiguration();\n        uint256 last=333;uint256 cost;\n        delete tiers;\n        for(uint256 i;i<next.length;i++){\n            if(next[i].throughId<=last||next[i].throughId>3333||next[i].breadCost==0||next[i].breadCost<cost) revert InvalidConfiguration();\n            last=next[i].throughId;cost=next[i].breadCost;tiers.push(next[i]);\n        }\n        if(last!=3333||multipliers[1]<10000||multipliers[2]<multipliers[1]) revert InvalidConfiguration();\n        modeBps=multipliers;modeEnabled=enabled;treasury=treasury_;emit EconomicConfigurationChanged();\n    }\n    function freezeEconomicConfiguration() external onlyOwner {\n        if(frozen) revert Frozen();if(tiers.length==0||treasury==address(0)) revert InvalidConfiguration();\n        frozen=true;emit EconomicConfigurationFrozen(keccak256(abi.encode(tiers,modeBps,modeEnabled,treasury)));\n    }\n    function cost(uint256 nextId,uint8 mode) public view returns(uint256){\n        if(mode>2||!modeEnabled[mode]) revert ModeUnavailable();\n        if(nextId>3333) revert SoldOut();\n        for(uint256 i;i<tiers.length;i++) if(nextId<=tiers[i].throughId) return uint256(tiers[i].breadCost)*modeBps[mode]/10000;\n        revert InvalidConfiguration();\n    }\n    function tierCount() external view returns(uint256){return tiers.length;}\n}\n"},"v2/GenesisDrawV2.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.28;\r\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport {MerkleProof} from \"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol\";\r\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\nimport {EIP712} from \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\r\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\r\ninterface IGenesisQuacks {function mintGenesis(address to,uint256 id,uint256 seed) external;function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256);}\r\ninterface IDrawEntropy {function request(uint256 roundId) external returns(uint256);function cancel(uint256 requestId) external;}\r\n\r\n/// @notice Phased whitelist/public draws with frozen eligibility and asynchronous entropy.\ncontract GenesisDrawV2 is ReentrancyGuard,EIP712,Ownable {\r\n    uint256 public constant INTERVAL=30 minutes;\r\n    uint256 public constant CLAIM_WINDOW=24 hours;\r\n    bytes32 public eligibilityRoot;\n    bytes32 public publicEligibilityRoot;\n    uint256 public whitelistWinLimit;\n    uint256 public whitelistWins;\n    event WhitelistConfigured(uint256 wins,bytes32 whitelistRoot,bytes32 publicRoot);\n    event PublicRegistrationOpened(uint256 whitelistWins);\n    event EmptyRoundRestarted(uint256 nextDrawAt);\n    bool public configurationFrozen;bool public paused;bool public oneWinPerWallet=true;\r\n    uint256 public claimedCount;uint256 public pendingClaimCount;\r\n    event ConfigurationFrozen();event PauseChanged(bool paused);\r\n    address public immutable eligibilitySigner;\r\n    bytes32 public constant ENTRY_TYPEHASH=keccak256(\"Entry(address wallet,uint256 deadline)\");\r\n    IGenesisQuacks public immutable quacks;\r\n    IDrawEntropy public immutable entropy;\r\n    uint256 public nextDrawAt;\r\n    uint256 public rounds;\r\n    uint256 public pendingRequest;\r\n    uint256 public snapshotSize;\r\n    uint256 public selectedToken;\r\n    mapping(uint256=>bool) public usedRequest;\r\n    address[] public entrants;\r\n    uint256[] public pool;\r\n    mapping(address=>bool) public registered;\r\n    mapping(address=>uint256) public pendingAward;\r\n    mapping(address=>bool) public hasClaimed;\r\n    struct Award {address winner;uint64 deadline;uint256 seed;bool claimed;}\r\n    mapping(uint256=>Award) public awards;\r\n    event Registered(address indexed guest);\r\n    event DrawRequested(uint256 indexed round,uint256 indexed requestId,uint256 indexed tokenId,uint256 entrants);\r\n    event Awarded(uint256 indexed tokenId,address indexed winner,uint256 deadline);\r\n    event Returned(uint256 indexed tokenId);\r\n    event Claimed(uint256 indexed tokenId,address indexed winner);\r\n    constructor(address nft,address rng,bytes32 root,uint256 startAt,address signer) EIP712(\"Quacks Genesis\",\"2\") Ownable(msg.sender){\r\n        require(nft.code.length>0 && rng.code.length>0 && (root!=bytes32(0) || signer!=address(0)) && startAt>block.timestamp,\"Invalid setup\");\r\n        quacks=IGenesisQuacks(nft);entropy=IDrawEntropy(rng);eligibilityRoot=root;eligibilitySigner=signer;nextDrawAt=startAt;\r\n        for(uint256 i=333;i>0;i--)pool.push(i);\r\n    }\r\n    function register(bytes32[] calldata proof) external {\n        bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\n        require(eligibilityRoot!=bytes32(0)&&MerkleProof.verifyCalldata(proof,eligibilityRoot,leaf),\"Not eligible\");_register();\n    }\n    function publicRegistrationOpen() public view returns(bool){return whitelistWins>=whitelistWinLimit;}\n    /// @notice Zero public root and signer means permissionless public registration.\n    function registerPublic(bytes32[] calldata proof) external {\n        require(publicRegistrationOpen(),\"Whitelist phase\");\n        if(publicEligibilityRoot!=bytes32(0)){\n            bytes32 leaf=keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));\n            require(MerkleProof.verifyCalldata(proof,publicEligibilityRoot,leaf),\"Not eligible\");\n        }else require(eligibilitySigner==address(0),\"Public ticket required\");\n        _register();\n    }\n    function registerWithTicket(uint256 deadline,bytes calldata signature) external {\n        require(publicRegistrationOpen(),\"Whitelist phase\");\n        require(!registered[msg.sender] && eligibilitySigner!=address(0) && block.timestamp<=deadline,\"Entry unavailable\");\n        bytes32 digest=_hashTypedDataV4(keccak256(abi.encode(ENTRY_TYPEHASH,msg.sender,deadline)));\n        require(ECDSA.recover(digest,signature)==eligibilitySigner,\"Not eligible\");_register();\n    }\n    function _register() internal {\n        require(configurationFrozen&&!paused,\"Entry paused or not frozen\");\n        require(!registered[msg.sender],\"Already registered\");\n        require(pool.length>0||pendingRequest!=0||pendingClaimCount>0,\"Genesis complete\");\n        registered[msg.sender]=true;entrants.push(msg.sender);emit Registered(msg.sender);\n    }\n    function configureWhitelist(uint256 wins,bytes32 publicRoot) external onlyOwner {\n        require(!configurationFrozen,\"Frozen\");require(wins<=333&&(wins==0||eligibilityRoot!=bytes32(0)),\"Invalid whitelist\");\n        whitelistWinLimit=wins;publicEligibilityRoot=publicRoot;emit WhitelistConfigured(wins,eligibilityRoot,publicRoot);\n    }\r\n    function configureEligibility(bytes32 root,bool singleWin) external onlyOwner {require(!configurationFrozen,\"Frozen\");require(root!=bytes32(0)||eligibilitySigner!=address(0),\"No eligibility\");eligibilityRoot=root;oneWinPerWallet=singleWin;}\r\n    function freezeEconomicConfiguration() external onlyOwner {require(!configurationFrozen,\"Frozen\");require(whitelistWinLimit==0||eligibilityRoot!=bytes32(0),\"No whitelist root\");configurationFrozen=true;emit ConfigurationFrozen();}\n    function setPaused(bool value) external onlyOwner {paused=value;emit PauseChanged(value);}\r\n    function entrantCount() external view returns(uint256){return entrants.length;}\r\n    function poolCount() external view returns(uint256){return pool.length;}\r\n    function requestDraw() external nonReentrant {\r\n        require(configurationFrozen&&!paused&&block.timestamp>=nextDrawAt && pendingRequest==0 && pool.length>0,\"Draw unavailable\");\n        if(entrants.length==0){nextDrawAt=block.timestamp+INTERVAL;emit EmptyRoundRestarted(nextDrawAt);return;}\n        selectedToken=pool[pool.length-1];pool.pop();snapshotSize=entrants.length;rounds++;nextDrawAt=block.timestamp+INTERVAL;\r\n        uint256 requestId=entropy.request(rounds);require(requestId>0 && !usedRequest[requestId],\"Bad request\");usedRequest[requestId]=true;pendingRequest=requestId;\r\n        emit DrawRequested(rounds,requestId,selectedToken,snapshotSize);\r\n    }\r\n    function fulfillEntropy(uint256 requestId,uint256 seed) external nonReentrant {\r\n        require(msg.sender==address(entropy) && requestId==pendingRequest && requestId!=0,\"Invalid fulfillment\");\r\n        uint256 index=seed%snapshotSize;address winner=entrants[index];entrants[index]=entrants[entrants.length-1];entrants.pop();\r\n        uint256 token=selectedToken;pendingRequest=0;selectedToken=0;snapshotSize=0;\r\n        quacks.reserveGenesisArtwork(token,seed);pendingAward[winner]=token;\r\n        pendingClaimCount++;awards[token]=Award(winner,uint64(block.timestamp+CLAIM_WINDOW),seed,false);emit Awarded(token,winner,block.timestamp+CLAIM_WINDOW);\n        if(whitelistWins<whitelistWinLimit){whitelistWins++;if(whitelistWins==whitelistWinLimit)emit PublicRegistrationOpened(whitelistWins);}\n    }\r\n    function claim(uint256 token) external nonReentrant {\r\n        Award storage award=awards[token];require(award.winner==msg.sender && !award.claimed && block.timestamp<award.deadline,\"Claim unavailable\");\r\n        claimedCount++;pendingClaimCount--;award.claimed=true;pendingAward[msg.sender]=0;hasClaimed[msg.sender]=true;quacks.mintGenesis(msg.sender,token,award.seed);if(!oneWinPerWallet)entrants.push(msg.sender);emit Claimed(token,msg.sender);\r\n    }\r\n    function recoverStalledDraw() external nonReentrant {require(pendingRequest!=0,\"No request\");entropy.cancel(pendingRequest);pool.push(selectedToken);pendingRequest=0;selectedToken=0;snapshotSize=0;}\r\n    function recycle(uint256 token) external {\r\n        Award memory award=awards[token];require(award.winner!=address(0) && !award.claimed && block.timestamp>=award.deadline,\"Not expired\");\r\n        pendingClaimCount--;delete awards[token];pool.push(token);pendingAward[award.winner]=0;entrants.push(award.winner);emit Returned(token);\r\n    }\r\n}\r\n"},"v2/IRandomnessProvider.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\n\ninterface IRandomnessProvider {\n    function request(uint256 context) external returns (uint256);\n    /// @notice Cancellation must reject a result already available for delivery.\n    function cancel(uint256 requestId) external;\n}\n\ninterface IRandomnessConsumer {\n    function fulfillEntropy(uint256 requestId, uint256 seed) external;\n}\n"},"v2/Quacks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {ERC721} from \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport {ERC2981} from \"@openzeppelin/contracts/token/common/ERC2981.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {EconomicConfig} from \"./EconomicConfig.sol\";\nimport {Bread} from \"./Bread.sol\";\nimport {TraitInventory} from \"./TraitInventory.sol\";\nimport {IRandomnessProvider} from \"./IRandomnessProvider.sol\";\ninterface IRendererV2 {function tokenURI(uint256,bool,uint8,uint256) external view returns(string memory);function burnedTokenURI(uint256,uint256) external view returns(string memory);}\n\ncontract Quacks is ERC721,ERC2981,Ownable,ReentrancyGuard {\n    uint256 public constant MAX_SUPPLY=3333;uint256 public constant GENESIS_SUPPLY=333;\n    uint256 public constant INCUBATION=7 days;uint256 public immutable recoveryDelay;\n    EconomicConfig public immutable economics;Bread public immutable bread;\n    TraitInventory public immutable traits;IRandomnessProvider public entropy;IRendererV2 public renderer;\n    address public draw;bool public configured;bool public rendererFrozen;bool public hatchingPaused;\n    uint256 public expansionMinted;uint256 public genesisMinted;uint256 public totalQuacksBurned;\n    mapping(uint256=>uint256) public transferNonce;\n    mapping(uint256=>bool) public revealed;mapping(uint256=>uint256) public artworkOf;\n    mapping(uint256=>bool) public wasBurned;mapping(uint256=>address) public burnedBy;mapping(uint256=>uint256) public replacementOf;\n    struct Egg {uint64 readyAt;uint64 requestedAt;uint8 mode;bool paid;bool cancelled;uint256 requestId;}\n    mapping(uint256=>Egg) public eggs;mapping(uint256=>uint256) public requestToken;mapping(uint256=>bool) public usedRequest;\n    event EggMinted(uint256 indexed tokenId,address indexed owner,uint256 cost,uint8 mode,uint256 readyAt);\n    event HatchModeAdjusted(uint256 indexed tokenId,uint8 requestedMode,uint256 premiumRefund);\n    event HatchRequested(uint256 indexed tokenId,uint256 indexed requestId);\n    event QuackGenerated(uint256 indexed tokenId,uint256 indexed artwork,address indexed owner);\n    event QuackBurned(uint256 indexed tokenId,address indexed owner);\n    event ReplacementGenerated(uint256 indexed burnedId,uint256 indexed replacementId);\n    event HatchRecovered(uint256 indexed tokenId,address indexed owner);\n    event MetadataUpdate(uint256 tokenId);\n    event RendererFrozen(address renderer);event HatchingPauseChanged(bool paused);\n    error Unavailable();error Unauthorized();error SoldOut();error InvalidConfiguration();error InvalidRequest();\n    constructor(address token,address config,address inventory,uint256 timeout) ERC721(\"Quacks\",\"QUACKS\") Ownable(msg.sender){\n        if(token.code.length==0||config.code.length==0||inventory.code.length==0||timeout<1 days) revert InvalidConfiguration();\n        bread=Bread(token);economics=EconomicConfig(config);traits=TraitInventory(inventory);recoveryDelay=timeout;\n    }\n    function configure(address draws,address rng,address art) external onlyOwner {\n        if(configured||draws.code.length==0||rng.code.length==0||art.code.length==0) revert InvalidConfiguration();\n        draw=draws;entropy=IRandomnessProvider(rng);renderer=IRendererV2(art);configured=true;\n    }\n    function setRenderer(address art) external onlyOwner {if(rendererFrozen||art.code.length==0) revert InvalidConfiguration();renderer=IRendererV2(art);}\n    function freezeRenderer() public virtual onlyOwner {if(rendererFrozen||address(renderer)==address(0)||!economics.frozen()) revert InvalidConfiguration();rendererFrozen=true;_setDefaultRoyalty(economics.treasury(),500);emit RendererFrozen(address(renderer));}\n    function setHatchingPaused(bool value) external onlyOwner {hatchingPaused=value;emit HatchingPauseChanged(value);}\n    function isGenesis(uint256 id) public pure returns(bool){return id>0&&id<=333;}\n    function lifetimeGenerated() public view returns(uint256){return genesisMinted+expansionMinted;}\n    /// @notice Reserved Genesis slots plus used expansion slots. Claims cannot hold back unlocks.\n    /// This is distinct from minted/live supply and never decreases after a burn or refund.\n    function generationProgress() public view returns(uint256){return GENESIS_SUPPLY+expansionMinted;}\n    function totalSupply() external view returns(uint256){return lifetimeGenerated()-totalQuacksBurned;}\n    function remainingGenerationSlots() external view returns(uint256){return 3333-lifetimeGenerated();}\n    function currentHatchCost() public view returns(uint256){return economics.cost(334+expansionMinted,0);}\n    function hatchCost(uint8 mode) public view returns(uint256){\n        uint256 cost=economics.cost(334+expansionMinted,mode);\n        if(mode>0&&!traits.hasModeAdvantage(generationProgress()+1,mode))revert Unavailable();return cost;\n    }\n    function _ready() internal view {if(!configured||!rendererFrozen||!traits.frozen()||!bread.frozen()||!economics.frozen()) revert Unavailable();}\n    function reserveGenesisArtwork(uint256 id,uint256 seed) external returns(uint256){\n        _ready();if(msg.sender!=draw||!isGenesis(id)) revert Unauthorized();\n        if(artworkOf[id]==0)artworkOf[id]=traits.assign(seed,generationProgress(),0);return artworkOf[id];\n    }\n    function mintGenesis(address to,uint256 id,uint256) external nonReentrant {\n        _ready();if(msg.sender!=draw||!isGenesis(id)||artworkOf[id]==0||revealed[id]||wasBurned[id]) revert Unauthorized();\n        genesisMinted++;revealed[id]=true;_safeMint(to,id);emit QuackGenerated(id,artworkOf[id],to);\n    }\n    function mintEgg(uint8 mode,uint256 maxCost) external nonReentrant returns(uint256 id){\n        _ready();if(hatchingPaused) revert Unavailable();if(expansionMinted>=3000) revert SoldOut();\n        uint256 cost=hatchCost(mode);if(cost>maxCost||cost>type(uint128).max) revert Unavailable();\n        id=334+expansionMinted++;eggs[id]=Egg(uint64(block.timestamp+INCUBATION),0,mode,true,false,0);\n        bread.payHatch(id,msg.sender,uint128(cost));_safeMint(msg.sender,id);emit EggMinted(id,msg.sender,cost,mode,block.timestamp+INCUBATION);\n    }\n    function hatch(uint256 id) external nonReentrant {\n        if(ownerOf(id)!=msg.sender||revealed[id]||block.timestamp<eggs[id].readyAt) revert Unavailable();_request(id);\n    }\n    function _request(uint256 id) internal {\n        Egg storage e=eggs[id];if(e.requestId!=0||e.cancelled) revert InvalidRequest();\n        e.requestedAt=uint64(block.timestamp);uint256 request=entropy.request(id);\n        if(request==0||usedRequest[request]) revert InvalidRequest();usedRequest[request]=true;e.requestId=request;requestToken[request]=id;emit HatchRequested(id,request);\n    }\n    function fulfillEntropy(uint256 request,uint256 seed) external nonReentrant {\n        if(msg.sender!=address(entropy)) revert Unauthorized();uint256 id=requestToken[request];if(id==0) revert InvalidRequest();\n        delete requestToken[request];Egg storage e=eggs[id];uint256 refund;\n        if(e.paid&&e.mode>0&&!traits.hasModeAdvantage(generationProgress(),e.mode)){\n            (,uint128 paid,)=bread.hatchPayments(id);refund=paid-economics.cost(id,0);\n            emit HatchModeAdjusted(id,e.mode,refund);e.mode=0;\n        }\n        artworkOf[id]=traits.assign(seed,generationProgress(),e.mode);revealed[id]=true;\n        if(e.paid){if(refund>0)bread.resolveHatchPaymentPartial(id,ownerOf(id),uint128(refund));else bread.resolveHatchPayment(id,address(0));}\n        emit MetadataUpdate(id);emit QuackGenerated(id,artworkOf[id],ownerOf(id));\n    }\n    function burnForMint(uint256 id) external nonReentrant returns(uint256 replacement){\n        _ready();if(hatchingPaused||ownerOf(id)!=msg.sender||!revealed[id]) revert Unavailable();if(expansionMinted>=3000) revert SoldOut();\n        _destroy(id);replacement=334+expansionMinted++;replacementOf[id]=replacement;eggs[replacement]=Egg(uint64(block.timestamp),0,0,false,false,0);\n        _request(replacement);_safeMint(msg.sender,replacement);emit ReplacementGenerated(id,replacement);\n    }\n    /// @notice Refund an expired paid request only after the provider atomically cancels it.\n    /// The burned egg's lifetime slot is not recycled; no ID or known random outcome is reused.\n    function recoverFailedHatch(uint256 id) external nonReentrant {\n        Egg storage e=eggs[id];if(ownerOf(id)!=msg.sender||revealed[id]||!e.paid||block.timestamp<(e.requestId==0?e.readyAt:e.requestedAt)+recoveryDelay) revert Unavailable();\n        if(e.requestId!=0){entropy.cancel(e.requestId);delete requestToken[e.requestId];}e.cancelled=true;_destroy(id);bread.resolveHatchPayment(id,msg.sender);emit HatchRecovered(id,msg.sender);\n    }\n    function retryFailedReplacement(uint256 id) external nonReentrant {\n        Egg storage e=eggs[id];if(ownerOf(id)!=msg.sender||revealed[id]||e.paid||e.requestId==0||block.timestamp<e.requestedAt+recoveryDelay) revert Unavailable();\n        entropy.cancel(e.requestId);delete requestToken[e.requestId];e.requestId=0;_request(id);\n    }\n    function _destroy(uint256 id) internal {wasBurned[id]=true;burnedBy[id]=msg.sender;_burn(id);totalQuacksBurned++;emit QuackBurned(id,msg.sender);emit MetadataUpdate(id);}\n    function stage(uint256 id) public view returns(uint8){uint256 ready=eggs[id].readyAt;if(ready==0||block.timestamp>=ready)return 7;return uint8((INCUBATION-(ready-block.timestamp))/1 days);}\n    function tokenURI(uint256 id) public view override returns(string memory){\n        if(wasBurned[id])return renderer.burnedTokenURI(id,artworkOf[id]);\n        _requireOwned(id);return renderer.tokenURI(id,revealed[id],stage(id),artworkOf[id]);\n    }\n    function _update(address to,uint256 id,address auth) internal virtual override returns(address){transferNonce[id]++;return super._update(to,id,auth);}\n    function supportsInterface(bytes4 id) public view virtual override(ERC721,ERC2981) returns(bool){return id==0x49064906||super.supportsInterface(id);}\n}\n"},"v2/QuacksRendererV2.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.28;\r\nimport {Base64} from \"@openzeppelin/contracts/utils/Base64.sol\";\r\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\r\n\r\n/// @notice Immutable native 32x32 PNG art, attributes and eight egg stages, entirely on-chain.\r\ncontract QuacksRendererV2 {\r\n    using Strings for uint256;\r\n    address[] public pages;\r\n    address public immutable indexBlob;\r\n    address public immutable traitsBlob;\r\n    address public immutable eggsBlob;\r\n    uint256 public immutable traitCount;\r\n    bytes32 public immutable manifestHash;\r\n    uint256 public constant ART_COUNT=3333;\r\n    constructor(address[] memory artPages,address index_,address traits_,address eggs_,uint256 traitsCount_,bytes32 hash_){\r\n        require(artPages.length>0 && artPages.length<256 && index_.code.length==16666 && traits_.code.length>1 && eggs_.code.length>1 && traitsCount_>0 && traitsCount_<256,\"Invalid art\");\r\n        for(uint256 i;i<artPages.length;i++)require(artPages[i].code.length>1 && artPages[i].code.length<=24001,\"Invalid page\");\r\n        pages=artPages;indexBlob=index_;traitsBlob=traits_;eggsBlob=eggs_;traitCount=traitsCount_;manifestHash=hash_;\r\n    }\r\n    function _read(address blob,uint256 offset,uint256 length) internal view returns(bytes memory data){require(offset+length+1<=blob.code.length,\"Art bounds\");data=new bytes(length);assembly{extcodecopy(blob,add(data,32),add(offset,1),length)}}\r\n    function _u16(bytes memory b,uint256 at) internal pure returns(uint256){return uint8(b[at])*256+uint8(b[at+1]);}\r\n    function record(uint256 artwork) public view returns(bytes memory){require(artwork>0 && artwork<=ART_COUNT,\"Art ID\");bytes memory pointer=_read(indexBlob,(artwork-1)*5,5);return _read(pages[uint8(pointer[0])],_u16(pointer,1),_u16(pointer,3));}\r\n    function _slice(bytes memory b,uint256 start,uint256 length) internal pure returns(bytes memory result){require(start+length<=b.length,\"Slice\");result=new bytes(length);for(uint256 i;i<length;i++)result[i]=b[start+i];}\r\n    function _trait(uint256 id) internal view returns(bytes memory){require(id<traitCount,\"Trait ID\");bytes memory p=_read(traitsBlob,id*4,4);return _read(traitsBlob,traitCount*4+_u16(p,0),_u16(p,2));}\r\n    /// @notice Original on-chain PNG with a native-grid flame, retained after ERC-721 destruction.\r\n    function burnedTokenURI(uint256 id,uint256 artwork) external view returns(string memory){\r\n        bytes memory data;\n        if(artwork==0){bytes memory pointer=_read(eggsBlob,28,4);bytes memory egg=_read(eggsBlob,32+_u16(pointer,0),_u16(pointer,2));data=bytes.concat(bytes2(uint16(egg.length)),egg);}\n        else data=record(artwork);\n        uint256 pngLength=_u16(data,0);\n        bytes memory svg=abi.encodePacked(\r\n            '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" shape-rendering=\"crispEdges\">',\r\n            '<image width=\"32\" height=\"32\" style=\"image-rendering:pixelated\" href=\"data:image/png;base64,',Base64.encode(_slice(data,2,pngLength)),'\"/>',\r\n            '<g id=\"burned-icon\"><path fill=\"#ff3038\" d=\"M1 31V25h1v-2h1v2h1v-1h1v2h1v5zM1 22h1v1H1zM3 21h1v1H3zM4 22h1v1H4z\"/>',\r\n            '<path fill=\"#ff941f\" d=\"M2 31v-4h1v-1h2v5z\"/><path fill=\"#ffdc2c\" d=\"M3 31v-3h1v-1h1v4z\"/></g></svg>'\r\n        );\r\n        bytes memory attributes=bytes('[');\r\n        for(uint256 i=2+pngLength;i<data.length;i++)attributes=bytes.concat(attributes,i==2+pngLength?bytes(''):bytes(','),_trait(uint8(data[i])));\r\n        attributes=bytes.concat(attributes,data.length>2+pngLength?bytes(','):bytes(''),bytes('{\"trait_type\":\"Status\",\"value\":\"Burned\"},'),bytes(id<=333?'{\"trait_type\":\"Genesis\",\"value\":\"Yes\"}]':'{\"trait_type\":\"Genesis\",\"value\":\"No\"}]'));\n        return string.concat('data:application/json;base64,',Base64.encode(abi.encodePacked(\r\n            '{\"name\":\"Quacks #',id.toString(),'\",\"description\":\"This Quack was permanently burned for a replacement. Its original artwork is preserved with a pixel flame. It cannot be owned, transferred or staked.\",\"image\":\"data:image/svg+xml;base64,',Base64.encode(svg),'\",\"attributes\":',attributes,'}'\r\n        )));\r\n    }\r\n    function tokenURI(uint256 id,bool hatched,uint8 day,uint256 artwork) external view returns(string memory){\r\n        bytes memory image;bytes memory attributes;string memory name;\r\n        if(hatched){\r\n            bytes memory data=record(artwork);uint256 pngLength=_u16(data,0);image=bytes.concat(bytes('data:image/png;base64,'),bytes(Base64.encode(_slice(data,2,pngLength))));\r\n            attributes=bytes('[');for(uint256 i=2+pngLength;i<data.length;i++)attributes=bytes.concat(attributes,i==2+pngLength?bytes(''):bytes(','),_trait(uint8(data[i])));attributes=bytes.concat(attributes,bytes(id<=333?',{\"trait_type\":\"Genesis\",\"value\":\"Yes\"}]':',{\"trait_type\":\"Genesis\",\"value\":\"No\"}]'));name=string.concat('Quacks #',id.toString());\r\n        }else{\r\n            require(day<=7,\"Egg stage\");bytes memory p=_read(eggsBlob,uint256(day)*4,4);bytes memory svg=_read(eggsBlob,32+_u16(p,0),_u16(p,2));\r\n            image=bytes.concat(bytes('data:image/png;base64,'),bytes(Base64.encode(svg)));name=string.concat('Quacks Egg #',id.toString());\r\n            attributes=bytes(string.concat('[{\"trait_type\":\"Incubation day\",\"value\":',uint256(day).toString(),'}]'));\r\n        }\r\n        image=bytes.concat(bytes('data:image/svg+xml;base64,'),bytes(Base64.encode(abi.encodePacked('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" shape-rendering=\"crispEdges\"><image width=\"32\" height=\"32\" style=\"image-rendering:pixelated\" href=\"',image,'\"/></svg>'))));\r\n        return string.concat('data:application/json;base64,',Base64.encode(abi.encodePacked('{\"name\":\"',name,'\",\"description\":\"Quacks. Small ducks. Big personalities.\",\"image\":\"',image,'\",\"attributes\":',attributes,'}')));\r\n    }\r\n}\r\n"},"v2/QuacksStaking.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\ninterface IStakeQuacks is IERC721 {function revealed(uint256) external view returns(bool);}\ninterface IRewardBread {function mintRewards(address,uint256) external;}\n\ncontract QuacksStaking is Ownable,ReentrancyGuard {\n    IStakeQuacks public immutable quacks;IRewardBread public immutable bread;\n    uint256 public constant DAILY_REWARD=1 ether;\n    uint256 public totalStaked;bool public paused;\n    mapping(uint256=>address) public depositor;\n    mapping(uint256=>uint256) private indexOf;\n    mapping(address=>uint256[]) private tokens;\n    mapping(address=>uint256) private accruedNumerator;\n    mapping(address=>uint256) private lastUpdate;\n    event Staked(address indexed owner,uint256 indexed tokenId);\n    event Unstaked(address indexed owner,uint256 indexed tokenId);\n    event RewardsClaimed(address indexed owner,uint256 amount);\n    event PauseChanged(bool paused);\n    error Unavailable();error NotDepositor();error InvalidBatch();\n    constructor(address nft,address token) Ownable(msg.sender){quacks=IStakeQuacks(nft);bread=IRewardBread(token);}\n    function setPaused(bool value) external onlyOwner {paused=value;emit PauseChanged(value);}\n    function _checkpoint(address who) internal {\n        accruedNumerator[who]+=(block.timestamp-lastUpdate[who])*tokens[who].length*DAILY_REWARD;lastUpdate[who]=block.timestamp;\n    }\n    function earned(address who) public view returns(uint256){return (accruedNumerator[who]+(block.timestamp-lastUpdate[who])*tokens[who].length*DAILY_REWARD)/1 days;}\n    function stakedTokens(address who) external view returns(uint256[] memory){return tokens[who];}\n    function stake(uint256 id) external nonReentrant {_checkpoint(msg.sender);_stake(id);}\n    function stakeBatch(uint256[] calldata ids) external nonReentrant {if(ids.length==0||ids.length>50) revert InvalidBatch();_checkpoint(msg.sender);for(uint256 i;i<ids.length;i++)_stake(ids[i]);}\n    function _stake(uint256 id) internal {\n        if(paused||quacks.ownerOf(id)!=msg.sender||!quacks.revealed(id)) revert Unavailable();\n        depositor[id]=msg.sender;indexOf[id]=tokens[msg.sender].length;tokens[msg.sender].push(id);totalStaked++;\n        quacks.transferFrom(msg.sender,address(this),id);emit Staked(msg.sender,id);\n    }\n    function unstake(uint256 id) external nonReentrant {_checkpoint(msg.sender);_unstake(id);}\n    function unstakeBatch(uint256[] calldata ids) external nonReentrant {if(ids.length==0||ids.length>50) revert InvalidBatch();_checkpoint(msg.sender);for(uint256 i;i<ids.length;i++)_unstake(ids[i]);}\n    function _unstake(uint256 id) internal {\n        if(depositor[id]!=msg.sender) revert NotDepositor();uint256 index=indexOf[id];uint256 last=tokens[msg.sender][tokens[msg.sender].length-1];\n        tokens[msg.sender][index]=last;indexOf[last]=index;tokens[msg.sender].pop();delete depositor[id];delete indexOf[id];totalStaked--;\n        quacks.safeTransferFrom(address(this),msg.sender,id);emit Unstaked(msg.sender,id);\n    }\n    function claimAll() public nonReentrant {\n        _checkpoint(msg.sender);uint256 amount=accruedNumerator[msg.sender]/1 days;accruedNumerator[msg.sender]%=1 days;\n        if(amount>0){bread.mintRewards(msg.sender,amount);emit RewardsClaimed(msg.sender,amount);}\n    }\n    function claim() external {claimAll();}\n}\n"},"v2/QuiverRecoveryEntropy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {IRandomnessProvider,IRandomnessConsumer} from \"./IRandomnessProvider.sol\";\ninterface IQuiverV2 {function getFee(address) external view returns(uint128);function requestWithCallback(address,bytes32) external payable returns(uint64);function retryCallback(address,uint64) external;}\n\n/// @notice Quiver adapter; provider liveness/secrecy remain explicit external trust assumptions.\n/// Pre-launch review must approve coordinator bytecode and provider before this is used for value.\ncontract QuiverRecoveryEntropy is IRandomnessProvider,Ownable,ReentrancyGuard {\n    IQuiverV2 public immutable coordinator;address public immutable provider;uint256 public immutable timeout;uint256 public immutable feeCeiling;\n    mapping(address=>bool) public consumers;bool public frozen;uint256 public requested;uint256 public nextDelivery=1;\n    struct Request {address consumer;uint64 sequence;uint64 createdAt;bool ready;bool delivered;bool cancelled;uint256 seed;}\n    mapping(uint256=>Request) public requests;mapping(uint64=>uint256) public sequenceToRequest;\n    event Requested(uint256 indexed id,address indexed consumer,uint256 context);event Ready(uint256 indexed id);event Delivered(uint256 indexed id);event Cancelled(uint256 indexed id);\n    error Unavailable();error Unauthorized();\n    constructor(address coordinator_,address provider_,uint256 timeout_,uint256 maxFee) Ownable(msg.sender){require(coordinator_.code.length>0&&provider_!=address(0)&&timeout_>=1 days);coordinator=IQuiverV2(coordinator_);provider=provider_;timeout=timeout_;feeCeiling=maxFee;}\n    receive() external payable{}\n    function configureConsumers(address nft,address draw) external onlyOwner{if(frozen||nft.code.length==0||draw.code.length==0)revert Unavailable();consumers[nft]=true;consumers[draw]=true;frozen=true;}\n    function request(uint256 context) external nonReentrant returns(uint256 id){\n        if(!consumers[msg.sender])revert Unauthorized();uint256 fee=coordinator.getFee(provider);if(fee>feeCeiling||fee>address(this).balance)revert Unavailable();\n        id=++requested;uint64 sequence=coordinator.requestWithCallback{value:fee}(provider,keccak256(abi.encode(block.chainid,address(this),id,context)));\n        if(sequenceToRequest[sequence]!=0)revert Unavailable();sequenceToRequest[sequence]=id;requests[id]=Request(msg.sender,sequence,uint64(block.timestamp),false,false,false,0);emit Requested(id,msg.sender,context);\n    }\n    function quiverCallback(uint64 sequence,address provider_,bytes32 word) external {\n        if(msg.sender!=address(coordinator)||provider_!=provider)revert Unauthorized();uint256 id=sequenceToRequest[sequence];Request storage r=requests[id];\n        if(id==0||r.cancelled)revert Unavailable();if(r.ready)return;r.ready=true;r.seed=uint256(word);emit Ready(id);\n    }\n    function cancel(uint256 id) external {\n        Request storage r=requests[id];if(r.consumer!=msg.sender)revert Unauthorized();\n        if(r.ready||r.delivered||r.cancelled||block.timestamp<r.createdAt+timeout)revert Unavailable();r.cancelled=true;emit Cancelled(id);\n    }\n    function advanceCancelled(uint256 limit) public {if(limit>100)revert Unavailable();for(uint256 i;i<limit&&nextDelivery<=requested&&requests[nextDelivery].cancelled;i++)nextDelivery++;}\n    function deliverNext() external nonReentrant {\n        advanceCancelled(100);uint256 id=nextDelivery;Request storage r=requests[id];if(!r.ready||r.delivered||r.cancelled)revert Unavailable();\n        r.delivered=true;nextDelivery++;IRandomnessConsumer(r.consumer).fulfillEntropy(id,r.seed);emit Delivered(id);\n    }\n    function retryCallback(uint256 id) external {Request storage r=requests[id];if(r.consumer==address(0)||r.cancelled||r.delivered)revert Unavailable();coordinator.retryCallback(provider,r.sequence);}\n}\n"},"v2/TraitInventory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/// @notice Bounded weighted sampling of unique approved artwork, not arbitrary new trait combinations.\n/// Caps are reserved at catalog registration, so a capped trait can never be oversubscribed at reveal.\ncontract TraitInventory is Ownable {\n    struct Rule {uint16 unlockAtGenerated;uint16 lockAfterGenerated;uint16 maxMints;bool defined;}\n    struct Bucket {uint16 unlockAt;uint16 lockAfter;uint16[3] weights;uint16[] artworks;}\n    mapping(uint8=>Rule) public rules;\n    mapping(uint8=>uint16) public reservedTraitCount;\n    mapping(uint8=>uint16) public mintedTraitCount;\n    mapping(uint256=>uint80) public dna;\n    mapping(uint80=>bool) public usedDNA;\n    mapping(uint256=>bool) public registeredArtwork;\n    mapping(uint256=>bool) public assignedArtwork;\n    Bucket[] private buckets;\n    uint256 public registered;uint256 public remaining;address public quacks;bool public frozen;\n    event TraitRuleConfigured(uint8 indexed traitId,uint16 unlockAt,uint16 lockAfter,uint16 maxMints);\n    event TraitConfigurationFrozen(address indexed quacks,uint256 count);\n    event ArtworkAssigned(uint256 indexed artwork,uint80 dna,uint8 mode,uint256 lifetimeGenerated);\n    error InvalidConfiguration();error Frozen();error Unauthorized();error NoEligibleArtwork();\n    constructor() Ownable(msg.sender){}\n    function configureRule(uint8 id,uint16 unlockAt,uint16 lockAfter,uint16 maxMints) external onlyOwner {\n        if(frozen||registered!=0) revert Frozen();\n        if(id==0||unlockAt>3333||lockAfter!=0&&lockAfter<unlockAt||maxMints==0) revert InvalidConfiguration();\n        rules[id]=Rule(unlockAt,lockAfter,maxMints,true);emit TraitRuleConfigured(id,unlockAt,lockAfter,maxMints);\n    }\n    function addBucket(uint16 unlockAt,uint16 lockAfter,uint16[3] calldata weights) external onlyOwner {\n        if(frozen) revert Frozen();\n        if(buckets.length>=64||unlockAt>3333||lockAfter!=0&&lockAfter<unlockAt||weights[0]==0||weights[1]==0||weights[2]==0) revert InvalidConfiguration();\n        buckets.push();Bucket storage b=buckets[buckets.length-1];b.unlockAt=unlockAt;b.lockAfter=lockAfter;b.weights=weights;\n    }\n    function addArtwork(uint256 bucket,uint16[] calldata ids,uint80[] calldata dnas) external onlyOwner {\n        if(frozen) revert Frozen();if(ids.length==0||ids.length>100||ids.length!=dnas.length||bucket>=buckets.length) revert InvalidConfiguration();\n        Bucket storage b=buckets[bucket];\n        for(uint256 i;i<ids.length;i++){\n            uint256 id=ids[i];uint80 value=dnas[i];\n            if(id==0||id>3333||registeredArtwork[id]||usedDNA[value]||value==0) revert InvalidConfiguration();\n            for(uint256 j;j<10;j++){\n                uint8 t=uint8(value>>(j*8));if(t==0)continue;Rule memory r=rules[t];\n                if(!r.defined||b.unlockAt<r.unlockAtGenerated||(r.lockAfterGenerated!=0&&(b.lockAfter==0||b.lockAfter>r.lockAfterGenerated))) revert InvalidConfiguration();\n                if(++reservedTraitCount[t]>r.maxMints) revert InvalidConfiguration();\n            }\n            registeredArtwork[id]=true;usedDNA[value]=true;dna[id]=value;b.artworks.push(uint16(id));registered++;remaining++;\n        }\n    }\n    function freezeTraitConfiguration(address nft) external onlyOwner {\n        if(frozen) revert Frozen();if(registered!=3333||nft.code.length==0) revert InvalidConfiguration();\n        quacks=nft;frozen=true;emit TraitConfigurationFrozen(nft,registered);\n    }\n    function bucketCount() external view returns(uint256){return buckets.length;}\n    function bucketInfo(uint256 id) external view returns(uint16,uint16,uint16[3] memory,uint256){Bucket storage b=buckets[id];return(b.unlockAt,b.lockAfter,b.weights,b.artworks.length);}\n    function eligibleWeight(uint256 generated,uint8 mode) public view returns(uint256 total){\n        if(mode>2) revert InvalidConfiguration();for(uint256 i;i<buckets.length;i++){Bucket storage b=buckets[i];if(generated>=b.unlockAt&&(b.lockAfter==0||generated<=b.lockAfter))total+=b.artworks.length*b.weights[mode];}\n    }\n    /// @notice True only when premium weights change the eligible distribution.\n    function hasModeAdvantage(uint256 generated,uint8 mode) public view returns(bool){\n        if(mode>2)revert InvalidConfiguration();if(mode==0)return false;\n        uint256 normal;uint256 boosted;\n        for(uint256 i;i<buckets.length;i++){\n            Bucket storage b=buckets[i];if(b.artworks.length==0||generated<b.unlockAt||(b.lockAfter!=0&&generated>b.lockAfter))continue;\n            if(normal==0){normal=b.weights[0];boosted=b.weights[mode];}\n            else if(normal*b.weights[mode]!=boosted*b.weights[0])return true;\n        }\n        return false;\n    }\n    function assign(uint256 seed,uint256 generated,uint8 mode) external returns(uint256 id){\n        if(msg.sender!=quacks||!frozen) revert Unauthorized();uint256 total=eligibleWeight(generated,mode);if(total==0) revert NoEligibleArtwork();\n        uint256 roll=uint256(keccak256(abi.encode(seed,\"bucket\")))%total;\n        for(uint256 i;i<buckets.length;i++){\n            Bucket storage b=buckets[i];if(generated<b.unlockAt||b.lockAfter!=0&&generated>b.lockAfter)continue;\n            uint256 weight=b.artworks.length*b.weights[mode];if(roll>=weight){roll-=weight;continue;}\n            uint256 index=uint256(keccak256(abi.encode(seed,\"artwork\")))%b.artworks.length;id=b.artworks[index];\n            b.artworks[index]=b.artworks[b.artworks.length-1];b.artworks.pop();remaining--;assignedArtwork[id]=true;\n            uint80 value=dna[id];for(uint256 j;j<10;j++){uint8 t=uint8(value>>(j*8));if(t!=0)mintedTraitCount[t]++;}\n            emit ArtworkAssigned(id,value,mode,generated);return id;\n        }\n        revert NoEligibleArtwork();\n    }\n}\n"},"v2/test/Fixtures.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Quacks} from \"../Quacks.sol\";\nimport {TraitInventory} from \"../TraitInventory.sol\";\nimport {IRandomnessConsumer} from \"../IRandomnessProvider.sol\";\nimport {BreadTradingHook} from \"../BreadTradingHook.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {SwapParams} from \"@uniswap/v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"@uniswap/v4-core/src/types/BalanceDelta.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract TestEntropyV2 {\n    uint256 public next;struct Request{address consumer;uint64 at;bool ready;bool done;uint256 seed;}\n    mapping(uint256=>Request)public requests;\n    function request(uint256) external returns(uint256 id){id=++next;requests[id]=Request(msg.sender,uint64(block.timestamp),false,false,0);}\n    function ready(uint256 id,uint256 seed) external {Request storage r=requests[id];require(!r.ready&&!r.done);r.ready=true;r.seed=seed;}\n    function deliver(uint256 id) external {Request storage r=requests[id];require(r.ready&&!r.done);r.done=true;IRandomnessConsumer(r.consumer).fulfillEntropy(id,r.seed);}\n    function cancel(uint256 id) external {Request storage r=requests[id];require(msg.sender==r.consumer&&!r.ready&&!r.done&&block.timestamp>=r.at+3 days);r.done=true;}\n}\ncontract TestQuacksV2 is Quacks {\n    constructor(address a,address b,address c)Quacks(a,b,c,3 days){}\n    function testAssign(uint256 n)external{for(uint256 i;i<n;i++)traits.assign(i,3333,0);}\n    function testAssignSeed(uint256 seed,uint256 progress,uint8 mode)external{traits.assign(seed,progress,mode);}\n}\ncontract TestRendererV2 {function tokenURI(uint256,bool,uint8,uint256)external pure returns(string memory){return \"fixture\";}function burnedTokenURI(uint256,uint256)external pure returns(string memory){return \"burned-fixture\";}}\ncontract TestGenerationDrawV2 {\n    function reserve(address q,uint256 id,uint256 seed) external returns(uint256){return Quacks(q).reserveGenesisArtwork(id,seed);}\n}\ncontract TestDrawNFT {\n    mapping(uint256=>address) public ownerOf;\n    mapping(uint256=>bool) public reserved;\n    function reserveGenesisArtwork(uint256 id,uint256) external returns(uint256){reserved[id]=true;return id;}\n    function mintGenesis(address to,uint256 id,uint256) external {require(ownerOf[id]==address(0));ownerOf[id]=to;}\n}\ncontract TestInventoryV2 is TraitInventory {\n    // Tiny inventory solely for boundary tests; production freeze still requires 3333 records.\n    function enableTinyFixture(address consumer) external {quacks=consumer;frozen=true;}\n    function testGenerationBatch(uint256 start,uint256 count) external {\n        for(uint256 i=start;i<start+count;i++){\n            uint256 progress=i<333?333:i+1;\n            uint256 id=this.assign(uint256(keccak256(abi.encode(i))),progress,0);\n            uint80 value=dna[id];\n            for(uint256 j;j<10;j++){uint8 t=uint8(value>>(j*8));if(t!=0)require(rules[t].unlockAtGenerated<=progress,\"Early trait\");}\n        }\n    }\n}\ncontract TestFeeManager {\n    receive() external payable{}\n    function take(Currency token,address to,uint256 amount)external {if(Currency.unwrap(token)==address(0)){(bool ok,)=to.call{value:amount}(\"\");require(ok);}else require(IERC20(Currency.unwrap(token)).transfer(to,amount));}\n    function swapHook(address hook,PoolKey calldata key,SwapParams calldata params,BalanceDelta delta)external returns(int128){(,int128 fee)=BreadTradingHook(hook).afterSwap(msg.sender,key,params,delta,\"\");return fee;}\n}\ncontract RejectNFTBuyer {\n    function execute(address target,bytes calldata data)external { (bool ok,bytes memory result)=target.call(data);if(!ok)assembly{revert(add(result,32),mload(result))} }\n}\n"},"v3/EntropyBoundaryFixtures.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {QuiverRecoveryEntropy} from \"../v2/QuiverRecoveryEntropy.sol\";\nimport {IRandomnessConsumer} from \"../v2/IRandomnessProvider.sol\";\ncontract BoundaryCoordinator {\n    uint64 public sequence;uint128 public fee;\n    function getFee(address)external view returns(uint128){return fee;}\n    function setFee(uint128 value)external{fee=value;}\n    function requestWithCallback(address,bytes32)external payable returns(uint64){require(msg.value==fee);return ++sequence;}\n    function send(address consumer,uint64 id,address provider,bytes32 seed)external{QuiverRecoveryEntropy(payable(consumer)).quiverCallback(id,provider,seed);}\n    function retryCallback(address,uint64)external pure{revert(\"No buffered callback\");}\n}\ncontract BoundaryConsumer is IRandomnessConsumer {\n    QuiverRecoveryEntropy public adapter;bool public fail;uint256 public delivered;uint256 public seed;\n    constructor(address value){adapter=QuiverRecoveryEntropy(payable(value));}\n    function request()external returns(uint256){return adapter.request(1);}\n    function cancel(uint256 id)external{adapter.cancel(id);}\n    function setFail(bool value)external{fail=value;}\n    function fulfillEntropy(uint256 id,uint256 value)external{require(msg.sender==address(adapter)&&!fail);delivered=id;seed=value;}\n}\n"},"v3/GenerativeTraits.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/// New combinations are rolled from individual traits. There is no artwork catalog.\ncontract GenerativeTraits is Ownable {\n    struct Trait {uint8 category;uint16 unlockAt;uint16 cap;uint16[3] weights;bool special;}\n    struct Exclusion {uint256 first;uint256 second;uint16 clearCategories;}\n    mapping(uint8=>Trait) public traits;\n    uint8[][10] private options;\n    uint16[10] public noneWeights;\n    Exclusion[] private exclusions;\n    mapping(uint8=>uint16) public mintedTraitCount;\n    mapping(uint80=>bool) public usedDNA;\n    uint256 public generated;address public quacks;bool public frozen;\n    uint8 public normalExpression;uint8 public skeletonBody;uint8 public normalBeak;\n    uint16 public constant OPTIONAL_MASK=1008; // slots 4..9\n    event ArtworkAssigned(uint256 indexed artwork,uint80 dna,uint8 mode,uint256 lifetimeGenerated);\n    error Unavailable();error Unauthorized();error DuplicateRetriesExhausted();\n    constructor() Ownable(msg.sender){}\n    function configureTraits(uint8[] calldata ids,Trait[] calldata defs) external onlyOwner {\n        if(frozen||ids.length!=defs.length)revert Unavailable();\n        for(uint256 i;i<ids.length;i++){uint8 id=ids[i];Trait memory t=defs[i];if(id==0||traits[id].cap!=0||t.category>9||t.cap==0||t.unlockAt>3333||t.weights[0]==0||t.weights[1]==0||t.weights[2]==0||t.special&&(t.category!=1||t.cap!=1))revert Unavailable();traits[id]=t;options[t.category].push(id);}\n    }\n    function configureRules(uint16[10] calldata none_,Exclusion[] calldata rules_,uint8 normal_,uint8 skeleton_,uint8 beak_) external onlyOwner {\n        if(frozen||exclusions.length!=0||traits[normal_].category!=3||traits[skeleton_].category!=1)revert Unavailable();\n        if(traits[beak_].category!=2||traits[beak_].cap<3333||traits[normal_].cap<3333)revert Unavailable();\n        noneWeights=none_;normalExpression=normal_;skeletonBody=skeleton_;normalBeak=beak_;\n        for(uint256 i;i<rules_.length;i++)exclusions.push(rules_[i]);\n    }\n    function freezeTraitConfiguration(address consumer) external onlyOwner {\n        if(frozen||consumer.code.length==0||normalExpression==0)revert Unavailable();\n        for(uint256 c;c<10;c++){if(options[c].length==0)revert Unavailable();if(c<4&&noneWeights[c]!=0)revert Unavailable();}\n        quacks=consumer;frozen=true;\n    }\n    function remaining() external view returns(uint256){return 3333-generated;}\n    function _available(uint8 id,uint256 progress) internal view returns(bool){Trait storage t=traits[id];return t.unlockAt<=progress&&mintedTraitCount[id]<t.cap;}\n    function _pick(uint256 seed,uint256 attempt,uint256 category,uint256 progress,uint8 mode) internal view returns(uint8){\n        uint256 total=noneWeights[category];uint8[] storage ids=options[category];\n        for(uint256 i;i<ids.length;i++)if(_available(ids[i],progress))total+=traits[ids[i]].weights[mode];\n        if(total==0)revert Unavailable();uint256 roll=uint256(keccak256(abi.encode(seed,attempt,category)))%total;\n        if(roll<noneWeights[category])return 0;roll-=noneWeights[category];\n        for(uint256 i;i<ids.length;i++){uint8 id=ids[i];if(!_available(id,progress))continue;uint256 w=traits[id].weights[mode];if(roll<w)return id;roll-=w;}\n        revert Unavailable();\n    }\n    function _combination(uint256 seed,uint256 attempt,uint256 progress,uint8 mode) internal view returns(uint80 dna){\n        uint8[10] memory chosen;\n        chosen[0]=_pick(seed,attempt,0,progress,mode);chosen[1]=_pick(seed,attempt,1,progress,mode);\n        if(!traits[chosen[1]].special){\n            for(uint256 c=2;c<10;c++)chosen[c]=_pick(seed,attempt,c,progress,mode);\n            // Preserve the art compatibility rules, in the same declared order.\n            for(uint256 i;i<exclusions.length;i++){\n                uint256 selected;for(uint256 c;c<10;c++)if(chosen[c]!=0)selected|=uint256(1)<<chosen[c];\n                Exclusion storage rule=exclusions[i];if(selected&rule.first!=0&&selected&rule.second!=0)for(uint256 c;c<10;c++)if(rule.clearCategories&(uint16(1)<<c)!=0)chosen[c]=0;\n            }\n            uint8[6] memory optional;uint256 count;\n            for(uint8 c=4;c<10;c++)if(chosen[c]!=0)optional[count++]=c;\n            // Unbiased category priority is derived separately from trait rolls.\n            for(uint256 i=count;i>1;i--){uint256 j=uint256(keccak256(abi.encode(seed,attempt,\"accessories\",i)))%i;(optional[i-1],optional[j])=(optional[j],optional[i-1]);}\n            for(uint256 i=3;i<count;i++)chosen[optional[i]]=0;\n            if(chosen[5]!=0||chosen[1]==skeletonBody)chosen[3]=normalExpression;\n            if(chosen[2]==0)chosen[2]=normalBeak;\n        }\n        for(uint256 c;c<10;c++)dna|=uint80(chosen[c])<<(8*c);\n    }\n    function hasModeAdvantage(uint256 progress,uint8 mode) external view returns(bool){\n        if(mode==0||mode>2||generated>=3333)return false;\n        for(uint256 c;c<10;c++){\n            uint256 normal=noneWeights[c];uint256 boosted=normal;\n            for(uint256 i;i<options[c].length;i++){uint8 id=options[c][i];if(!_available(id,progress))continue;Trait storage t=traits[id];if(normal==0){normal=t.weights[0];boosted=t.weights[mode];}else if(normal*t.weights[mode]!=boosted*t.weights[0])return true;}\n        }return false;\n    }\n    function assign(uint256 seed,uint256 progress,uint8 mode) external returns(uint256){\n        if(msg.sender!=quacks||!frozen)revert Unauthorized();if(mode>2||progress>3333||generated>=3333)revert Unavailable();\n        for(uint256 attempt;attempt<32;attempt++){\n            uint80 dna=_combination(seed,attempt,progress,mode);if(usedDNA[dna])continue;\n            usedDNA[dna]=true;generated++;for(uint256 c;c<10;c++){uint8 id=uint8(dna>>(8*c));if(id!=0)mintedTraitCount[id]++;}\n            emit ArtworkAssigned(dna,dna,mode,progress);return dna;\n        }revert DuplicateRetriesExhausted();\n    }\n}\n"},"v3/LayeredQuacksRenderer.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.28;\r\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport {Base64} from \"@openzeppelin/contracts/utils/Base64.sol\";\r\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\r\n\r\n/// Composes only the selected trait layers. No finished-duck images or external URLs.\r\ncontract LayeredQuacksRenderer is Ownable {\r\n    using Strings for uint256;\r\n    struct Part {uint16 asset;uint8 position;}\r\n    struct Appearance {Part[] parts;bytes metadata;}\r\n    address[] public pages;bytes public assetIndex;address public immutable eggs;\r\n    mapping(uint8=>Appearance) private appearances;\r\n    mapping(uint8=>uint16) public headphoneBodies;\r\n    uint8 public headphones;uint8 public skeleton;uint8 public normal;uint16 public socketAsset;\r\n    bool public frozen;\r\n    constructor(address[] memory pages_,bytes memory index_,address eggs_) Ownable(msg.sender){\r\n        require(index_.length%5==0&&eggs_.code.length>1);for(uint256 i;i<pages_.length;i++)require(pages_[i].code.length>1&&pages_[i].code.length<=24001);\r\n        pages=pages_;assetIndex=index_;eggs=eggs_;\r\n    }\r\n    function configureTrait(uint8 id,Part[] calldata parts,bytes calldata metadata_) external onlyOwner {\r\n        require(!frozen&&id!=0&&appearances[id].metadata.length==0&&parts.length>0&&parts.length<=2);\r\n        for(uint256 i;i<parts.length;i++){require(parts[i].asset>0&&uint256(parts[i].asset)*5<=assetIndex.length);appearances[id].parts.push(parts[i]);}\r\n        appearances[id].metadata=metadata_;\r\n    }\r\n    function configureOverrides(uint8 h,uint8 s,uint8 n,uint16 socket,uint8[] calldata bodies,uint16[] calldata assets) external onlyOwner {\r\n        require(!frozen&&bodies.length==assets.length);headphones=h;skeleton=s;normal=n;socketAsset=socket;\r\n        for(uint256 i;i<bodies.length;i++)headphoneBodies[bodies[i]]=assets[i];\r\n    }\r\n    function freeze() external onlyOwner {require(!frozen);frozen=true;}\r\n    function _read(address blob,uint256 offset,uint256 length) internal view returns(bytes memory result){require(offset+length+1<=blob.code.length);result=new bytes(length);assembly{extcodecopy(blob,add(result,32),add(offset,1),length)}}\r\n    function _u16(bytes memory b,uint256 i) internal pure returns(uint256){return uint8(b[i])*256+uint8(b[i+1]);}\r\n    function _png(uint16 asset) internal view returns(bytes memory){uint256 at=(uint256(asset)-1)*5;bytes memory idx=assetIndex;return _read(pages[uint8(idx[at])],_u16(idx,at+1),_u16(idx,at+3));}\r\n    function _image(bytes memory png) internal pure returns(bytes memory){return abi.encodePacked('<image width=\"32\" height=\"32\" style=\"image-rendering:pixelated\" href=\"data:image/png;base64,',Base64.encode(png),'\"/>');}\r\n    function _compose(uint80 dna) internal view returns(bytes memory svg,bytes memory attributes){\r\n        Part[20] memory parts;uint256 length;attributes='[';\r\n        uint8 body=uint8(dna>>8);bool headphone=uint8(dna>>48)==headphones;\r\n        for(uint256 c;c<10;c++){uint8 id=uint8(dna>>(8*c));if(id==0)continue;Appearance storage a=appearances[id];require(a.metadata.length>0);\r\n            attributes=bytes.concat(attributes,attributes.length==1?bytes(''):bytes(','),a.metadata);\r\n            for(uint256 j;j<a.parts.length;j++){Part memory part=a.parts[j];if(c==1&&headphone&&headphoneBodies[body]!=0)part.asset=headphoneBodies[body];if(c==3&&body==skeleton&&id==normal)part.asset=socketAsset;parts[length++]=part;}\r\n        }\r\n        for(uint256 i=1;i<length;i++){Part memory part=parts[i];uint256 j=i;while(j>0&&parts[j-1].position>part.position){parts[j]=parts[j-1];j--;}parts[j]=part;}\r\n        for(uint256 i;i<length;i++)svg=bytes.concat(svg,_image(_png(parts[i].asset)));\r\n    }\r\n    function _uri(uint256 id,bool revealed,uint8 day,uint256 value,bool burned) internal view returns(string memory){\r\n        require(frozen&&value<=type(uint80).max&&day<=7);bytes memory svg;bytes memory attrs;string memory name;\r\n        if(revealed){(svg,attrs)=_compose(uint80(value));name=string.concat('Quack #',id.toString());}\r\n        else{bytes memory pointer=_read(eggs,uint256(day)*4,4);svg=_image(_read(eggs,32+_u16(pointer,0),_u16(pointer,2)));attrs=bytes(string.concat('[{\"trait_type\":\"Incubation day\",\"value\":',uint256(day).toString(),'}'));name=string.concat('Quack #',id.toString());}\r\n        if(burned){svg=bytes.concat(svg,bytes('<path fill=\"#ff392e\" d=\"M1 30v-7h1v-3h1v2h1v2h1v2h1v4zM1 19h1v1H1zM3 18h1v1H3z\"/><path fill=\"#ff951c\" d=\"M2 30v-5h1v-2h1v3h1v4z\"/><path fill=\"#ffe84a\" d=\"M3 30v-4h1v4z\"/>'));attrs=bytes.concat(attrs,bytes(',{\"trait_type\":\"Status\",\"value\":\"Burned\"}'));}\r\n        attrs=bytes.concat(attrs,bytes(id<=333?',{\"trait_type\":\"Genesis\",\"value\":\"Yes\"}]':',{\"trait_type\":\"Genesis\",\"value\":\"No\"}]'));\r\n        svg=abi.encodePacked('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" shape-rendering=\"crispEdges\">',svg,'</svg>');\r\n        return string.concat('data:application/json;base64,',Base64.encode(abi.encodePacked('{\"name\":\"',name,'\",\"description\":\"Quacks. Traits generated and composed on-chain.\",\"image\":\"data:image/svg+xml;base64,',Base64.encode(svg),'\",\"attributes\":',attrs,'}')));\r\n    }\r\n    function tokenURI(uint256 id,bool revealed,uint8 day,uint256 dna) external view returns(string memory){return _uri(id,revealed,day,dna,false);}\r\n    function burnedTokenURI(uint256 id,uint256 dna) external view returns(string memory){return _uri(id,dna!=0,7,dna,true);}\r\n}\r\n"},"v3/RandomnessProbe.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {IRandomnessProvider,IRandomnessConsumer} from \"../v2/IRandomnessProvider.sol\";\n/// Testnet probe of the real adapter boundary. No NFT or token value is held.\ncontract RandomnessProbe is IRandomnessConsumer {\n    address public immutable owner=msg.sender;\n    IRandomnessProvider public immutable entropy;\n    mapping(uint256=>bool) public received;\n    mapping(uint256=>uint256) public result;\n    event ProbeResult(uint256 indexed requestId,uint256 seed);\n    constructor(address adapter){entropy=IRandomnessProvider(adapter);}\n    function request(uint256 context)external returns(uint256){require(msg.sender==owner);return entropy.request(context);}\n    function cancel(uint256 id)external{require(msg.sender==owner);entropy.cancel(id);}\n    function fulfillEntropy(uint256 id,uint256 seed)external{require(msg.sender==address(entropy)&&!received[id]);received[id]=true;result[id]=seed;emit ProbeResult(id,seed);}\n}\n"},"v3/ReviewConsumer.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\ninterface IGenerativeReview {function assign(uint256,uint256,uint8) external returns(uint256);}\n/// Only the harness batches calls. Every trait roll is in GenerativeTraits.assign.\ncontract ReviewConsumer {\n    IGenerativeReview public immutable generator;\n    constructor(address g){generator=IGenerativeReview(g);}\n    function run(uint256[] calldata seeds,uint16[] calldata progress,uint8[] calldata modes) external {\n        require(seeds.length==progress.length&&seeds.length==modes.length);\n        for(uint256 i;i<seeds.length;i++)generator.assign(seeds[i],progress[i],modes[i]);\n    }\n}\n"},"v3/RoyaltyFixtures.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {RoyaltyQuacks} from \"./RoyaltyQuacks.sol\";\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {IERC2981} from \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\n\n/// Local-only payment fixture, NOT a production marketplace or registry.\ncontract TestRoyaltyValidator {\n    address public immutable admin=msg.sender;\n    mapping(address=>bool) public staking;\n    bytes32 private activeTransfer;\n    bool public giftEnabled;\n    function setStaking(address value,bool enabled)external{require(msg.sender==admin);staking[value]=enabled;}\n    function setGifts(bool enabled)external{require(msg.sender==admin);giftEnabled=enabled;}\n    function validateTransfer(address caller,address from,address to,uint256 id)external view{\n        bool stake=staking[caller]&&(caller==to||caller==from);\n        require(stake||(giftEnabled&&caller==from)||activeTransfer==keccak256(abi.encode(msg.sender,caller,from,to,id)),\"Royalty authorization missing\");\n    }\n    function buy(address nft,address seller,uint256 id,uint256 price,uint256 royaltyPayment)external payable {\n        require(activeTransfer==bytes32(0)&&msg.value==price,\"Invalid sale\");\n        (address receiver,uint256 royalty)=IERC2981(nft).royaltyInfo(id,price);\n        require(royaltyPayment==royalty,\"5% royalty required\");\n        activeTransfer=keccak256(abi.encode(nft,address(this),seller,msg.sender,id));\n        IERC721(nft).transferFrom(seller,msg.sender,id);\n        delete activeTransfer;\n        (bool paid,)=receiver.call{value:royalty}(\"\");require(paid);\n        (bool rest,)=seller.call{value:price-royalty}(\"\");require(rest);\n    }\n}\n/// Exposes only fixture minting to test all inherited transfer paths.\ncontract TestRoyaltyQuacks is RoyaltyQuacks {\n    constructor(address a,address b,address c)RoyaltyQuacks(a,b,c,3 days){}\n    function fixtureMint(address to,uint256 id)external{_safeMint(to,id);revealed[id]=true;}\n    function fixtureBurn(uint256 id)external{require(ownerOf(id)==msg.sender);_destroy(id);}\n}\n"},"v3/RoyaltyQuacks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Quacks} from \"../v2/Quacks.sol\";\n\ninterface IQuacksTransferValidator {\n    function validateTransfer(address caller,address from,address to,uint256 tokenId) external view;\n}\ninterface IQuacksRoyaltyStaking {function quacks() external view returns(address);function bread() external view returns(address);}\ninterface IQuacksCreatorToken {\n    event TransferValidatorUpdated(address oldValidator,address newValidator);\n    function getTransferValidator() external view returns(address);\n    function getTransferValidationFunction() external view returns(bytes4,bool);\n    function setTransferValidator(address validator) external;\n}\n\n/// Creator-token hook documented by OpenSea. The production validator and its\n/// marketplace authorization policy MUST be verified on the deployment chain.\n/// ERC-2981 alone reports 5%; the validator authorizes royalty-compliant sales.\ncontract RoyaltyQuacks is Quacks,IQuacksCreatorToken {\n    uint96 public constant ROYALTY_BPS=500;\n    address private transferValidator;\n    address public royaltyStaking;\n    event RoyaltyStakingConfigured(address indexed staking);\n    event RoyaltyPolicyFrozen(address indexed validator,address indexed receiver,uint96 bps);\n    constructor(address token,address config,address generator,uint256 timeout)\n        Quacks(token,config,generator,timeout) {}\n\n    function getTransferValidator() external view returns(address){return transferValidator;}\n    function getTransferValidationFunction() external pure returns(bytes4,bool){\n        return (IQuacksTransferValidator.validateTransfer.selector,true);\n    }\n    function setTransferValidator(address validator) external onlyOwner {\n        if(rendererFrozen||validator.code.length==0||validator==address(this))revert InvalidConfiguration();\n        emit TransferValidatorUpdated(transferValidator,validator);transferValidator=validator;\n    }\n    /// Fixed custody exception: only the bound staking contract can move tokens\n    /// into or out of its own custody. It cannot authorize marketplace transfers.\n    function setRoyaltyStaking(address staking) external onlyOwner {\n        if(rendererFrozen||royaltyStaking!=address(0)||staking.code.length==0)revert InvalidConfiguration();\n        if(IQuacksRoyaltyStaking(staking).quacks()!=address(this)||IQuacksRoyaltyStaking(staking).bread()!=address(bread))revert InvalidConfiguration();\n        royaltyStaking=staking;emit RoyaltyStakingConfigured(staking);\n    }\n    function freezeRenderer() public override onlyOwner {\n        if(transferValidator.code.length==0)revert InvalidConfiguration();\n        super.freezeRenderer();\n        emit RoyaltyPolicyFrozen(transferValidator,economics.treasury(),ROYALTY_BPS);\n    }\n    function _update(address to,uint256 id,address auth) internal override returns(address){\n        if(!rendererFrozen||transferValidator.code.length==0)revert InvalidConfiguration();\n        address from=_ownerOf(id);\n        // Every real transfer is validated, including owner calls and both\n        // safeTransferFrom overloads. Only mint and burn bypass sale validation.\n        bool custody=msg.sender==royaltyStaking&&(from==royaltyStaking||to==royaltyStaking);\n        if(from!=address(0)&&to!=address(0)&&!custody)\n            IQuacksTransferValidator(transferValidator).validateTransfer(msg.sender,from,to,id);\n        return super._update(to,id,auth);\n    }\n    function supportsInterface(bytes4 id) public view override returns(bool){\n        return id==type(IQuacksCreatorToken).interfaceId||super.supportsInterface(id);\n    }\n}\n"},"v4/ModeEggRenderer.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\nimport {Base64} from \"@openzeppelin/contracts/utils/Base64.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\n\ninterface IApprovedDuckRenderer {\n    function frozen() external view returns(bool);\n    function tokenURI(uint256,bool,uint8,uint256) external view returns(string memory);\n    function burnedTokenURI(uint256,uint256) external view returns(string memory);\n}\ninterface IQuacksEggMode {\n    function eggs(uint256) external view returns(uint64,uint64,uint8,bool,bool,uint256);\n}\n\n/// @notice Immutable egg-mode artwork adapter for the next deployment.\n/// Revealed/burned ducks retain the approved renderer's exact metadata and artwork.\ncontract ModeEggRenderer {\n    using Strings for uint256;\n    IApprovedDuckRenderer public immutable ducks;\n    address public immutable eggs;\n    bool public constant frozen=true;\n    error InvalidEggArt();\n    constructor(address duckRenderer,address eggBlob){\n        require(duckRenderer.code.length>0&&IApprovedDuckRenderer(duckRenderer).frozen());\n        ducks=IApprovedDuckRenderer(duckRenderer);eggs=eggBlob;\n        if(eggBlob.code.length<102||eggBlob.code.length>24001||bytes4(_read(0,4))!=bytes4(\"QEG2\"))revert InvalidEggArt();\n        for(uint256 i;i<24;i++){bytes memory ptr=_read(4+i*4,4);uint256 size=_u16(ptr,2);if(size<8||101+_u16(ptr,0)+size>eggBlob.code.length)revert InvalidEggArt();}\n    }\n    function _read(uint256 offset,uint256 length) internal view returns(bytes memory out){\n        if(offset+length+1>eggs.code.length)revert InvalidEggArt();out=new bytes(length);address blob=eggs;\n        assembly{extcodecopy(blob,add(out,32),add(offset,1),length)}\n    }\n    function _u16(bytes memory b,uint256 i) internal pure returns(uint256){return uint8(b[i])*256+uint8(b[i+1]);}\n    function eggTokenURI(uint256 id,uint8 day,uint8 mode) public view returns(string memory){\n        require(day<=7&&mode<=2);\n        bytes memory ptr=_read(4+(uint256(mode)*8+day)*4,4);\n        bytes memory png=_read(100+_u16(ptr,0),_u16(ptr,2));\n        string memory name=mode==0?\"Normal\":mode==1?\"Lucky\":\"Golden\";\n        bytes memory svg=abi.encodePacked('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" shape-rendering=\"crispEdges\"><image width=\"32\" height=\"32\" style=\"image-rendering:pixelated\" href=\"data:image/png;base64,',Base64.encode(png),'\"/></svg>');\n        return string.concat('data:application/json;base64,',Base64.encode(abi.encodePacked('{\"name\":\"Quack #',id.toString(),'\",\"description\":\"Quacks. Traits generated and composed on-chain.\",\"image\":\"data:image/svg+xml;base64,',Base64.encode(svg),'\",\"attributes\":[{\"trait_type\":\"Incubation day\",\"value\":',uint256(day).toString(),'}, {\"trait_type\":\"Egg mode\",\"value\":\"',name,'\"},{\"trait_type\":\"Genesis\",\"value\":\"',id<=333?'Yes':'No','\"}]}')));\n    }\n    function tokenURI(uint256 id,bool revealed,uint8 day,uint256 dna) external view returns(string memory){\n        if(revealed)return ducks.tokenURI(id,true,day,dna);\n        // Read the recorded purchase mode from the NFT, never a frontend guess.\n        (,,uint8 mode,,,)=IQuacksEggMode(msg.sender).eggs(id);\n        return eggTokenURI(id,day,mode);\n    }\n    function burnedTokenURI(uint256 id,uint256 dna) external view returns(string memory){return ducks.burnedTokenURI(id,dna);}\n}\n"},"@uniswap/v4-core/src/types/PoolKey.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n    /// @notice The lower currency of the pool, sorted numerically\n    Currency currency0;\n    /// @notice The higher currency of the pool, sorted numerically\n    Currency currency1;\n    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000\n    uint24 fee;\n    /// @notice Ticks that involve positions must be a multiple of tick spacing\n    int24 tickSpacing;\n    /// @notice The hooks of the pool\n    IHooks hooks;\n}\n"},"@uniswap/v4-core/src/types/PoolOperation.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n    // the lower and upper tick of the position\n    int24 tickLower;\n    int24 tickUpper;\n    // how to modify the liquidity\n    int256 liquidityDelta;\n    // a value to set if you want unique liquidity positions at the same range\n    bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n    /// Whether to swap token0 for token1 or vice versa\n    bool zeroForOne;\n    /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n    int256 amountSpecified;\n    /// The sqrt price at which, if reached, the swap will stop executing\n    uint160 sqrtPriceLimitX96;\n}\n"}},"settings":{"evmVersion":"paris","optimizer":{"enabled":true,"runs":200},"outputSelection":{"*":{"*":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences"]}}}}