Skip to content
Verified contractPartialMIT

TaxRWAERC20LaunchpadFactory

Address0xca111dcdd2ce924c3378d6514fdcbc46217bca16
Balance

0 ETH

 

Transactions

9

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,350,846
Creation transaction
0x75635467ea…664130950a
Libraries
src/tax/TaxLaunchOperations.sol:TaxLaunchOperations0x5331…2aa967

65 files

src/tax/TaxRWAERC20LaunchpadFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";

import {TaxERC20FactoryBase} from "./TaxERC20FactoryBase.sol";
import {IRWAQuoteRegistry} from "../interfaces/IRWAQuoteRegistry.sol";
import {TaxLaunchOperations} from "./TaxLaunchOperations.sol";

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

import {TaxLaunchHook} from "./TaxLaunchHook.sol";
import {TaxLaunchTokenDeployer} from "./TaxLaunchTokenDeployer.sol";

/// @title TaxRWAERC20LaunchpadFactory
/// @notice Managed ERC20 launch factory serving standard and RWA routes on Base, Monad and Robinhood.
contract TaxRWAERC20LaunchpadFactory is TaxERC20FactoryBase {
    uint256 public constant MAX_QUOTE_BATCH_SIZE = TaxSuiteConstants.MAX_BATCH_SIZE;
    uint16 public constant TOKEN_ADDRESS_SUFFIX = 0xcccc;

    address public priceUpdater;
    bool public launchCreationEnabled;
    mapping(address quoteToken => uint64 revision) public quoteRevision;

    event PriceUpdaterUpdated(address indexed previousPriceUpdater, address indexed newPriceUpdater);
    event LaunchCreationEnabledUpdated(bool creationEnabled);

    error UnauthorizedPriceUpdater();
    error StaleQuoteRevision(address quoteToken, uint64 expectedRevision, uint64 actualRevision);
    error QuoteBatchOutOfBounds();
    error QuoteBatchNotSorted();
    error MisalignedStartTick();
    error InvalidQuoteToken();
    error InvalidTokenAddressSuffix(address predictedToken);
    error LaunchCreationDisabled();

    modifier onlyOwnerOrPriceUpdater() {
        if (msg.sender != owner() && msg.sender != priceUpdater) revert UnauthorizedPriceUpdater();
        _;
    }

    constructor(
        IPoolManager poolManagerAddress,
        TaxLaunchHook launchHook,
        TaxLaunchTokenDeployer launchTokenDeployer,
        TaxDividendDeployer launchDividendDeployer,
        FactoryInitialization memory initialFactoryConfiguration
    )
        TaxERC20FactoryBase(
            poolManagerAddress, launchHook, launchTokenDeployer, launchDividendDeployer, initialFactoryConfiguration
        )
    {}

    function registerQuote(address quoteToken, int24 startTickToken0Frame) public onlyOwner nonReentrant {
        _registerQuote(quoteToken, startTickToken0Frame);
        _bumpConfigVersion();
    }

    function batchRegisterQuotes(IRWAQuoteRegistry.QuoteRegistration[] calldata quoteRegistrations)
        external
        onlyOwner
        nonReentrant
    {
        _validateBatchLength(quoteRegistrations.length);
        address previousQuoteToken;
        for (uint256 i = 0; i < quoteRegistrations.length; i++) {
            IRWAQuoteRegistry.QuoteRegistration calldata registration = quoteRegistrations[i];
            if (i != 0) _validateSortedAddress(previousQuoteToken, registration.quoteToken);
            _registerQuote(registration.quoteToken, registration.startTickToken0Frame);
            previousQuoteToken = registration.quoteToken;
        }
        _bumpConfigVersion();
    }

    function setQuoteStartTick(address quoteToken, int24 newStartTickToken0Frame, uint64 expectedRevision)
        external
        onlyOwnerOrPriceUpdater
        nonReentrant
    {
        _setQuoteStartTick(quoteToken, newStartTickToken0Frame, expectedRevision);
    }

    function batchSetQuoteStartTicks(IRWAQuoteRegistry.QuoteTickUpdate[] calldata quoteTickUpdates)
        external
        onlyOwnerOrPriceUpdater
        nonReentrant
    {
        _validateBatchLength(quoteTickUpdates.length);
        address previousQuoteToken;
        for (uint256 i = 0; i < quoteTickUpdates.length; i++) {
            IRWAQuoteRegistry.QuoteTickUpdate calldata update = quoteTickUpdates[i];
            if (i != 0) _validateSortedAddress(previousQuoteToken, update.quoteToken);
            _setQuoteStartTick(update.quoteToken, update.newStartTickToken0Frame, update.expectedRevision);
            previousQuoteToken = update.quoteToken;
        }
    }

    function unregisterQuote(address quoteToken) public onlyOwner nonReentrant {
        _unregisterQuote(quoteToken);
        _bumpConfigVersion();
    }

    function batchUnregisterQuotes(address[] calldata quoteTokens) external onlyOwner nonReentrant {
        _validateBatchLength(quoteTokens.length);
        address previousQuoteToken;
        for (uint256 i = 0; i < quoteTokens.length; i++) {
            address quoteToken = quoteTokens[i];
            if (i != 0) _validateSortedAddress(previousQuoteToken, quoteToken);
            _unregisterQuote(quoteToken);
            previousQuoteToken = quoteToken;
        }
        _bumpConfigVersion();
    }

    function setPriceUpdater(address newPriceUpdater) external onlyOwner nonReentrant {
        address previousPriceUpdater = priceUpdater;
        if (newPriceUpdater == previousPriceUpdater) return;
        priceUpdater = newPriceUpdater;
        _bumpConfigVersion();
        emit PriceUpdaterUpdated(previousPriceUpdater, newPriceUpdater);
    }

    function setLaunchCreationEnabled(bool creationEnabled) external onlyOwner nonReentrant {
        if (creationEnabled == launchCreationEnabled) return;
        if (creationEnabled) _requireLaunchCreationWiring();
        launchCreationEnabled = creationEnabled;
        _bumpConfigVersion();
        emit LaunchCreationEnabledUpdated(creationEnabled);
    }

    function renounceOwnership() public override onlyOwner {
        if (launchCreationEnabled || priceUpdater != address(0)) revert UnsafeOwnershipRenunciation();
        super.renounceOwnership();
    }

    function launchTokenInitCodeHash(LaunchParams calldata launchParams) external view returns (bytes32 initCodeHash) {
        return TaxLaunchOperations.tokenInitCodeHash(tokenDeployer, launchParams, launchSupply, hook);
    }

    function _beforeCreateLaunch(LaunchParams calldata launchParams) internal view override {
        super._beforeCreateLaunch(launchParams);
        if (!launchCreationEnabled) revert LaunchCreationDisabled();
        _validateQuoteStartTick(_quoteConfig[launchParams.quoteToken].startTickToken0Frame);
    }

    function _registerQuote(address quoteToken, int24 startTickToken0Frame) internal {
        if (quoteToken != address(0) && quoteToken.code.length == 0) revert InvalidQuoteToken();
        if (_quoteConfig[quoteToken].registered) revert QuoteAlreadyRegistered();
        _validateQuoteStartTick(startTickToken0Frame);

        uint8 quoteDecimals = quoteToken == address(0) ? 18 : IERC20Metadata(quoteToken).decimals();
        _quoteConfig[quoteToken] =
            QuoteConfig({registered: true, quoteDecimals: quoteDecimals, startTickToken0Frame: startTickToken0Frame});
        uint64 revision = _nextQuoteRevision(quoteToken);
        emit QuoteRegistered(quoteToken, quoteDecimals, startTickToken0Frame, revision);
    }

    function _setQuoteStartTick(address quoteToken, int24 newStartTickToken0Frame, uint64 expectedRevision) internal {
        QuoteConfig storage config = _quoteConfig[quoteToken];
        if (!config.registered) revert QuoteNotRegistered();

        uint64 actualRevision = quoteRevision[quoteToken];
        if (expectedRevision != actualRevision) {
            revert StaleQuoteRevision(quoteToken, expectedRevision, actualRevision);
        }
        _validateQuoteStartTick(newStartTickToken0Frame);
        int24 previousStartTickToken0Frame = config.startTickToken0Frame;
        if (newStartTickToken0Frame == previousStartTickToken0Frame) return;

        config.startTickToken0Frame = newStartTickToken0Frame;
        uint64 revision = _nextQuoteRevision(quoteToken);
        emit QuoteStartTickUpdated(quoteToken, previousStartTickToken0Frame, newStartTickToken0Frame, revision);
    }

    function _unregisterQuote(address quoteToken) internal {
        if (!_quoteConfig[quoteToken].registered) revert QuoteNotRegistered();
        delete _quoteConfig[quoteToken];
        uint64 revision = _nextQuoteRevision(quoteToken);
        emit QuoteUnregistered(quoteToken, revision);
    }

    function _nextQuoteRevision(address quoteToken) internal returns (uint64 revision) {
        revision = quoteRevision[quoteToken] + 1;
        quoteRevision[quoteToken] = revision;
    }

    function _validateQuoteStartTick(int24 startTickToken0Frame) internal view {
        _validateStartTickFrame(startTickToken0Frame);
        if (startTickToken0Frame % tickSpacing != 0) revert MisalignedStartTick();
    }

    function _validateBatchLength(uint256 length) internal pure {
        if (length == 0 || length > MAX_QUOTE_BATCH_SIZE) revert QuoteBatchOutOfBounds();
    }

    function _validateSortedAddress(address previousQuoteToken, address currentQuoteToken) internal pure {
        if (uint160(currentQuoteToken) <= uint160(previousQuoteToken)) revert QuoteBatchNotSorted();
    }

    function _validatePredictedToken(address predictedToken) internal pure override {
        if ((uint160(predictedToken) & 0xffff) != TOKEN_ADDRESS_SUFFIX) {
            revert InvalidTokenAddressSuffix(predictedToken);
        }
    }

    function _requireLaunchCreationWiring() internal view override {
        super._requireLaunchCreationWiring();
        if (tokenDeployer.factory() != address(this) || dividendDeployer.factory() != address(this)) {
            revert InvalidConfig();
        }
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

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

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

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

lib/v4-core/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/v4-core/lib/openzeppelin-contracts/contracts/proxy/Clones.sol

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

pragma solidity ^0.8.20;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev A clone instance deployment failed.
     */
    error ERC1167FailedCreateClone();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

lib/v4-core/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/v4-core/src/interfaces/IExtsload.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

lib/v4-core/src/interfaces/IExttload.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

lib/v4-core/src/interfaces/IHooks.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @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)
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

lib/v4-core/src/interfaces/IPoolManager.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    struct ModifyLiquidityParams {
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // how to modify the liquidity
        int256 liquidityDelta;
        // a value to set if you want unique liquidity positions at the same range
        bytes32 salt;
    }

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    struct SwapParams {
        /// Whether to swap token0 for token1 or vice versa
        bool zeroForOne;
        /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
        int256 amountSpecified;
        /// The sqrt price at which, if reached, the swap will stop executing
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// 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
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

lib/v4-core/src/interfaces/IProtocolFees.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

lib/v4-core/src/interfaces/callback/IUnlockCallback.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
    /// @param data The data that was passed to the call to unlock
    /// @return Any data that you want to be returned from the unlock call
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

lib/v4-core/src/interfaces/external/IERC20Minimal.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

lib/v4-core/src/interfaces/external/IERC6909Claims.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

lib/v4-core/src/libraries/BitMath.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

lib/v4-core/src/libraries/CurrencyReserves.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

import {Currency} from "../types/Currency.sol";
import {CustomRevert} from "./CustomRevert.sol";

library CurrencyReserves {
    using CustomRevert for bytes4;

    /// bytes32(uint256(keccak256("ReservesOf")) - 1)
    bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
    /// bytes32(uint256(keccak256("Currency")) - 1)
    bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;

    function getSyncedCurrency() internal view returns (Currency currency) {
        assembly ("memory-safe") {
            currency := tload(CURRENCY_SLOT)
        }
    }

    function resetCurrency() internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, 0)
        }
    }

    function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            tstore(RESERVES_OF_SLOT, value)
        }
    }

    function getSyncedReserves() internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(RESERVES_OF_SLOT)
        }
    }
}

lib/v4-core/src/libraries/CustomRevert.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

lib/v4-core/src/libraries/FixedPoint96.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

lib/v4-core/src/libraries/FullMath.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}

lib/v4-core/src/libraries/Hooks.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);

    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;

    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;

    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;

    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;

    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;

    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;

    struct Permissions {
        bool beforeInitialize;
        bool afterInitialize;
        bool beforeAddLiquidity;
        bool afterAddLiquidity;
        bool beforeRemoveLiquidity;
        bool afterRemoveLiquidity;
        bool beforeSwap;
        bool afterSwap;
        bool beforeDonate;
        bool afterDonate;
        bool beforeSwapReturnDelta;
        bool afterSwapReturnDelta;
        bool afterAddLiquidityReturnDelta;
        bool afterRemoveLiquidityReturnDelta;
    }

    /// @notice Thrown if the address will not lead to the specified hook calls being called
    /// @param hooks The address of the hooks contract
    error HookAddressNotValid(address hooks);

    /// @notice Hook did not return its selector
    error InvalidHookResponse();

    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails
    error HookCallFailed();

    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
    error HookDeltaExceedsSwapAmount();

    /// @notice Utility function intended to be used in hook constructors to ensure
    /// the deployed hooks address causes the intended hooks to be called
    /// @param permissions The hooks that are intended to be called
    /// @dev permissions param is memory as the function will be called from constructors
    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
        if (
            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                || permissions.afterRemoveLiquidityReturnDelta
                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) {
            HookAddressNotValid.selector.revertWith(address(self));
        }
    }

    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
    /// @param self The hook to verify
    /// @param fee The fee of the pool the hook is used with
    /// @return bool True if the hook address is valid
    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
        {
            return false;
        }
        if (
            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) return false;

        // If there is no hook contract set, then fee cannot be dynamic
        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
        return address(self) == address(0)
            ? !fee.isDynamicFee()
            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
    }

    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
    /// @return result The complete data returned by the hook
    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
        }
        // Revert with FailedHookCall, containing any error message to bubble up
        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

        // The call was successful, fetch the returned data
        assembly ("memory-safe") {
            // allocate result byte array from the free memory pointer
            result := mload(0x40)
            // store new free memory pointer at the end of the array padded to 32 bytes
            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
            // store length in memory
            mstore(result, returndatasize())
            // copy return data to result
            returndatacopy(add(result, 0x20), 0, returndatasize())
        }

        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
            InvalidHookResponse.selector.revertWith();
        }
    }

    /// @notice performs a hook call using the given calldata on the given hook
    /// @return int256 The delta returned by the hook
    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
        bytes memory result = callHook(self, data);

        // If this hook wasn't meant to return something, default to 0 delta
        if (!parseReturn) return 0;

        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta
        if (result.length != 64) InvalidHookResponse.selector.revertWith();
        return result.parseReturnDelta();
    }

    /// @notice modifier to prevent calling a hook if they initiated the action
    modifier noSelfCall(IHooks self) {
        if (msg.sender != address(self)) {
            _;
        }
    }

    /// @notice calls beforeInitialize hook if permissioned and validates return value
    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
        }
    }

    /// @notice calls afterInitialize hook if permissioned and validates return value
    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
        }
    }

    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
    function beforeModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        IPoolManager.ModifyLiquidityParams memory params,
        bytes calldata hookData
    ) internal noSelfCall(self) {
        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
        }
    }

    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value
    function afterModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        IPoolManager.ModifyLiquidityParams memory params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);

        callerDelta = delta;
        if (params.liquidityDelta > 0) {
            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        } else {
            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        }
    }

    /// @notice calls beforeSwap hook if permissioned and validates return value
    function beforeSwap(IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData)
        internal
        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
    {
        amountToSwap = params.amountSpecified;
        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);

        if (self.hasPermission(BEFORE_SWAP_FLAG)) {
            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));

            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
            if (result.length != 96) InvalidHookResponse.selector.revertWith();

            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();

            // skip this logic for the case where the hook return is 0
            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());

                // any return in unspecified is passed to the afterSwap hook for handling
                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();

                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
                if (hookDeltaSpecified != 0) {
                    bool exactInput = amountToSwap < 0;
                    amountToSwap += hookDeltaSpecified;
                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
                        HookDeltaExceedsSwapAmount.selector.revertWith();
                    }
                }
            }
        }
    }

    /// @notice calls afterSwap hook if permissioned and validates return value
    function afterSwap(
        IHooks self,
        PoolKey memory key,
        IPoolManager.SwapParams memory params,
        BalanceDelta swapDelta,
        bytes calldata hookData,
        BeforeSwapDelta beforeSwapHookReturn
    ) internal returns (BalanceDelta, BalanceDelta) {
        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);

        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();

        if (self.hasPermission(AFTER_SWAP_FLAG)) {
            hookDeltaUnspecified += self.callHookWithReturnDelta(
                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
            ).toInt128();
        }

        BalanceDelta hookDelta;
        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);

            // the caller has to pay for (or receive) the hook's delta
            swapDelta = swapDelta - hookDelta;
        }
        return (swapDelta, hookDelta);
    }

    /// @notice calls beforeDonate hook if permissioned and validates return value
    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(BEFORE_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    /// @notice calls afterDonate hook if permissioned and validates return value
    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}

lib/v4-core/src/libraries/LPFeeLibrary.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @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
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @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
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;

    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
    uint24 public constant MAX_LP_FEE = 1000000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
    /// @param self The fee to check
    /// @return bool True of the fee is valid
    function isValid(uint24 self) internal pure returns (bool) {
        return self <= MAX_LP_FEE;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    function validate(uint24 self) internal pure {
        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
    }

    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
    function getInitialLPFee(uint24 self) internal pure returns (uint24) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicFee()) return 0;
        self.validate();
        return self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & REMOVE_OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}

lib/v4-core/src/libraries/Lock.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
    // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
    bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;

    function unlock() internal {
        assembly ("memory-safe") {
            // unlock
            tstore(IS_UNLOCKED_SLOT, true)
        }
    }

    function lock() internal {
        assembly ("memory-safe") {
            tstore(IS_UNLOCKED_SLOT, false)
        }
    }

    function isUnlocked() internal view returns (bool unlocked) {
        assembly ("memory-safe") {
            unlocked := tload(IS_UNLOCKED_SLOT)
        }
    }
}

lib/v4-core/src/libraries/NonzeroDeltaCount.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
    // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
    bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
        0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;

    function read() internal view returns (uint256 count) {
        assembly ("memory-safe") {
            count := tload(NONZERO_DELTA_COUNT_SLOT)
        }
    }

    function increment() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := add(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }

    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
    function decrement() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := sub(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }
}

lib/v4-core/src/libraries/ParseBytes.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            selector := mload(add(result, 0x20))
        }
    }

    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
        assembly ("memory-safe") {
            lpFee := mload(add(result, 0x60))
        }
    }

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}

lib/v4-core/src/libraries/SafeCast.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

lib/v4-core/src/libraries/TickMath.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    using CustomRevert for bytes4;

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

            if (msb >= 128) r = price >> (msb - 127);
            else r = price << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

lib/v4-core/src/libraries/TransientStateLibrary.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";

/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
    /// @notice returns the reserves for the synced currency
    /// @param manager The pool manager contract.

    /// @return uint256 The reserves of the currency.
    /// @dev returns 0 if the reserves are not synced or value is 0.
    /// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
    function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
        if (getSyncedCurrency(manager).isAddressZero()) return 0;
        return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
    }

    function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
        return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
    }

    /// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
    function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
        return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
    }

    /// @notice Get the current delta for a caller in the given currency
    /// @param target The credited account address
    /// @param currency The currency for which to lookup the delta
    function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
        bytes32 key;
        assembly ("memory-safe") {
            mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            key := keccak256(0, 64)
        }
        return int256(uint256(manager.exttload(key)));
    }

    /// @notice Returns whether the contract is unlocked or not
    function isUnlocked(IPoolManager manager) internal view returns (bool) {
        return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
    }
}

lib/v4-core/src/types/BalanceDelta.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {SafeCast} from "../libraries/SafeCast.sol";

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

lib/v4-core/src/types/BeforeSwapDelta.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

lib/v4-core/src/types/Currency.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

lib/v4-core/src/types/PoolId.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

lib/v4-core/src/types/PoolKey.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @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
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

lib/v4-core/test/utils/CurrencySettler.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Currency} from "../../src/types/Currency.sol";
import {IERC20Minimal} from "../../src/interfaces/external/IERC20Minimal.sol";
import {IPoolManager} from "../../src/interfaces/IPoolManager.sol";

/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// To settle a positive delta (a credit to the user), a user may take or mint.
/// To settle a negative delta (a debt on the user), a user make transfer or burn to pay off a debt.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
    /// @notice Settle (pay) a currency to the PoolManager
    /// @param currency Currency to settle
    /// @param manager IPoolManager to settle to
    /// @param payer Address of the payer, the token sender
    /// @param amount Amount to send
    /// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
    function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
        // for native currencies or burns, calling sync is not required
        // short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
        if (burn) {
            manager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            manager.settle{value: amount}();
        } else {
            manager.sync(currency);
            if (payer != address(this)) {
                IERC20Minimal(Currency.unwrap(currency)).transferFrom(payer, address(manager), amount);
            } else {
                IERC20Minimal(Currency.unwrap(currency)).transfer(address(manager), amount);
            }
            manager.settle();
        }
    }

    /// @notice Take (receive) a currency from the PoolManager
    /// @param currency Currency to take
    /// @param manager IPoolManager to take from
    /// @param recipient Address of the recipient, the token receiver
    /// @param amount Amount to receive
    /// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
    function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
        claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
    }
}

lib/v4-core/test/utils/LiquidityAmounts.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import "../../src/libraries/FullMath.sol";
import "../../src/libraries/FixedPoint96.sol";

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x, "liquidity overflow");
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
        internal
        pure
        returns (uint128 liquidity)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
        return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
        internal
        pure
        returns (uint128 liquidity)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtPriceX96 A sqrt price representing the current pool prices
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    function getLiquidityForAmounts(
        uint160 sqrtPriceX96,
        uint160 sqrtPriceAX96,
        uint160 sqrtPriceBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    function getAmount0ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
        internal
        pure
        returns (uint256 amount0)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        return FullMath.mulDiv(
            uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96
        ) / sqrtPriceAX96;
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount of token1
    function getAmount1ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
        internal
        pure
        returns (uint256 amount1)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
    }

    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtPriceX96 A sqrt price representing the current pool prices
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function getAmountsForLiquidity(
        uint160 sqrtPriceX96,
        uint160 sqrtPriceAX96,
        uint160 sqrtPriceBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        }
    }
}

src/AnnouncementRegistry.sol

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

/// @title AnnouncementRegistry
interface ICreatorAuthority {
    function currentCreatorOf(address token) external view returns (address currentCreator);
}

/// @notice Optional, zero-live-roles creator announcements feed. The factory registers canonical launch tokens,
///         while creator authorization is resolved dynamically so rights transfers require no registry update.
contract AnnouncementRegistry {
    address public immutable factory;

    mapping(address token => bool registered) public isTokenRegistered;
    mapping(address token => mapping(bytes32 announcementId => bool used)) public isAnnouncementIdUsed;

    error NotFactory();
    error NotCreator();
    error AlreadyRegistered();
    error IdAlreadyUsed();
    error ZeroAddress();

    event TokenRegistered(address indexed token);
    event AnnouncementPosted(
        address indexed token,
        address indexed creator,
        bytes32 indexed announcementId,
        string description,
        string announcementURI
    );

    constructor(address factoryAddress) {
        if (factoryAddress == address(0) || factoryAddress.code.length == 0) revert ZeroAddress();
        factory = factoryAddress;
    }

    function registerToken(address token) external {
        if (msg.sender != factory) revert NotFactory();
        if (token == address(0)) revert ZeroAddress();
        if (isTokenRegistered[token]) revert AlreadyRegistered();
        isTokenRegistered[token] = true;
        emit TokenRegistered(token);
    }

    function postAnnouncement(
        address token,
        bytes32 announcementId,
        string calldata description,
        string calldata announcementURI
    ) external {
        if (!isTokenRegistered[token] || msg.sender != ICreatorAuthority(factory).currentCreatorOf(token)) {
            revert NotCreator();
        }
        if (isAnnouncementIdUsed[token][announcementId]) revert IdAlreadyUsed();
        isAnnouncementIdUsed[token][announcementId] = true;
        emit AnnouncementPosted(token, msg.sender, announcementId, description, announcementURI);
    }
}

src/FeeEscrow.sol

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

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/// @title FeeEscrow
/// @notice Pull-based ledger of trade fees. The launch hook takes each fee as an ERC-6909 claim minted to
///         this contract (balance-safe: no real transfer happens mid-swap) and records the per-recipient
///         split here. On `claimFor` or `claimTo`, this contract redeems the claim to real tokens.
///         Keeping fee custody in this minimal contract (not the hook or factory) shrinks the fund-holding
///         surface, and the pull model means one reverting recipient can never block distribution.
/// @dev    `currency == address(0)` denotes native currency (Uniswap v4's native sentinel). The only writer is
///         the hook; redemption is the only PoolManager interaction and nets to zero (burn 6909, take real).
contract FeeEscrow is IUnlockCallback, ReentrancyGuard {
    IPoolManager public immutable poolManager;

    /// @notice The only address allowed to credit balances: the launch hook.
    address public immutable hook;

    /// @notice recipient => currency (address(0) = native currency) => claimable balance.
    mapping(address recipient => mapping(address currency => uint256 claimableAmount)) public owed;

    error NotHook();
    error NotPoolManager();
    error NothingToClaim();
    error ZeroAddress();
    error ZeroDestination();

    event Credited(address indexed recipient, address indexed currency, uint256 amount);
    event Claimed(address indexed recipient, address indexed currency, address indexed destination, uint256 amount);

    constructor(IPoolManager poolManagerAddress, address launchHook) {
        if (
            address(poolManagerAddress) == address(0) || address(poolManagerAddress).code.length == 0
                || launchHook == address(0) || launchHook.code.length == 0
        ) revert ZeroAddress();
        poolManager = poolManagerAddress;
        hook = launchHook;
    }

    /// @notice Record a recipient's share. The matching ERC-6909 claim must already have been minted here by
    ///         the hook in the same transaction, so the redeemable balance always covers the sum of `owed`.
    function credit(address recipient, address currency, uint256 amount) external {
        if (msg.sender != hook) revert NotHook();
        if (recipient == address(0)) revert ZeroAddress();
        if (amount == 0) return;
        owed[recipient][currency] += amount;
        emit Credited(recipient, currency, amount);
    }

    /// @notice Redeem and pay out everything owed to `recipient` in `currency`. Permissionless to trigger,
    ///         but funds always go to `recipient`. CEI: the balance is zeroed before the redemption.
    function claimFor(address recipient, address currency) external nonReentrant {
        _redeemTo(recipient, currency, recipient);
    }

    /// @notice Redeem the caller's own balance to a chosen address. Escape hatch for a recipient that cannot
    ///         receive a currency directly (e.g. a contract with no payable `receive` on a native-currency pool):
    ///         only the recipient can redirect its own balance, so this adds no new authority.
    function claimTo(address currency, address destination) external nonReentrant {
        if (destination == address(0)) revert ZeroDestination();
        _redeemTo(msg.sender, currency, destination);
    }

    /// @dev The single redemption path: zero the owner's balance (CEI), then unlock to pay `destination`.
    function _redeemTo(address balanceOwner, address currency, address destination) internal {
        uint256 amount = owed[balanceOwner][currency];
        if (amount == 0) revert NothingToClaim();
        owed[balanceOwner][currency] = 0;
        poolManager.unlock(abi.encode(destination, currency, amount));
        emit Claimed(balanceOwner, currency, destination, amount);
    }

    /// @notice Only reachable as the callback to this contract's own `unlock` (the PoolManager calls back the
    ///         address that called `unlock`), so `onlyPoolManager` fully gates it. Burns our ERC-6909 claim
    ///         (a positive currency delta) and takes the real tokens out to the recipient (netting to zero).
    function unlockCallback(bytes calldata callbackData) external returns (bytes memory result) {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        (address destination, address currencyAddress, uint256 amount) =
            abi.decode(callbackData, (address, address, uint256));
        Currency currency = Currency.wrap(currencyAddress);
        poolManager.burn(address(this), currency.toId(), amount);
        poolManager.take(currency, destination, amount);
        return "";
    }
}

src/base/BaseHook.sol

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

import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol";

/// @title BaseHook
/// @notice Minimal Uniswap v4 hook base. It (1) verifies at construction that the deployed address
///         encodes exactly the declared permission bits, (2) restricts every callback to the
///         PoolManager, and (3) reverts on any callback the concrete hook does not implement
///         (fail-closed: a stray permission bit becomes a DoS, never a fund risk).
/// @dev    A minimal in-repo base (the project vendors only v4-core, not v4-periphery). Concrete hooks
///         override only the `_`-prefixed internals they enable.
abstract contract BaseHook is IHooks {
    error NotPoolManager();
    error HookNotImplemented();

    IPoolManager public immutable poolManager;

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
        Hooks.validateHookPermissions(IHooks(address(this)), getHookPermissions());
    }

    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    /// @notice The hooks this contract implements; its return MUST match the address's low 14 bits.
    function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);

    // --- IHooks: each callback is PoolManager-only and dispatches to an overridable internal ---

    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _beforeInitialize(sender, key, sqrtPriceX96);
    }

    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _afterInitialize(sender, key, sqrtPriceX96, tick);
    }

    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeAddLiquidity(sender, key, params, hookData);
    }

    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
    }

    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeRemoveLiquidity(sender, key, params, hookData);
    }

    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
    }

    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
        return _beforeSwap(sender, key, params, hookData);
    }

    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, int128) {
        return _afterSwap(sender, key, params, delta, hookData);
    }

    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeDonate(sender, key, amount0, amount1, hookData);
    }

    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _afterDonate(sender, key, amount0, amount1, hookData);
    }

    function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    function _beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    function _afterAddLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    function _beforeRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        bytes calldata
    ) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    function _afterRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    function _beforeSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        revert HookNotImplemented();
    }

    function _afterSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, BalanceDelta, bytes calldata)
        internal
        virtual
        returns (bytes4, int128)
    {
        revert HookNotImplemented();
    }

    function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }
}

src/interfaces/ICreatorRightsReceiver.sol

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

interface ICreatorRightsReceiver {
    function onCreatorRightsReceived(address previousCreator, address token, bytes calldata callbackData)
        external
        payable
        returns (bytes4 selector);
}

src/interfaces/ILaunchBuyAdapter.sol

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

import {PoolKey} from "v4-core/src/types/PoolKey.sol";

/// @title ILaunchBuyAdapter
/// @notice Common immutable wiring and execution surface for one atomic launch-buy router binding.
interface ILaunchBuyAdapter {
    struct LaunchBuyRequest {
        address originalCreator;
        address launchToken;
        address quoteToken;
        PoolKey poolKey;
        address fundingToken;
        uint256 amountIn;
        uint256 minAmountOut;
        uint64 deadline;
        bytes routeData;
    }

    function factory() external view returns (address launchFactory);
    function launchHook() external view returns (address hookAddress);
    function poolManager() external view returns (address manager);
    function router() external view returns (address underlyingRouter);
    function swapCaller() external view returns (address callbackCaller);

    function executeLaunchBuy(LaunchBuyRequest calldata request) external payable returns (uint256 amountOut);
}

src/interfaces/ILaunchTokenMetadata.sol

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

interface ILaunchTokenMetadata {
    function updateName(string calldata newName) external;
    function updateSymbol(string calldata newSymbol) external;
    function updateContractURI(string calldata newContractURI) external;
    function updateExtraMetadata(string calldata metadataKey, string calldata metadataValue) external;
}

src/interfaces/IRWAQuoteRegistry.sol

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

/// @notice Common quote-management ABI shared by the managed ERC20 and B20 launch factories.
interface IRWAQuoteRegistry {
    struct QuoteRegistration {
        address quoteToken;
        int24 startTickToken0Frame;
    }

    struct QuoteTickUpdate {
        address quoteToken;
        int24 newStartTickToken0Frame;
        uint64 expectedRevision;
    }

    function MAX_QUOTE_BATCH_SIZE() external view returns (uint256 maximumBatchSize);
    function nativeLaunchFee() external view returns (uint256 launchFee);
    function priceUpdater() external view returns (address updater);
    function launchCreationEnabled() external view returns (bool creationEnabled);
    function quoteConfig(address quoteToken)
        external
        view
        returns (bool registered, uint8 quoteDecimals, int24 startTickToken0Frame);
    function quoteRevision(address quoteToken) external view returns (uint64 revision);
    function registerQuote(address quoteToken, int24 startTickToken0Frame) external;
    function batchRegisterQuotes(QuoteRegistration[] calldata quoteRegistrations) external;
    function setQuoteStartTick(address quoteToken, int24 newStartTickToken0Frame, uint64 expectedRevision) external;
    function batchSetQuoteStartTicks(QuoteTickUpdate[] calldata quoteTickUpdates) external;
    function unregisterQuote(address quoteToken) external;
    function batchUnregisterQuotes(address[] calldata quoteTokens) external;
    function setNativeLaunchFee(uint256 newNativeLaunchFee) external;
    function setPriceUpdater(address newPriceUpdater) external;
    function setLaunchCreationEnabled(bool creationEnabled) external;
}

src/tax/LaunchConsent.sol

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

import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {TaxFeeMath} from "./TaxFeeMath.sol";
import {ILaunchConsent} from "./interfaces/ILaunchConsent.sol";

/// @notice Lets an integrator contract refuse a launch that names it, and records a launch that it accepted.
/// @dev The question is a gas-limited static call, so an integrator cannot change state, cannot make a
///      launch expensive, and cannot return more than one word to the caller. Only the exact reject word
///      blocks, so an integrator can block only the launches that chose to name it. Only the exact accept
///      word is recorded. No answer, for any reason, lets the launch proceed without a record.
library LaunchConsent {
    using PoolIdLibrary for PoolKey;

    // forge-lint: disable-next-line(unsafe-typecast) a tag is the leading four bytes of its hash by definition
    bytes4 internal constant REJECTED = bytes4(keccak256("LAUNCH_REJECTED"));
    bytes4 internal constant ACCEPTED = ILaunchConsent.launchConsent.selector;
    uint256 internal constant GAS = 50_000;
    /// @dev EIP-150 forwards at most 63/64 of the remaining gas. The margin covers the call itself.
    uint256 private constant MINIMUM_GAS_BEFORE_CALL = GAS + GAS / 63 + 3_000;

    error IntegratorRejectedLaunch(address integrator);
    error InsufficientGasForLaunchConsent();

    event LaunchConsented(PoolId indexed poolId, address indexed integrator);

    /// @param consented The caller's record of pools whose named integrator accepted the launch.
    function requireConsent(
        mapping(PoolId poolId => bool accepted) storage consented,
        PoolKey calldata poolKey,
        bool tokenIsCurrency0,
        address integrator,
        address creator,
        bool antiSnipeEnabled,
        TaxFeeMath.TaxConfiguration calldata taxConfiguration
    ) internal {
        if (integrator.code.length == 0) return;
        address token = Currency.unwrap(poolKey.currency1);
        address quoteToken = Currency.unwrap(poolKey.currency0);
        if (tokenIsCurrency0) (token, quoteToken) = (quoteToken, token);
        bool accepted = requireConsentFor(
            integrator, ILaunchConsent.LaunchContext(token, quoteToken, creator, antiSnipeEnabled, taxConfiguration)
        );
        if (!accepted) return;
        PoolId poolId = poolKey.toId();
        consented[poolId] = true;
        emit LaunchConsented(poolId, integrator);
    }

    /// @return accepted True only when the integrator answered with the exact accept word.
    function requireConsentFor(address integrator, ILaunchConsent.LaunchContext memory context)
        internal
        view
        returns (bool accepted)
    {
        if (integrator.code.length == 0) return false;
        bytes memory payload = abi.encodeCall(ILaunchConsent.launchConsent, (context));
        // A caller must not be able to starve a rejecting integrator of gas and launch anyway.
        if (gasleft() < MINIMUM_GAS_BEFORE_CALL) revert InsufficientGasForLaunchConsent();
        bool answered;
        bytes32 word;
        assembly ("memory-safe") {
            let ok := staticcall(GAS, integrator, add(payload, 0x20), mload(payload), 0x00, 0x20)
            answered := and(ok, eq(returndatasize(), 0x20))
            word := mload(0x00)
        }
        if (!answered) return false;
        if (word == bytes32(REJECTED)) revert IntegratorRejectedLaunch(integrator);
        return word == bytes32(ACCEPTED);
    }
}

src/tax/TaxDividend.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";
import {ITaxDividendClaimHelper} from "./interfaces/ITaxDividendClaimHelper.sol";

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {TransientStateLibrary} from "v4-core/src/libraries/TransientStateLibrary.sol";
import {FeeEscrow} from "../FeeEscrow.sol";

interface ITaxDividendWrappedNative {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
}

/// @notice Per-launch rewards using the reviewed Flap pending-balance and reward-debt accounting.
/// @dev The fixed owner is the suite factory. Emergency withdrawal deliberately may remove unpaid backing.
///      Upstream reference and adaptation details are in contracts/reference/flap/.
contract TaxDividend is Initializable, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using TransientStateLibrary for IPoolManager;

    uint256 internal constant MAGNITUDE = 2 ** 128;
    uint256 public constant MAX_BATCH_SIZE = TaxSuiteConstants.MAX_BATCH_SIZE;
    address public constant BURN_SINK = TaxSuiteConstants.BURN_SINK;
    address public immutable wrappedNative;
    address public immutable claimHelper;

    struct Initialization {
        address factory;
        address taxToken;
        address quoteToken;
        address hook;
        FeeEscrow feeEscrow;
        uint256 minimumDividendHolding;
        address[] defaultExclusions;
    }

    struct UserInfo {
        uint256 share;
        uint256 rewardDebt;
        /// @dev Settled old-balance earnings; live share accrual is added by withdrawableDividendOf.
        uint256 pendingBalance;
    }

    address private _owner;
    address public rewardToken;
    address public taxToken;
    address public quoteToken;
    address public hook;
    FeeEscrow public feeEscrow;
    IPoolManager public poolManager;
    uint256 public minimumDividendHolding;
    uint256 internal magnifiedDividendPerShare;
    uint256 public totalShares;
    uint256 public totalDividendsAllocated;
    uint256 public totalDividendsWithdrawn;
    uint256 public totalDividendFeesAccrued;
    uint256 public totalBackingReplenished;
    mapping(address holder => UserInfo info) public userInfo;
    mapping(address holder => uint256 amount) public withdrawnDividends;
    mapping(address holder => bool excluded) public excludedFromDividends;
    mapping(address holder => bool excluded) public mandatoryExclusion;
    mapping(address holder => address receiver) internal _dividendReceiver;
    address private _recoveryRecipient;
    uint8 private _recoveryCallbacks;

    error Unauthorized();
    error InvalidConfiguration();
    error InvalidBatch();
    error MandatoryExclusion();
    error AlreadyExcluded();
    error NotExcluded();
    error PoolManagerUnlocked();
    error InsufficientAssetBalance();
    error NoEligibleDividendShares();
    error InsufficientRewardBacking(uint256 required, uint256 available);

    event OwnershipInitialized(address indexed factory);
    event DividendShareChanged(address indexed taxToken, address indexed holder, uint256 share, uint256 totalShares);
    event DividendPendingBalanceChanged(address indexed taxToken, address indexed holder, uint256 pendingBalance);
    event DividendRewardDebtChanged(address indexed taxToken, address indexed holder, uint256 rewardDebt);
    event DividendsAllocated(address indexed taxToken, uint256 amount, uint256 magnifiedDividendPerShare);
    event DividendPaid(address indexed taxToken, address indexed holder, address indexed receiver, uint256 amount);
    event DividendReceiverSet(
        address indexed taxToken, address indexed holder, address receiver, address previousReceiver
    );
    event DividendAddressExcluded(address indexed taxToken, address indexed holder);
    event DividendAddressUnexcluded(address indexed taxToken, address indexed holder);
    event DividendFeeAccrued(address indexed taxToken, uint256 amount, uint256 totalAccrued);
    event VoluntaryDividendDeposited(address indexed depositor, uint256 amount);
    event DividendBackingReplenished(address indexed funder, uint256 amount);
    event EmergencyWithdrawal(address indexed asset, address indexed recipient, uint256 amount);

    constructor(address wrappedNativeAddress, address dividendClaimHelper) {
        if (wrappedNativeAddress == address(0) || wrappedNativeAddress.code.length == 0) revert InvalidConfiguration();
        if (dividendClaimHelper.code.length == 0) revert InvalidConfiguration();
        wrappedNative = wrappedNativeAddress;
        claimHelper = dividendClaimHelper;
        _disableInitializers();
    }

    modifier onlyOwner() {
        if (msg.sender != _owner) revert Unauthorized();
        _;
    }

    function owner() public view returns (address) {
        return _owner;
    }

    function initialize(Initialization calldata configuration) external initializer nonReentrant {
        if (
            msg.sender != configuration.factory || configuration.factory.code.length == 0
                || configuration.taxToken.code.length == 0 || configuration.hook.code.length == 0
                || address(configuration.feeEscrow).code.length == 0
                || configuration.feeEscrow.hook() != configuration.hook
                || ITaxDividendClaimHelper(claimHelper).factory() != configuration.factory
                || ITaxDividendClaimHelper(claimHelper).hook() != configuration.hook
                || configuration.defaultExclusions.length > MAX_BATCH_SIZE
        ) revert InvalidConfiguration();
        uint256 supply = IERC20(configuration.taxToken).totalSupply();
        if (supply == 0 || supply >= MAGNITUDE || configuration.minimumDividendHolding > supply) {
            revert InvalidConfiguration();
        }
        address reward = _rewardTokenForQuote(configuration.quoteToken);
        if (reward.code.length == 0 || reward == configuration.taxToken) revert InvalidConfiguration();
        _owner = configuration.factory;
        taxToken = configuration.taxToken;
        quoteToken = configuration.quoteToken;
        rewardToken = reward;
        hook = configuration.hook;
        feeEscrow = configuration.feeEscrow;
        poolManager = configuration.feeEscrow.poolManager();
        minimumDividendHolding = configuration.minimumDividendHolding;
        _excludeMandatory(address(0));
        _excludeMandatory(BURN_SINK);
        _excludeMandatory(address(this));
        _excludeMandatory(taxToken);
        _excludeMandatory(_owner);
        _excludeMandatory(hook);
        _excludeMandatory(address(feeEscrow));
        _excludeMandatory(address(poolManager));
        _excludeMandatory(claimHelper);
        for (uint256 i; i < configuration.defaultExclusions.length; ++i) {
            address account = configuration.defaultExclusions[i];
            if (!excludedFromDividends[account]) {
                excludedFromDividends[account] = true;
                emit DividendAddressExcluded(taxToken, account);
            }
        }
        emit OwnershipInitialized(_owner);
    }

    /// @notice Record the bound token's raw holder balance; eligibility is applied internally.
    function setShare(address holder, uint256 share) external {
        if (msg.sender != taxToken) revert Unauthorized();
        if (_reentrancyGuardEntered()) {
            address expectedHolder = _recoveryRecipient;
            if (_recoveryCallbacks == 2) expectedHolder = address(this);
            if (_recoveryCallbacks == 0 || holder != expectedHolder) revert ReentrancyGuardReentrantCall();
            --_recoveryCallbacks;
            if (share != IERC20(taxToken).balanceOf(holder)) revert InvalidConfiguration();
            _updateShare(holder, share);
            return;
        }
        _setShareGuarded(holder, share);
    }

    function _setShareGuarded(address holder, uint256 share) private nonReentrant {
        _updateShare(holder, share);
    }

    function _updateShare(address holder, uint256 share) private {
        if (excludedFromDividends[holder]) return;
        if (share < minimumDividendHolding) share = 0;
        _setShare(holder, share);
    }

    function refreshShares(address[] calldata holders) external onlyOwner nonReentrant {
        if (holders.length > MAX_BATCH_SIZE) revert InvalidBatch();
        for (uint256 i; i < holders.length; ++i) {
            _refreshShare(holders[i]);
        }
    }

    function excludeAddress(address holder) external onlyOwner nonReentrant {
        if (excludedFromDividends[holder]) revert AlreadyExcluded();
        _setShare(holder, 0);
        excludedFromDividends[holder] = true;
        emit DividendAddressExcluded(taxToken, holder);
    }

    function unexcludeAddress(address holder) external onlyOwner nonReentrant {
        if (mandatoryExclusion[holder]) revert MandatoryExclusion();
        if (!excludedFromDividends[holder]) revert NotExcluded();
        excludedFromDividends[holder] = false;
        _refreshShare(holder);
        emit DividendAddressUnexcluded(taxToken, holder);
    }

    function setDividendReceiver(address holder, address receiver) external onlyOwner nonReentrant {
        if (holder == address(0)) revert InvalidConfiguration();
        address previous = _dividendReceiver[holder];
        _dividendReceiver[holder] = receiver;
        emit DividendReceiverSet(taxToken, holder, receiver, previous);
    }

    function receiverOf(address holder) public view returns (address receiver) {
        receiver = _dividendReceiver[holder];
        if (receiver == address(0)) receiver = holder;
    }

    function notifyDividendFee(uint256 amount) external nonReentrant {
        if (msg.sender != hook) revert Unauthorized();
        if (amount == 0) return;
        if (totalShares == 0) revert NoEligibleDividendShares();
        totalDividendFeesAccrued += amount;
        emit DividendFeeAccrued(taxToken, amount, totalDividendFeesAccrued);
        _allocate(amount);
    }

    function pendingDividendFunding() public view returns (uint256) {
        return feeEscrow.owed(address(this), quoteToken);
    }

    /// @notice Accounting backing, including unredeemed claims; external transfers may still fail.
    function availableRewardBacking() public view returns (uint256) {
        return _heldRewardBacking() + pendingDividendFunding();
    }

    /// @notice Conservative accounting backing, including allocation rounding residue; not an enumerable claim sum.
    function requiredRewardBacking() public view returns (uint256) {
        return totalDividendsAllocated - totalDividendsWithdrawn;
    }

    function rewardBackingDeficit() external view returns (uint256) {
        uint256 backing = requiredRewardBacking();
        uint256 balance = availableRewardBacking();
        if (backing > balance) return backing - balance;
        return 0;
    }

    function depositDividends(uint256 amount) external nonReentrant returns (bool success) {
        _requireSettled();
        if (amount == 0 || totalShares == 0) return false;
        uint256 received = _receiveReward(amount);
        if (received == 0) return false;
        _allocate(received);
        emit VoluntaryDividendDeposited(msg.sender, received);
        return true;
    }

    /// @notice Restore withdrawn backing without creating new dividend entitlements.
    function replenishBacking(uint256 amount) external nonReentrant returns (uint256 received) {
        _requireSettled();
        if (amount == 0) return 0;
        received = _receiveReward(amount);
        totalBackingReplenished += received;
        emit DividendBackingReplenished(msg.sender, received);
    }

    function withdrawDividends() external nonReentrant returns (bool paid) {
        return _withdrawDividendOfUser(msg.sender, true);
    }

    function withdrawDividendsFor(address holder, bool unwrapWrappedNative) external nonReentrant returns (bool paid) {
        return _withdrawDividendOfUser(holder, unwrapWrappedNative);
    }

    /// @notice Recorded unpaid entitlement, including amounts temporarily blocked by exclusion.
    function withdrawableDividendOf(address holder) public view returns (uint256 amount) {
        UserInfo storage info = userInfo[holder];
        uint256 accrued = _accruedFor(info.share, magnifiedDividendPerShare);
        amount = info.pendingBalance;
        if (accrued > info.rewardDebt) amount += accrued - info.rewardDebt;
    }

    function accumulativeDividendOf(address holder) public view returns (uint256) {
        return withdrawableDividendOf(holder) + withdrawnDividends[holder];
    }

    function getMagnifiedDividendPerShare() public view returns (uint256) {
        return magnifiedDividendPerShare;
    }

    /// @notice Fixed-owner administrative withdrawal; amount zero selects the full held asset balance.
    /// @dev May remove unpaid reward backing. Recorded entitlements and allocation counters do not change.
    function emergencyWithdraw(address asset, uint256 amount, address recipient) external onlyOwner nonReentrant {
        if (recipient == address(0)) revert InvalidConfiguration();
        uint256 balance;
        if (asset == address(0)) balance = address(this).balance;
        else balance = IERC20(asset).balanceOf(address(this));
        if (amount == 0) amount = balance;
        if (amount > balance) revert InsufficientAssetBalance();
        if (asset == address(0)) {
            Address.sendValue(payable(recipient), amount);
        } else if (asset == taxToken) {
            // Only this transfer's authenticated sender/recipient notifications may enter the held guard.
            _recoveryRecipient = recipient;
            _recoveryCallbacks = 2;
            if (recipient == address(this)) _recoveryCallbacks = 1;
            IERC20(asset).safeTransfer(recipient, amount);
            if (_recoveryCallbacks != 0) revert ReentrancyGuardReentrantCall();
            delete _recoveryRecipient;
        } else {
            IERC20(asset).safeTransfer(recipient, amount);
        }
        emit EmergencyWithdrawal(asset, recipient, amount);
    }

    function _heldRewardBacking() internal view returns (uint256 balance) {
        balance = IERC20(rewardToken).balanceOf(address(this));
        if (quoteToken == address(0)) balance += address(this).balance;
    }

    function _rewardTokenForQuote(address quote) internal view virtual returns (address) {
        if (quote == address(0)) return wrappedNative;
        return quote;
    }

    function _ensureClaimBacking(uint256 amount) internal {
        if (_heldRewardBacking() < amount && pendingDividendFunding() != 0) {
            feeEscrow.claimFor(address(this), quoteToken);
        }
        uint256 balance = IERC20(rewardToken).balanceOf(address(this));
        if (quoteToken == address(0)) {
            if (balance < amount) {
                uint256 nativeAmount = Math.min(address(this).balance, amount - balance);
                if (nativeAmount != 0) {
                    ITaxDividendWrappedNative(wrappedNative).deposit{value: nativeAmount}();
                    balance = IERC20(rewardToken).balanceOf(address(this));
                }
            }
        }
        if (balance < amount) revert InsufficientRewardBacking(amount, balance);
    }

    function _allocate(uint256 amount) internal {
        magnifiedDividendPerShare += Math.mulDiv(amount, MAGNITUDE, totalShares);
        totalDividendsAllocated += amount;
        emit DividendsAllocated(taxToken, amount, magnifiedDividendPerShare);
    }

    function _receiveReward(uint256 amount) internal returns (uint256) {
        IERC20 reward = IERC20(rewardToken);
        uint256 beforeBalance = reward.balanceOf(address(this));
        reward.safeTransferFrom(msg.sender, address(this), amount);
        return reward.balanceOf(address(this)) - beforeBalance;
    }

    function _requireSettled() internal view {
        if (poolManager.isUnlocked()) revert PoolManagerUnlocked();
    }

    function _excludeMandatory(address holder) internal {
        mandatoryExclusion[holder] = true;
        excludedFromDividends[holder] = true;
        emit DividendAddressExcluded(taxToken, holder);
    }

    function _refreshShare(address holder) internal {
        if (excludedFromDividends[holder]) return;
        uint256 share = IERC20(taxToken).balanceOf(holder);
        _updateShare(holder, share);
    }

    function _accruedFor(uint256 share, uint256 mdps) internal pure returns (uint256) {
        return Math.mulDiv(share, mdps, MAGNITUDE);
    }

    function _debtFor(uint256 share, uint256 mdps) internal pure returns (uint256) {
        return Math.mulDiv(share, mdps, MAGNITUDE, Math.Rounding.Ceil);
    }

    function _setShare(address holder, uint256 newShare) internal {
        UserInfo storage info = userInfo[holder];
        uint256 currentShare = info.share;
        if (newShare == currentShare) return;
        uint256 mdps = magnifiedDividendPerShare;
        uint256 currentDebt;
        if (currentShare != 0) currentDebt = info.rewardDebt;
        if (currentShare > 0) {
            uint256 accrued = _accruedFor(currentShare, mdps);
            if (accrued > currentDebt) {
                info.pendingBalance += accrued - currentDebt;
                emit DividendPendingBalanceChanged(taxToken, holder, info.pendingBalance);
            }
        }
        if (newShare > currentShare) totalShares += newShare - currentShare;
        else totalShares -= currentShare - newShare;
        info.share = newShare;
        uint256 newDebt = _debtFor(newShare, mdps);
        if (newDebt != currentDebt) {
            info.rewardDebt = newDebt;
            emit DividendRewardDebtChanged(taxToken, holder, newDebt);
        }
        emit DividendShareChanged(taxToken, holder, newShare, totalShares);
    }

    function _withdrawDividendOfUser(address holder, bool unwrapWrappedNative) internal returns (bool paid) {
        _requireClaimAuthorization(holder);
        _requireSettled();
        if (excludedFromDividends[holder]) return false;
        uint256 amount = withdrawableDividendOf(holder);
        if (amount == 0) return false;
        address receiver = receiverOf(holder);
        _ensureClaimBacking(amount);
        UserInfo storage info = userInfo[holder];
        uint256 newDebt = _debtFor(info.share, magnifiedDividendPerShare);
        if (newDebt != info.rewardDebt) {
            info.rewardDebt = newDebt;
            emit DividendRewardDebtChanged(taxToken, holder, newDebt);
        }
        if (info.pendingBalance != 0) {
            info.pendingBalance = 0;
            emit DividendPendingBalanceChanged(taxToken, holder, 0);
        }
        withdrawnDividends[holder] += amount;
        totalDividendsWithdrawn += amount;
        _payReward(receiver, amount, unwrapWrappedNative);
        emit DividendPaid(taxToken, holder, receiver, amount);
        return true;
    }

    function _payReward(address receiver, uint256 amount, bool unwrapWrappedNative) internal virtual {
        if (rewardToken == wrappedNative && unwrapWrappedNative) {
            ITaxDividendWrappedNative(wrappedNative).withdraw(amount);
            Address.sendValue(payable(receiver), amount);
        } else {
            IERC20(rewardToken).safeTransfer(receiver, amount);
        }
    }

    function _requireClaimAuthorization(address holder) internal view {
        if (msg.sender != holder && msg.sender != claimHelper) revert Unauthorized();
    }

    receive() external payable {}
}

src/tax/TaxDividendDeployer.sol

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

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {TaxDividend} from "./TaxDividend.sol";

interface ITaxDividendFactory {
    function dividendDeployer() external view returns (address);
}

/// @notice Fixed-target deterministic clone creation. The factory initializes each clone in its launch transaction.
contract TaxDividendDeployer {
    address public immutable factoryInitializer;
    TaxDividend public immutable implementation;
    address public factory;

    error Unauthorized();
    error InvalidConfiguration();
    error AlreadyInitialized();

    constructor(address initializer, TaxDividend dividendImplementation) {
        if (initializer == address(0) || address(dividendImplementation).code.length == 0) {
            revert InvalidConfiguration();
        }
        factoryInitializer = initializer;
        implementation = dividendImplementation;
    }

    function initializeFactory(address launchFactory) external {
        if (msg.sender != factoryInitializer) revert Unauthorized();
        if (factory != address(0)) revert AlreadyInitialized();
        if (launchFactory.code.length == 0 || ITaxDividendFactory(launchFactory).dividendDeployer() != address(this)) {
            revert InvalidConfiguration();
        }
        factory = launchFactory;
    }

    function predictDividendAddress(bytes32 scopedSalt) external view returns (address) {
        return Clones.predictDeterministicAddress(address(implementation), scopedSalt, address(this));
    }

    function deploy(bytes32 scopedSalt) external returns (address dividend) {
        if (msg.sender != factory) revert Unauthorized();
        return Clones.cloneDeterministic(address(implementation), scopedSalt);
    }
}

src/tax/TaxERC20FactoryBase.sol

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

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";

import {TaxLaunchOperations} from "./TaxLaunchOperations.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";

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

import {TaxLaunchHook} from "./TaxLaunchHook.sol";
import {TaxLaunchTokenDeployer} from "./TaxLaunchTokenDeployer.sol";
import {TaxLaunchpadFactoryCore} from "./TaxLaunchpadFactoryCore.sol";

/// @title TaxERC20FactoryBase
/// @notice Abstract token/deployer binding layer; only TaxRWAERC20LaunchpadFactory is deployed.
/// @dev Keeps deterministic ERC20 creation separate from managed quote policy without adding a deployed factory.
abstract contract TaxERC20FactoryBase is TaxLaunchpadFactoryCore {
    TaxLaunchTokenDeployer public immutable tokenDeployer;
    TaxDividendDeployer public immutable dividendDeployer;

    constructor(
        IPoolManager poolManagerAddress,
        TaxLaunchHook launchHook,
        TaxLaunchTokenDeployer launchTokenDeployer,
        TaxDividendDeployer launchDividendDeployer,
        FactoryInitialization memory initialFactoryConfiguration
    ) TaxLaunchpadFactoryCore(poolManagerAddress, launchHook, initialFactoryConfiguration) {
        if (
            address(launchTokenDeployer) == address(0) || address(launchTokenDeployer).code.length == 0
                || launchTokenDeployer.factory() != address(0)
        ) revert InvalidConfig();
        tokenDeployer = launchTokenDeployer;
        if (address(launchDividendDeployer).code.length == 0 || launchDividendDeployer.factory() != address(0)) {
            revert InvalidConfig();
        }
        dividendDeployer = launchDividendDeployer;
        launchValidation.validateInitialDeploymentRecipients(
            initialFactoryConfiguration.taxPolicy.protocolFeeConfiguration.protocolFeeRecipient,
            address(this),
            launchHook,
            address(launchTokenDeployer),
            launchDividendDeployer
        );
    }

    function _beforeCreateLaunch(LaunchParams calldata) internal view virtual override {}

    function _predictTokenAddress(LaunchParams calldata launchParams, bytes32 scopedSalt, uint256 currentLaunchSupply)
        internal
        view
        override
        returns (address)
    {
        return
            TaxLaunchOperations.predictTokenAddress(tokenDeployer, launchParams, scopedSalt, currentLaunchSupply, hook);
    }

    function _createLaunchPool(LaunchParams calldata params, address creator, LaunchPreparation memory preparation)
        internal
        override
        returns (address token, PoolId poolId, PoolKey memory key)
    {
        return TaxLaunchOperations.create(
            TaxLaunchOperations.Context(hook, tokenDeployer, dividendDeployer, _policyState.policy),
            params,
            preparation,
            _defaultDividendExclusions,
            creator
        );
    }
}

src/tax/TaxFeeMath.sol

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

import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice Inclusive ordinary tax, precise post-protocol allocations and mixed-currency settlement.
library TaxFeeMath {
    uint256 internal constant PERCENTAGE_SCALE = TaxSuiteConstants.PERCENTAGE_SCALE;
    uint256 internal constant RATE_SCALE = TaxSuiteConstants.RATE_SCALE;
    uint256 internal constant MAX_TOTAL_FEE_RATE = TaxSuiteConstants.MAX_TOTAL_FEE_RATE;

    struct TaxFeeBounds {
        uint32 minimumBuyTaxRate;
        uint32 maximumBuyTaxRate;
        uint32 minimumSellTaxRate;
        uint32 maximumSellTaxRate;
    }

    struct ProtocolFeeConfiguration {
        uint32 protocolTaxShare;
        uint32 minimumProtocolFeeRate;
        uint32 maximumProtocolFeeRate;
        address protocolFeeRecipient;
    }

    struct AntiSnipeConfiguration {
        uint32 startTotalFeeRate;
        uint32 windowSeconds;
    }

    struct TaxPolicy {
        TaxFeeBounds taxFeeBounds;
        ProtocolFeeConfiguration protocolFeeConfiguration;
        AntiSnipeConfiguration antiSnipeConfiguration;
        uint256 minimumDividendHoldingRequirement;
    }

    /// @dev Shares divide the remainder after protocol, using the same split on both trading sides.
    struct TaxConfiguration {
        uint32 buyTaxRate;
        uint32 sellTaxRate;
        uint32 creatorAllocationShare;
        uint32 burnAllocationShare;
        uint32 dividendAllocationShare;
        uint32 integratorAllocationShare;
        uint256 minimumDividendHolding;
    }

    struct Rates {
        uint256 quoteRate;
        uint256 burnRate;
        uint256 protocolRate;
        uint256 creatorRate;
        uint256 dividendRate;
        uint256 integratorRate;
        uint256 surchargeRate;
    }

    struct TaxConfigurationPreview {
        uint64 configVersion;
        Rates buyRates;
        Rates sellRates;
        bool dividendsEnabled;
        uint256 minimumDividendHoldingRequirement;
    }

    error InvalidTaxBounds();
    error InvalidTaxConfiguration();
    error InvalidProtocolFeeConfiguration();
    error InvalidMinimumDividendHoldingRequirement();
    error InvalidFeeSchedule();

    function validatePolicy(TaxPolicy memory policy, uint256 supply) internal pure {
        _validateProtocol(policy.protocolFeeConfiguration);
        uint256 minimum = policy.protocolFeeConfiguration.minimumProtocolFeeRate;
        TaxFeeBounds memory bounds = policy.taxFeeBounds;
        _validateSideBounds(bounds.minimumBuyTaxRate, bounds.maximumBuyTaxRate, minimum);
        _validateSideBounds(bounds.minimumSellTaxRate, bounds.maximumSellTaxRate, minimum);
        AntiSnipeConfiguration memory anti = policy.antiSnipeConfiguration;
        if (
            anti.startTotalFeeRate > MAX_TOTAL_FEE_RATE
                || (anti.windowSeconds != 0
                    && (anti.startTotalFeeRate < bounds.maximumBuyTaxRate
                        || anti.startTotalFeeRate < bounds.maximumSellTaxRate))
        ) revert InvalidFeeSchedule();
        if (policy.minimumDividendHoldingRequirement > supply) revert InvalidMinimumDividendHoldingRequirement();
    }

    function _validateSideBounds(uint256 minimum, uint256 maximum, uint256 protocolMinimum) private pure {
        if (
            minimum > maximum || maximum > MAX_TOTAL_FEE_RATE || (minimum != 0 && minimum < protocolMinimum)
                || (maximum != 0 && maximum < protocolMinimum)
        ) revert InvalidTaxBounds();
    }

    function _validateProtocol(ProtocolFeeConfiguration memory protocol) private pure {
        if (
            protocol.protocolTaxShare > PERCENTAGE_SCALE
                || protocol.minimumProtocolFeeRate > protocol.maximumProtocolFeeRate
                || protocol.maximumProtocolFeeRate > MAX_TOTAL_FEE_RATE
        ) revert InvalidProtocolFeeConfiguration();
    }

    function validateTax(TaxConfiguration memory tax, TaxPolicy memory policy, uint256 supply)
        internal
        pure
        returns (bool dividendsEnabled)
    {
        validatePolicy(policy, supply);
        TaxFeeBounds memory bounds = policy.taxFeeBounds;
        if (
            tax.buyTaxRate < bounds.minimumBuyTaxRate || tax.buyTaxRate > bounds.maximumBuyTaxRate
                || tax.sellTaxRate < bounds.minimumSellTaxRate || tax.sellTaxRate > bounds.maximumSellTaxRate
        ) revert InvalidTaxConfiguration();
        uint256 buyRemainder = uint256(tax.buyTaxRate) * PERCENTAGE_SCALE
            - protocolRateNumerator(tax.buyTaxRate, policy.protocolFeeConfiguration);
        uint256 sellRemainder = uint256(tax.sellTaxRate) * PERCENTAGE_SCALE
            - protocolRateNumerator(tax.sellTaxRate, policy.protocolFeeConfiguration);
        uint256 shares = uint256(tax.creatorAllocationShare) + tax.burnAllocationShare + tax.dividendAllocationShare
            + tax.integratorAllocationShare;
        if (buyRemainder == 0 && sellRemainder == 0) {
            if (shares != 0 || tax.minimumDividendHolding != 0) revert InvalidTaxConfiguration();
            return false;
        }
        if (shares != PERCENTAGE_SCALE) revert InvalidTaxConfiguration();
        dividendsEnabled = tax.dividendAllocationShare != 0;
        if (dividendsEnabled) {
            if (
                tax.minimumDividendHolding < policy.minimumDividendHoldingRequirement
                    || tax.minimumDividendHolding > supply
            ) revert InvalidMinimumDividendHoldingRequirement();
        } else if (tax.minimumDividendHolding != 0) {
            revert InvalidTaxConfiguration();
        }
    }

    /// @dev Denominator is PERCENTAGE_SCALE squared. An admitted zero side bypasses the positive floor.
    function protocolRateNumerator(uint256 totalTaxRate, ProtocolFeeConfiguration memory protocol)
        internal
        pure
        returns (uint256)
    {
        _validateProtocol(protocol);
        if (totalTaxRate > MAX_TOTAL_FEE_RATE) revert InvalidTaxConfiguration();
        if (totalTaxRate == 0) return 0;
        if (totalTaxRate < protocol.minimumProtocolFeeRate) revert InvalidTaxConfiguration();
        return Math.min(
            Math.max(
                totalTaxRate * protocol.protocolTaxShare, uint256(protocol.minimumProtocolFeeRate) * PERCENTAGE_SCALE
            ),
            uint256(protocol.maximumProtocolFeeRate) * PERCENTAGE_SCALE
        );
    }

    function rates(
        uint256 totalTaxRate,
        ProtocolFeeConfiguration memory protocol,
        TaxConfiguration memory tax,
        uint256 surchargeRate
    ) internal pure returns (Rates memory result) {
        if (totalTaxRate > MAX_TOTAL_FEE_RATE || surchargeRate > MAX_TOTAL_FEE_RATE - totalTaxRate) {
            revert InvalidFeeSchedule();
        }
        uint256 protocolNumerator = protocolRateNumerator(totalTaxRate, protocol);
        uint256 remainder = totalTaxRate * PERCENTAGE_SCALE - protocolNumerator;
        result.protocolRate = protocolNumerator * PERCENTAGE_SCALE;
        result.creatorRate = remainder * tax.creatorAllocationShare;
        result.burnRate = remainder * tax.burnAllocationShare;
        result.dividendRate = remainder * tax.dividendAllocationShare;
        result.integratorRate = remainder * tax.integratorAllocationShare;
        result.surchargeRate = surchargeRate * PERCENTAGE_SCALE * PERCENTAGE_SCALE;
        result.quoteRate = result.protocolRate + result.creatorRate + result.dividendRate + result.integratorRate
            + result.surchargeRate;
        if (result.quoteRate + result.burnRate != (totalTaxRate + surchargeRate) * PERCENTAGE_SCALE * PERCENTAGE_SCALE)
        {
            revert InvalidTaxConfiguration();
        }
    }

    function surcharge(
        uint256 normalFeeRate,
        uint256 openingTotalRate,
        uint256 launchTime,
        uint256 duration,
        uint256 timestamp,
        bool enabled
    ) internal pure returns (uint256) {
        if (normalFeeRate > MAX_TOTAL_FEE_RATE || openingTotalRate > MAX_TOTAL_FEE_RATE) {
            revert InvalidFeeSchedule();
        }
        if (!enabled || duration == 0) return 0;
        if (normalFeeRate > openingTotalRate) revert InvalidFeeSchedule();
        if (timestamp <= launchTime) return openingTotalRate - normalFeeRate;
        uint256 elapsed = timestamp - launchTime;
        if (elapsed >= duration) return 0;
        return Math.mulDiv(openingTotalRate - normalFeeRate, duration - elapsed, duration);
    }

    /// @dev Specified input is gross; specified output is net. Exact output has one combined gross-up denominator.
    function specifiedFee(uint256 amount, uint256 specifiedRate, uint256 otherRate, bool exactOutput)
        internal
        pure
        returns (uint256)
    {
        _validateRates(specifiedRate, otherRate);
        if (!exactOutput) return Math.mulDiv(amount, specifiedRate, RATE_SCALE);
        return Math.mulDiv(amount, specifiedRate, RATE_SCALE - specifiedRate - otherRate, Math.Rounding.Ceil);
    }

    /// @dev Gross input minus its own fee enters the pool, whichever leg the user specifies.
    function unspecifiedFee(uint256 poolAmount, uint256 specifiedRate, uint256 unspecifiedRate, bool exactOutput)
        internal
        pure
        returns (uint256)
    {
        _validateRates(specifiedRate, unspecifiedRate);
        if (exactOutput) {
            return Math.mulDiv(poolAmount, unspecifiedRate, RATE_SCALE - unspecifiedRate, Math.Rounding.Ceil);
        }
        return Math.mulDiv(poolAmount, unspecifiedRate, RATE_SCALE - specifiedRate);
    }

    function splitQuoteFee(uint256 amount, Rates memory rate)
        internal
        pure
        returns (
            uint256 protocolAmount,
            uint256 surchargeAmount,
            uint256 creatorAmount,
            uint256 dividendAmount,
            uint256 integratorAmount
        )
    {
        if (amount == 0) return (0, 0, 0, 0, 0);
        if (rate.quoteRate == 0) revert InvalidFeeSchedule();
        protocolAmount = Math.mulDiv(amount, rate.protocolRate, rate.quoteRate);
        surchargeAmount = Math.mulDiv(amount, rate.surchargeRate, rate.quoteRate);
        uint256 remaining = amount - protocolAmount - surchargeAmount;
        uint256 allocationRate = rate.creatorRate + rate.dividendRate + rate.integratorRate;
        if (allocationRate == 0) {
            if (rate.protocolRate != 0) protocolAmount += remaining;
            else surchargeAmount += remaining;
        } else if (rate.dividendRate != 0) {
            creatorAmount = Math.mulDiv(remaining, rate.creatorRate, allocationRate);
            integratorAmount = Math.mulDiv(remaining, rate.integratorRate, allocationRate);
            dividendAmount = remaining - creatorAmount - integratorAmount;
        } else if (rate.creatorRate != 0) {
            integratorAmount = Math.mulDiv(remaining, rate.integratorRate, allocationRate);
            creatorAmount = remaining - integratorAmount;
        } else {
            integratorAmount = remaining;
        }
    }

    function _validateRates(uint256 firstRate, uint256 secondRate) private pure {
        uint256 maximum = MAX_TOTAL_FEE_RATE * PERCENTAGE_SCALE * PERCENTAGE_SCALE;
        if (firstRate > maximum || secondRate > maximum - firstRate) revert InvalidFeeSchedule();
    }
}

src/tax/TaxLaunchHook.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";

import {BaseHook} from "../base/BaseHook.sol";
import {FeeEscrow} from "../FeeEscrow.sol";
import {TaxFeeMath} from "./TaxFeeMath.sol";
import {TaxDividend} from "./TaxDividend.sol";
import {ITaxDividend} from "./interfaces/ITaxDividend.sol";
import {TaxLaunchToken} from "./TaxLaunchToken.sol";
import {LaunchConsent} from "./LaunchConsent.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {SafeCast} from "v4-core/src/libraries/SafeCast.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol";
import {CurrencySettler} from "v4-core/test/utils/CurrencySettler.sol";

import {ILaunchBuyAdapter} from "../interfaces/ILaunchBuyAdapter.sol";

interface IWiredFactory {
    function hook() external view returns (address launchHook);
    function poolManager() external view returns (address manager);
    function launchValidation() external view returns (address validation);
}

interface ITaxSlotValidation {
    function validateFeeRecipient(address recipient, address factory) external view;
    function validatePoolRegistration(TaxLaunchHook.PoolRegistration calldata registration)
        external
        view
        returns (uint8 creatorSlotIndex);
}

/// @title TaxLaunchHook
/// @notice The single shared Uniswap v4 hook for every launch in one deployment suite. It:
///         - gates pool creation to the launchpad factory (`beforeInitialize`),
///         - blocks all third-party liquidity adds/removes, and owns the permanently locked
///           single-sided genesis-band positions (no code path ever passes a negative liquidityDelta),
///         - on every swap takes a fee on the quote currency as an ERC-6909 claim minted to the
///           FeeEscrow, split into inclusive protocol and remainder allocations; temporary anti-sniping
///           surcharge goes to the frozen protocol recipient. Burn credits redeem later to the fixed sink.
/// @dev    One deployment, reused by all launches; per-pool economics are frozen at launch in `poolConfig`.
///         Deployed at a CREATE2-mined address whose low 14 bits equal `getHookPermissions()` (BaseHook
///         validates this in the constructor). Fee custody lives in the FeeEscrow, not here.
contract TaxLaunchHook is BaseHook, Initializable {
    using CurrencySettler for Currency;
    using SafeCast for uint256;

    /// @notice Inclusive ordinary tax plus temporary surcharge stays strictly below 100%.
    uint32 public constant MAX_TOTAL_FEE_RATE = TaxSuiteConstants.MAX_TOTAL_FEE_RATE;
    uint256 public constant RATE_SCALE = TaxSuiteConstants.RATE_SCALE;
    address public constant BURN_SINK = TaxSuiteConstants.BURN_SINK;
    uint256 public constant MAX_FEE_SLOTS = 7;
    uint256 internal constant BPS = 10_000;
    mapping(address dividend => bool registered) public isDividendContract;
    uint256 public constant MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH = TaxSuiteConstants.MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH;

    /// @notice Frozen execution economics; creator and creator payout retain their existing authorized updates.
    struct PoolConfig {
        bool initialized;
        bool tokenIsCurrency0;
        address token;
        address quoteToken;
        address currentCreator;
        address creatorFeeRecipient;
        TaxFeeMath.ProtocolFeeConfiguration protocolFeeConfiguration;
        TaxFeeMath.AntiSnipeConfiguration antiSnipeConfiguration;
        uint48 launchTime;
        bool antiSnipeEnabled;
        address integratorFeeRecipient;
        address dividend;
        TaxFeeMath.TaxConfiguration taxConfiguration;
    }

    /// @notice Each weight defines a share of the creator tax. One slot can follow creator rights.
    struct FeeSlotInput {
        address recipient;
        address admin;
        uint16 relativeWeightBps;
        bool isCreator;
    }

    /// @notice The weight stays fixed. The recipient and admin can change.
    struct FeeSlot {
        address recipient;
        address admin;
        uint16 weightBps;
        bool isCreator;
    }

    struct PoolRegistration {
        address token;
        address creator;
        address launcher;
        address creatorFeeRecipient;
        address integratorFeeRecipient;
        address dividend;
        uint48 launchTime;
        bool antiSnipeEnabled;
        TaxFeeMath.TaxPolicy admittedPolicy;
        TaxFeeMath.TaxConfiguration taxConfiguration;
        FeeSlotInput[] feeSlots;
    }

    enum LaunchBuyContextState {
        NONE,
        ARMED,
        EXECUTING,
        CONSUMED
    }

    struct LaunchBuyContext {
        LaunchBuyContextState state;
        PoolId poolId;
        address swapCaller;
    }

    /// @notice A resolved single-sided liquidity band, computed by the factory and seeded here.
    struct SeedPosition {
        int24 tickLower;
        int24 tickUpper;
        uint128 liquidity;
    }

    /// @notice The address allowed to wire `factory`/`feeEscrow` exactly once (the deployer/deploy script).
    address public immutable deployer;

    address public factory;
    address public feeEscrow;
    address public launchBuyAdapter;
    bool public wired;

    mapping(PoolId poolId => PoolConfig configuration) public poolConfig;
    mapping(PoolId poolId => FeeSlot[] slots) internal _poolFeeSlots;
    mapping(PoolId poolId => uint8 indexPlusOne) internal _creatorSlotIndex;
    LaunchBuyContext internal _launchBuyContext;
    /// @notice Records the integrator's acceptance of the frozen launch terms.
    mapping(PoolId poolId => bool accepted) public launchConsented;

    error NotDeployer();
    error NotFactory();
    error NotWired();
    error ZeroAddress();
    error BadWiring();
    error AlreadyRegistered();
    error LiquidityLocked();
    error NotSingleSided();
    error InvalidFeeConfig();
    error InvalidFeeSlots();
    error NotSlotAdmin();
    error CreatorSlotManagedByFactory();
    error AntiSnipeUnavailable();
    error ExactOutputDisabledDuringAntiSnipe();
    error PartialFillUnsupported();
    error LaunchBuyContextActive();
    error LaunchBuyContextMissing();
    error LaunchBuyContextMismatch(
        PoolId expectedPoolId, PoolId actualPoolId, address expectedSwapCaller, address actualSwapCaller
    );
    error LaunchBuyContextNotConsumed();
    error LaunchBuyMultipleSwaps();
    error InvalidLaunchBuyDirection();
    error LaunchBuyExactOutputUnsupported();
    error ZeroLaunchBuyOutput();
    error LaunchBuyAdapterNotConfigured();
    error InvalidLaunchBuyAdapter(address adapter);
    error InvalidLaunchBuyRequest();

    event FeeSlotCreated(
        PoolId indexed poolId,
        uint256 indexed slotIndex,
        address recipient,
        address admin,
        uint16 weightBps,
        bool isCreator
    );
    event FeeSlotRecipientUpdated(
        PoolId indexed poolId, uint256 indexed slotIndex, address oldRecipient, address newRecipient
    );
    event FeeSlotAdminUpdated(PoolId indexed poolId, uint256 indexed slotIndex, address oldAdmin, address newAdmin);

    event BurnTaxCredited(PoolId indexed poolId, address indexed token, address indexed sink, uint256 amount);
    event CreatorTaxCredited(PoolId indexed poolId, address indexed recipient, address currency, uint256 amount);
    event DividendTaxCredited(PoolId indexed poolId, address indexed dividend, address currency, uint256 amount);
    event DividendTaxRedirected(
        PoolId indexed poolId, address indexed recipient, address indexed currency, uint256 amount
    );
    event IntegratorAttributed(PoolId indexed poolId, address indexed integratorFeeRecipient);
    event ProtocolFeeCredited(PoolId indexed poolId, address indexed recipient, address currency, uint256 amount);
    event IntegratorTaxCredited(PoolId indexed poolId, address indexed recipient, address currency, uint256 amount);
    event AntiSnipeFeeCredited(PoolId indexed poolId, address indexed recipient, address currency, uint256 amount);
    event Wired(address indexed factory, address indexed feeEscrow);
    event PoolRegistered(PoolId indexed poolId, address indexed originalCreator, address indexed creatorFeeRecipient);
    event CreatorRightsUpdated(
        PoolId indexed poolId,
        address indexed previousCreator,
        address indexed newCreator,
        address previousCreatorFeeRecipient,
        address newCreatorFeeRecipient
    );
    event Seeded(PoolId indexed poolId, uint256 tokenAmountSeeded);
    /// @notice One record per successful registered-pool swap, including zero rounded quote fees.
    /// @dev quoteCurrency/quoteFeeAmount cover quote fees only; BurnTaxCredited records launched-token allocation.
    event Trade(
        PoolId indexed poolId,
        address indexed executor,
        address indexed referrer,
        address quoteCurrency,
        uint256 quoteFeeAmount,
        bytes32 comment
    );

    constructor(IPoolManager poolManagerAddress, address hookDeployer) BaseHook(poolManagerAddress) {
        address manager = address(poolManagerAddress);
        if (
            manager == address(0) || manager.code.length == 0 || hookDeployer == address(0)
                || hookDeployer == address(this) || hookDeployer == manager
        ) revert BadWiring();
        deployer = hookDeployer;
    }

    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true,
            afterInitialize: false,
            beforeAddLiquidity: true,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: true,
            afterRemoveLiquidity: false,
            beforeSwap: true,
            afterSwap: true,
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: true,
            afterSwapReturnDelta: true,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    /// @notice One-time wiring of the factory + fee escrow (breaks the deploy cycle: hook is deployed first).
    /// @dev    Guarded by OpenZeppelin's `initializer` modifier (set-once, the standard initialization pattern)
    ///         on top of the deployer-only authorization check, so it can never be re-run. To also close the
    ///         deploy-time window, only the designated initializer can complete wiring. The tax-suite script
    ///         prepares multiple transactions and leaves creation disabled; see TAX_TOKEN_SUITE_DEPLOYMENT.md.
    function initialize(address factoryAddress, address feeEscrowAddress) external initializer {
        if (msg.sender != deployer) revert NotDeployer();
        if (factoryAddress == address(0) || feeEscrowAddress == address(0)) revert ZeroAddress();
        // The hook is the single shared, un-re-wireable instance, so a mis-wire bricks every launch with no
        // recovery. Bind both sides: the factory and escrow must already point back at this exact hook (and
        // the escrow at the same PoolManager) or wiring fails closed instead of silently.
        if (factoryAddress.code.length == 0 || feeEscrowAddress.code.length == 0) revert BadWiring();
        if (IWiredFactory(factoryAddress).hook() != address(this)) revert BadWiring();
        if (IWiredFactory(factoryAddress).poolManager() != address(poolManager)) revert BadWiring();
        if (FeeEscrow(feeEscrowAddress).hook() != address(this)) revert BadWiring();
        if (address(FeeEscrow(feeEscrowAddress).poolManager()) != address(poolManager)) revert BadWiring();
        factory = factoryAddress;
        feeEscrow = feeEscrowAddress;
        wired = true;
        emit Wired(factoryAddress, feeEscrowAddress);
    }

    // ---- factory-only setup ----

    function registerPool(PoolKey calldata key, PoolRegistration calldata registration) external {
        if (msg.sender != factory) revert NotFactory();
        if (address(key.hooks) != address(this) || key.fee != 0 || registration.token == address(0)) {
            revert BadWiring();
        }
        bool tokenIsCurrency0 = Currency.unwrap(key.currency0) == registration.token;
        if (!tokenIsCurrency0 && Currency.unwrap(key.currency1) != registration.token) revert BadWiring();
        address quoteToken = Currency.unwrap(tokenIsCurrency0 ? key.currency1 : key.currency0);
        uint8 creatorSlotIndex =
            ITaxSlotValidation(IWiredFactory(factory).launchValidation()).validatePoolRegistration(registration);
        LaunchConsent.requireConsent(
            launchConsented,
            key,
            tokenIsCurrency0,
            registration.integratorFeeRecipient,
            registration.launcher,
            registration.antiSnipeEnabled,
            registration.taxConfiguration
        );
        TaxLaunchToken token = TaxLaunchToken(registration.token);
        if (token.factory() != factory || token.dividend() != registration.dividend) revert BadWiring();
        if (registration.dividend != address(0)) {
            TaxDividend tracker = TaxDividend(payable(registration.dividend));
            if (
                tracker.taxToken() != registration.token || tracker.owner() != factory
                    || tracker.hook() != address(this) || address(tracker.feeEscrow()) != feeEscrow
                    || isDividendContract[address(tracker)] || tracker.quoteToken() != quoteToken
                    || tracker.minimumDividendHolding() != registration.taxConfiguration.minimumDividendHolding
            ) revert BadWiring();
            isDividendContract[address(tracker)] = true;
        }
        PoolId poolId = key.toId();
        if (poolConfig[poolId].initialized) revert AlreadyRegistered();
        poolConfig[poolId] = PoolConfig({
            initialized: true,
            tokenIsCurrency0: tokenIsCurrency0,
            token: registration.token,
            quoteToken: quoteToken,
            currentCreator: registration.creator,
            creatorFeeRecipient: registration.creatorFeeRecipient,
            protocolFeeConfiguration: registration.admittedPolicy.protocolFeeConfiguration,
            antiSnipeConfiguration: registration.admittedPolicy.antiSnipeConfiguration,
            launchTime: registration.launchTime,
            antiSnipeEnabled: registration.antiSnipeEnabled,
            integratorFeeRecipient: registration.integratorFeeRecipient,
            dividend: registration.dividend,
            taxConfiguration: registration.taxConfiguration
        });
        _registerFeeSlots(poolId, registration, creatorSlotIndex);
        emit IntegratorAttributed(poolId, registration.integratorFeeRecipient);
        emit PoolRegistered(poolId, registration.creator, registration.creatorFeeRecipient);
    }

    function updateCreatorRights(PoolId poolId, address newCreator, address newCreatorFeeRecipient) external {
        if (msg.sender != factory) revert NotFactory();
        PoolConfig storage configuration = poolConfig[poolId];
        if (!configuration.initialized) revert InvalidFeeConfig();
        if (newCreator == address(0) || newCreatorFeeRecipient == address(0)) revert InvalidFeeConfig();
        address previousCreator = configuration.currentCreator;
        address previousCreatorFeeRecipient = configuration.creatorFeeRecipient;
        configuration.currentCreator = newCreator;
        configuration.creatorFeeRecipient = newCreatorFeeRecipient;
        uint256 indexPlusOne = _creatorSlotIndex[poolId];
        if (indexPlusOne != 0) {
            uint256 index = indexPlusOne - 1;
            FeeSlot storage slot = _poolFeeSlots[poolId][index];
            slot.recipient = newCreatorFeeRecipient;
            slot.admin = newCreator;
            emit FeeSlotRecipientUpdated(poolId, index, previousCreatorFeeRecipient, newCreatorFeeRecipient);
            emit FeeSlotAdminUpdated(poolId, index, previousCreator, newCreator);
        }
        emit CreatorRightsUpdated(
            poolId, previousCreator, newCreator, previousCreatorFeeRecipient, newCreatorFeeRecipient
        );
    }

    function poolFeeSlots(PoolId poolId) external view returns (FeeSlot[] memory) {
        return _poolFeeSlots[poolId];
    }

    function updateFeeSlotRecipient(PoolId poolId, uint256 slotIndex, address newRecipient) external {
        FeeSlot storage slot = _requireSlotAdmin(poolId, slotIndex);
        _validateSlotAddress(poolId, newRecipient);
        address oldRecipient = slot.recipient;
        slot.recipient = newRecipient;
        emit FeeSlotRecipientUpdated(poolId, slotIndex, oldRecipient, newRecipient);
    }

    function updateFeeSlotAdmin(PoolId poolId, uint256 slotIndex, address newAdmin) external {
        FeeSlot storage slot = _requireSlotAdmin(poolId, slotIndex);
        _validateSlotAddress(poolId, newAdmin);
        address oldAdmin = slot.admin;
        slot.admin = newAdmin;
        emit FeeSlotAdminUpdated(poolId, slotIndex, oldAdmin, newAdmin);
    }

    function _requireSlotAdmin(PoolId poolId, uint256 slotIndex) internal view returns (FeeSlot storage slot) {
        if (slotIndex >= _poolFeeSlots[poolId].length) revert InvalidFeeSlots();
        slot = _poolFeeSlots[poolId][slotIndex];
        if (msg.sender != slot.admin) revert NotSlotAdmin();
        if (slot.isCreator) revert CreatorSlotManagedByFactory();
    }

    function _validateSlotAddress(PoolId poolId, address account) internal view {
        if (account == poolConfig[poolId].token) revert InvalidFeeConfig();
        ITaxSlotValidation(IWiredFactory(factory).launchValidation()).validateFeeRecipient(account, factory);
    }

    function _registerFeeSlots(PoolId poolId, PoolRegistration calldata registration, uint8 creatorSlotIndex) internal {
        FeeSlotInput[] calldata slots = registration.feeSlots;
        uint256 count = slots.length;
        if (count == 0) {
            _storeFeeSlot(poolId, registration.creatorFeeRecipient, registration.creator, uint16(BPS), true);
            _creatorSlotIndex[poolId] = 1;
            return;
        }
        _creatorSlotIndex[poolId] = creatorSlotIndex;
        for (uint256 i; i < count; ++i) {
            FeeSlotInput calldata slot = slots[i];
            _storeFeeSlot(poolId, slot.recipient, slot.admin, slot.relativeWeightBps, slot.isCreator);
        }
    }

    function _storeFeeSlot(PoolId poolId, address recipient, address admin, uint16 weight, bool isCreator) internal {
        uint256 index = _poolFeeSlots[poolId].length;
        _poolFeeSlots[poolId].push(FeeSlot(recipient, admin, weight, isCreator));
        emit FeeSlotCreated(poolId, index, recipient, admin, weight, isCreator);
    }

    function setLaunchBuyAdapter(address newLaunchBuyAdapter) external {
        if (msg.sender != factory) revert NotFactory();
        if (_launchBuyContext.state != LaunchBuyContextState.NONE) revert LaunchBuyContextActive();
        if (newLaunchBuyAdapter != address(0)) _validateLaunchBuyAdapter(newLaunchBuyAdapter);
        launchBuyAdapter = newLaunchBuyAdapter;
    }

    function executeLaunchBuy(PoolId poolId, ILaunchBuyAdapter.LaunchBuyRequest calldata request)
        external
        payable
        returns (uint256 amountOut)
    {
        if (msg.sender != factory) revert NotFactory();
        address adapter = launchBuyAdapter;
        if (adapter == address(0)) revert LaunchBuyAdapterNotConfigured();
        if (
            PoolId.unwrap(request.poolKey.toId()) != PoolId.unwrap(poolId) || request.launchToken == address(0)
                || request.originalCreator == address(0) || request.amountIn == 0 || request.minAmountOut == 0
                || request.routeData.length == 0 || request.routeData.length > MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH
        ) revert InvalidLaunchBuyRequest();

        PoolConfig storage configuration = poolConfig[poolId];
        if (!configuration.initialized) {
            revert InvalidLaunchBuyRequest();
        }
        if (_launchBuyContext.state != LaunchBuyContextState.NONE) revert LaunchBuyContextActive();

        address swapCaller = ILaunchBuyAdapter(adapter).swapCaller();
        _launchBuyContext =
            LaunchBuyContext({state: LaunchBuyContextState.ARMED, poolId: poolId, swapCaller: swapCaller});
        uint256 creatorBalanceBefore = IERC20(request.launchToken).balanceOf(request.originalCreator);
        amountOut = ILaunchBuyAdapter(adapter).executeLaunchBuy{value: msg.value}(request);
        LaunchBuyContext memory context = _launchBuyContext;
        if (context.state != LaunchBuyContextState.CONSUMED) revert LaunchBuyContextNotConsumed();

        uint256 creatorBalanceAfter = IERC20(request.launchToken).balanceOf(request.originalCreator);
        if (
            amountOut < request.minAmountOut || creatorBalanceAfter < creatorBalanceBefore
                || creatorBalanceAfter - creatorBalanceBefore != amountOut
        ) revert InvalidLaunchBuyRequest();
        delete _launchBuyContext;
    }

    function _validateLaunchBuyAdapter(address adapter) internal view {
        if (
            adapter.code.length == 0 || _isReservedLaunchBuyDependency(adapter)
                || ILaunchBuyAdapter(adapter).factory() != factory
                || ILaunchBuyAdapter(adapter).launchHook() != address(this)
                || ILaunchBuyAdapter(adapter).poolManager() != address(poolManager)
        ) revert InvalidLaunchBuyAdapter(adapter);

        address reportedRouter = ILaunchBuyAdapter(adapter).router();
        address reportedSwapCaller = ILaunchBuyAdapter(adapter).swapCaller();
        if (
            reportedRouter.code.length == 0 || reportedSwapCaller.code.length == 0
                || _isReservedLaunchBuyDependency(reportedRouter) || _isReservedLaunchBuyDependency(reportedSwapCaller)
        ) revert InvalidLaunchBuyAdapter(adapter);
    }

    function _isReservedLaunchBuyDependency(address account) internal view returns (bool) {
        return account == factory || account == address(this) || account == address(poolManager) || account == feeEscrow;
    }

    /// @notice Seed the launch token as single-sided liquidity owned by this hook (permanent: there is no
    ///         path that ever removes it). Each band's quote-side delta is asserted zero, the on-chain
    ///         guarantee that the seed is token-only.
    function seedLiquidity(PoolKey calldata key, SeedPosition[] calldata positions, bool tokenIsCurrency0) external {
        if (msg.sender != factory) revert NotFactory();
        poolManager.unlock(abi.encode(key, positions, tokenIsCurrency0));
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        // Only ever reached as the callback to this hook's own `seedLiquidity` unlock (the PoolManager calls
        // back the unlock caller), so this guard fully gates it.
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        (PoolKey memory key, SeedPosition[] memory positions, bool tokenIsCurrency0) =
            abi.decode(data, (PoolKey, SeedPosition[], bool));

        Currency tokenCurrency = tokenIsCurrency0 ? key.currency0 : key.currency1;
        uint256 tokenOwed;
        for (uint256 i = 0; i < positions.length; i++) {
            (BalanceDelta delta,) = poolManager.modifyLiquidity(
                key,
                IPoolManager.ModifyLiquidityParams({
                    tickLower: positions[i].tickLower,
                    tickUpper: positions[i].tickUpper,
                    liquidityDelta: int256(uint256(positions[i].liquidity)),
                    salt: bytes32(0)
                }),
                ""
            );
            int128 quoteDelta = tokenIsCurrency0 ? delta.amount1() : delta.amount0();
            if (quoteDelta != 0) revert NotSingleSided();
            int128 tokenDelta = tokenIsCurrency0 ? delta.amount0() : delta.amount1();
            // adding liquidity owes the token (negative delta from the caller's perspective)
            if (tokenDelta > 0) revert NotSingleSided();
            // forge-lint: disable-next-line(unsafe-typecast) tokenDelta is checked < 0, so -tokenDelta fits uint128
            tokenOwed += uint256(uint128(-tokenDelta));
        }
        tokenCurrency.settle(poolManager, address(this), tokenOwed, false);
        emit Seeded(key.toId(), tokenOwed);
        return "";
    }

    // ---- hook callbacks ----

    function _beforeInitialize(address sender, PoolKey calldata, uint160) internal view override returns (bytes4) {
        if (!wired) revert NotWired();
        if (sender != factory) revert NotFactory();
        return IHooks.beforeInitialize.selector;
    }

    function _beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
        internal
        pure
        override
        returns (bytes4)
    {
        // The hook's own genesis seed is a self-call and skips this callback; everyone else is blocked.
        revert LiquidityLocked();
    }

    function _beforeRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        bytes calldata
    ) internal pure override returns (bytes4) {
        revert LiquidityLocked();
    }

    function _beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params, bytes calldata)
        internal
        override
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        PoolId poolId = key.toId();
        PoolConfig memory cfg = poolConfig[poolId];
        (, bool quoteIsSpecified) = _quoteCurrencyAndSpecified(key, params, cfg);
        bool activeLaunchBuy = _launchBuyContext.state != LaunchBuyContextState.NONE;
        if (activeLaunchBuy) {
            _matchLaunchBuyContextBeforeSwap(poolId, sender, params, quoteIsSpecified, cfg.initialized);
        } else {
            if (!cfg.initialized) return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
            if (params.amountSpecified > 0 && _isSurchargeWindowActive(cfg, params.zeroForOne != cfg.tokenIsCurrency0))
            {
                revert ExactOutputDisabledDuringAntiSnipe();
            }
        }
        TaxFeeMath.Rates memory rate = _rates(cfg, params.zeroForOne != cfg.tokenIsCurrency0, activeLaunchBuy);
        uint256 specifiedRate = rate.burnRate;
        uint256 otherRate = rate.quoteRate;
        if (quoteIsSpecified) {
            specifiedRate = rate.quoteRate;
            otherRate = rate.burnRate;
        }
        uint256 amount = TaxFeeMath.specifiedFee(
            _specifiedMagnitude(params.amountSpecified), specifiedRate, otherRate, params.amountSpecified > 0
        );
        return (IHooks.beforeSwap.selector, toBeforeSwapDelta(amount.toInt128(), 0), 0);
    }

    function _afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) internal override returns (bytes4, int128) {
        PoolId poolId = key.toId();
        PoolConfig memory cfg = poolConfig[poolId];
        (Currency quoteCurrency, bool quoteIsSpecified) = _quoteCurrencyAndSpecified(key, params, cfg);
        bool activeLaunchBuy = _launchBuyContext.state != LaunchBuyContextState.NONE;
        bool isBuy = params.zeroForOne != cfg.tokenIsCurrency0;
        if (activeLaunchBuy) {
            _matchLaunchBuyContextAfterSwap(poolId, sender, params, quoteIsSpecified, cfg.initialized);
        } else {
            if (!cfg.initialized) return (IHooks.afterSwap.selector, 0);
            if (params.amountSpecified > 0 && _isSurchargeWindowActive(cfg, isBuy)) {
                revert ExactOutputDisabledDuringAntiSnipe();
            }
        }
        TaxFeeMath.Rates memory rate = _rates(cfg, isBuy, activeLaunchBuy);
        uint256 specifiedRate = rate.burnRate;
        uint256 otherRate = rate.quoteRate;
        if (quoteIsSpecified) {
            specifiedRate = rate.quoteRate;
            otherRate = rate.burnRate;
        }
        bool exactOutput = params.amountSpecified > 0;
        uint256 specifiedFee =
            TaxFeeMath.specifiedFee(_specifiedMagnitude(params.amountSpecified), specifiedRate, otherRate, exactOutput);
        if (specifiedFee != 0 || exactOutput || activeLaunchBuy) {
            _requireFullSpecifiedFill(params, delta, specifiedFee);
        }
        uint256 poolUnspecified = _unspecifiedMagnitude(params, delta);
        uint256 unspecifiedFee = TaxFeeMath.unspecifiedFee(poolUnspecified, specifiedRate, otherRate, exactOutput);
        uint256 quoteFee = unspecifiedFee;
        uint256 burnFee = specifiedFee;
        if (quoteIsSpecified) {
            quoteFee = specifiedFee;
            burnFee = unspecifiedFee;
        }
        if (quoteFee != 0) {
            poolManager.mint(feeEscrow, quoteCurrency.toId(), quoteFee);
        }
        _creditTax(cfg, quoteCurrency, quoteFee, rate, hookData, poolId, sender);
        if (burnFee != 0) {
            Currency tokenCurrency = key.currency1;
            if (cfg.tokenIsCurrency0) tokenCurrency = key.currency0;
            // Reserve claims without requiring physical seller input before the router settles.
            poolManager.mint(feeEscrow, tokenCurrency.toId(), burnFee);
            FeeEscrow(feeEscrow).credit(BURN_SINK, Currency.unwrap(tokenCurrency), burnFee);
            emit BurnTaxCredited(poolId, Currency.unwrap(tokenCurrency), BURN_SINK, burnFee);
        }
        if (activeLaunchBuy) _consumeLaunchBuyContextAfterSwap(cfg, delta);
        return (IHooks.afterSwap.selector, unspecifiedFee.toInt128());
    }

    // ---- fee internals ----

    function _creditTax(
        PoolConfig memory cfg,
        Currency currency,
        uint256 amount,
        TaxFeeMath.Rates memory rate,
        bytes calldata hookData,
        PoolId poolId,
        address sender
    ) internal {
        emit Trade(poolId, sender, address(0), Currency.unwrap(currency), amount, _parseComment(hookData));
        if (amount == 0) return;
        (
            uint256 protocolAmount,
            uint256 surchargeAmount,
            uint256 creatorAmount,
            uint256 dividendAmount,
            uint256 integratorAmount
        ) = TaxFeeMath.splitQuoteFee(amount, rate);
        FeeEscrow escrow = FeeEscrow(feeEscrow);
        address asset = Currency.unwrap(currency);
        address protocolRecipient = cfg.protocolFeeConfiguration.protocolFeeRecipient;
        if (protocolAmount != 0) {
            escrow.credit(protocolRecipient, asset, protocolAmount);
            emit ProtocolFeeCredited(poolId, protocolRecipient, asset, protocolAmount);
        }
        if (surchargeAmount != 0) {
            escrow.credit(protocolRecipient, asset, surchargeAmount);
            emit AntiSnipeFeeCredited(poolId, protocolRecipient, asset, surchargeAmount);
        }
        if (creatorAmount != 0) _creditCreatorTax(poolId, escrow, asset, creatorAmount);
        if (dividendAmount != 0) {
            if (cfg.dividend == address(0)) revert BadWiring();
            ITaxDividend tracker = ITaxDividend(cfg.dividend);
            if (tracker.totalShares() == 0) {
                escrow.credit(protocolRecipient, asset, dividendAmount);
                emit DividendTaxRedirected(poolId, protocolRecipient, asset, dividendAmount);
            } else {
                escrow.credit(cfg.dividend, asset, dividendAmount);
                tracker.notifyDividendFee(dividendAmount);
                emit DividendTaxCredited(poolId, cfg.dividend, asset, dividendAmount);
            }
        }
        if (integratorAmount != 0) {
            escrow.credit(cfg.integratorFeeRecipient, asset, integratorAmount);
            emit IntegratorTaxCredited(poolId, cfg.integratorFeeRecipient, asset, integratorAmount);
        }
    }

    function _creditCreatorTax(PoolId poolId, FeeEscrow escrow, address asset, uint256 amount) internal {
        FeeSlot[] storage slots = _poolFeeSlots[poolId];
        uint256 credited;
        for (uint256 i; i < slots.length; ++i) {
            FeeSlot storage slot = slots[i];
            // The last slot receives the remainder to conserve the creator tax.
            uint256 share = i + 1 == slots.length ? amount - credited : amount * slot.weightBps / BPS;
            credited += share;
            if (share == 0) continue;
            escrow.credit(slot.recipient, asset, share);
            emit CreatorTaxCredited(poolId, slot.recipient, asset, share);
        }
    }

    function _quoteCurrencyAndSpecified(
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        PoolConfig memory cfg
    ) internal pure returns (Currency quoteCurrency, bool quoteIsSpecified) {
        quoteCurrency = cfg.tokenIsCurrency0 ? key.currency1 : key.currency0;
        bool exactIn = params.amountSpecified < 0;
        bool specifiedIsCurrency0 = exactIn ? params.zeroForOne : !params.zeroForOne;
        Currency specifiedCurrency = specifiedIsCurrency0 ? key.currency0 : key.currency1;
        quoteIsSpecified = Currency.unwrap(specifiedCurrency) == Currency.unwrap(quoteCurrency);
    }

    function _specifiedMagnitude(int256 amountSpecified) internal pure returns (uint256) {
        if (amountSpecified < 0) return uint256(-(amountSpecified + 1)) + 1;
        // forge-lint: disable-next-line(unsafe-typecast) non-negative int256 always fits in uint256
        return uint256(amountSpecified);
    }

    function _requireFullSpecifiedFill(
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        uint256 specifiedFee
    ) internal pure {
        bool exactIn = params.amountSpecified < 0;
        bool specifiedIsCurrency0 = exactIn ? params.zeroForOne : !params.zeroForOne;
        int128 actualSpecified = specifiedIsCurrency0 ? delta.amount0() : delta.amount1();
        // forge-lint: disable-next-line(unsafe-typecast) beforeSwap already requires this fee to fit int128
        int256 expectedSpecified = params.amountSpecified + int256(specifiedFee);
        if (int256(actualSpecified) != expectedSpecified) revert PartialFillUnsupported();
    }

    /// @notice Quote and burn rates scaled by 1e24, including the decaying surcharge when applicable.
    /// @dev Configuration validates the combined ceiling; the calculation does not clip excess fees.
    function _rates(PoolConfig memory cfg, bool isBuy, bool exempt) internal view returns (TaxFeeMath.Rates memory) {
        uint256 sideTax = cfg.taxConfiguration.sellTaxRate;
        if (isBuy) sideTax = cfg.taxConfiguration.buyTaxRate;
        uint256 extra = TaxFeeMath.surcharge(
            sideTax,
            cfg.antiSnipeConfiguration.startTotalFeeRate,
            cfg.launchTime,
            cfg.antiSnipeConfiguration.windowSeconds,
            block.timestamp,
            cfg.antiSnipeEnabled && !exempt
        );
        return TaxFeeMath.rates(sideTax, cfg.protocolFeeConfiguration, cfg.taxConfiguration, extra);
    }

    function effectiveFeeRates(PoolId poolId, bool isBuy)
        external
        view
        returns (TaxFeeMath.Rates memory rate, bool exactOutputRestricted)
    {
        PoolConfig memory cfg = poolConfig[poolId];
        if (!cfg.initialized) revert InvalidFeeConfig();
        return (_rates(cfg, isBuy, false), _isSurchargeWindowActive(cfg, isBuy));
    }

    function _isSurchargeWindowActive(PoolConfig memory cfg, bool isBuy) internal view returns (bool) {
        if (!cfg.antiSnipeEnabled || cfg.antiSnipeConfiguration.windowSeconds == 0) return false;
        uint256 sideTax = cfg.taxConfiguration.sellTaxRate;
        if (isBuy) sideTax = cfg.taxConfiguration.buyTaxRate;
        if (cfg.antiSnipeConfiguration.startTotalFeeRate == sideTax) return false;
        if (block.timestamp <= cfg.launchTime) return true;
        return block.timestamp - cfg.launchTime < cfg.antiSnipeConfiguration.windowSeconds;
    }

    /// @notice The absolute amount that moved in the swap's unspecified currency.
    function _unspecifiedMagnitude(IPoolManager.SwapParams calldata params, BalanceDelta delta)
        internal
        pure
        returns (uint256)
    {
        // exact-in: unspecified = output; exact-out: unspecified = input.
        bool unspecifiedIsCurrency1 = params.zeroForOne;
        if (params.amountSpecified >= 0) unspecifiedIsCurrency1 = !unspecifiedIsCurrency1;
        int128 deltaAmount = delta.amount0();
        if (unspecifiedIsCurrency1) deltaAmount = delta.amount1();
        // Widen before negation so int128.min is handled without overflowing.
        if (deltaAmount < 0) return uint256(-int256(deltaAmount));
        return uint256(int256(deltaAmount));
    }

    /// @dev Preserve the existing comment offset; the first word has no financial referral meaning.
    function _parseComment(bytes calldata hookData) internal pure returns (bytes32 comment) {
        if (hookData.length >= 64) comment = bytes32(hookData[32:64]);
    }

    function _matchLaunchBuyContextBeforeSwap(
        PoolId poolId,
        address sender,
        IPoolManager.SwapParams calldata params,
        bool quoteIsSpecified,
        bool poolInitialized
    ) internal {
        LaunchBuyContext storage context = _launchBuyContext;
        if (context.state != LaunchBuyContextState.ARMED) revert LaunchBuyMultipleSwaps();
        if (PoolId.unwrap(context.poolId) != PoolId.unwrap(poolId) || context.swapCaller != sender) {
            revert LaunchBuyContextMismatch(context.poolId, poolId, context.swapCaller, sender);
        }
        if (params.amountSpecified >= 0) revert LaunchBuyExactOutputUnsupported();
        if (!poolInitialized || !quoteIsSpecified) revert InvalidLaunchBuyDirection();
        context.state = LaunchBuyContextState.EXECUTING;
    }

    function _matchLaunchBuyContextAfterSwap(
        PoolId poolId,
        address sender,
        IPoolManager.SwapParams calldata params,
        bool quoteIsSpecified,
        bool poolInitialized
    ) internal view {
        LaunchBuyContext storage context = _launchBuyContext;
        if (context.state != LaunchBuyContextState.EXECUTING) revert LaunchBuyContextMissing();
        if (PoolId.unwrap(context.poolId) != PoolId.unwrap(poolId) || context.swapCaller != sender) {
            revert LaunchBuyContextMismatch(context.poolId, poolId, context.swapCaller, sender);
        }
        if (params.amountSpecified >= 0) revert LaunchBuyExactOutputUnsupported();
        if (!poolInitialized || !quoteIsSpecified) revert InvalidLaunchBuyDirection();
    }

    function _consumeLaunchBuyContextAfterSwap(PoolConfig memory cfg, BalanceDelta delta) internal {
        int128 tokenOutput = cfg.tokenIsCurrency0 ? delta.amount0() : delta.amount1();
        if (tokenOutput <= 0) revert ZeroLaunchBuyOutput();
        _launchBuyContext.state = LaunchBuyContextState.CONSUMED;
    }
}

src/tax/TaxLaunchOperations.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";
import {TaxLaunchpadFactoryCore as Core} from "./TaxLaunchpadFactoryCore.sol";
import {TaxLaunchValidation} from "./TaxLaunchValidation.sol";
import {TaxFeeMath} from "./TaxFeeMath.sol";

import {TaxLaunchHook} from "./TaxLaunchHook.sol";
import {TaxLaunchToken} from "./TaxLaunchToken.sol";
import {TaxLaunchTokenDeployer} from "./TaxLaunchTokenDeployer.sol";
import {TaxDividendDeployer} from "./TaxDividendDeployer.sol";
import {TaxDividend} from "./TaxDividend.sol";
import {FeeEscrow} from "../FeeEscrow.sol";
import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";

/// @notice Statically linked launch execution. Delegate execution preserves factory-only wiring and atomic rollback.
/// @dev No mutable implementation, selector dispatcher, generic executor, or independently held launch assets.
library TaxLaunchOperations {
    struct PolicyState {
        TaxFeeMath.TaxPolicy policy;
    }
    event TaxPolicyUpdated(uint64 indexed configVersion, TaxFeeMath.TaxPolicy policy);
    event CreatorFeeRecipientUpdated(
        address indexed token, address indexed previousCreatorFeeRecipient, address indexed newCreatorFeeRecipient
    );
    event CreatorRightsTransferred(
        address indexed token,
        address indexed previousCreator,
        address indexed newCreator,
        address previousCreatorFeeRecipient,
        address newCreatorFeeRecipient
    );

    function setCreatorFeeRecipient(
        Core.CreatorRights storage rights,
        address token,
        address recipient,
        TaxLaunchValidation validation,
        TaxLaunchHook hook
    ) public {
        validation.validateFeeRecipient(recipient, Core(address(this)));
        address previousRecipient = rights.creatorFeeRecipient;
        if (previousRecipient == recipient) return;
        rights.creatorFeeRecipient = recipient;
        hook.updateCreatorRights(rights.poolId, rights.currentCreator, recipient);
        emit CreatorFeeRecipientUpdated(token, previousRecipient, recipient);
    }

    function transferCreatorRights(
        Core.CreatorRights storage rights,
        address token,
        address newCreator,
        TaxLaunchValidation validation,
        TaxLaunchHook hook
    ) public {
        validation.validateFeeRecipient(newCreator, Core(address(this)));
        address previousCreator = rights.currentCreator;
        address previousRecipient = rights.creatorFeeRecipient;
        _applyCreatorRightsTransition(rights, newCreator, newCreator, hook);
        emit CreatorRightsTransferred(token, previousCreator, newCreator, previousRecipient, newCreator);
    }

    function _applyCreatorRightsTransition(
        Core.CreatorRights storage rights,
        address newCreator,
        address recipient,
        TaxLaunchHook hook
    ) private {
        rights.currentCreator = newCreator;
        rights.creatorFeeRecipient = recipient;
        rights.pendingCreator = address(0);
        hook.updateCreatorRights(rights.poolId, newCreator, recipient);
    }

    function applyTaxPolicy(
        PolicyState storage state,
        TaxFeeMath.TaxPolicy memory policy,
        TaxLaunchValidation validation,
        TaxLaunchHook hook,
        uint256 supply
    ) public returns (bool) {
        validation.validateTaxPolicy(policy, supply, address(this), hook);
        return _storeTaxPolicy(state, policy);
    }

    function initializeTaxPolicy(
        PolicyState storage state,
        TaxFeeMath.TaxPolicy memory policy,
        TaxLaunchValidation validation,
        TaxLaunchHook hook,
        uint256 supply
    ) public {
        validation.validateInitialTaxPolicy(policy, supply, address(this), hook);
        _storeTaxPolicy(state, policy);
    }

    function _storeTaxPolicy(PolicyState storage state, TaxFeeMath.TaxPolicy memory policy) private returns (bool) {
        // Validation precedes comparison, including recipient checks for previously valid settings.
        if (keccak256(abi.encode(state.policy)) == keccak256(abi.encode(policy))) return false;
        state.policy = policy;
        return true;
    }

    function emitTaxPolicy(PolicyState storage state, uint64 configVersion) public {
        emit TaxPolicyUpdated(configVersion, state.policy);
    }

    function setDefaultExclusion(
        address[] storage accounts,
        mapping(address => uint256) storage indices,
        address account,
        bool excluded
    ) public returns (bool) {
        if (account == address(0)) revert InvalidConfig();
        uint256 index = indices[account];
        if (excluded) {
            if (index != 0) return false;
            if (accounts.length == TaxSuiteConstants.MAX_BATCH_SIZE) revert OutOfBounds();
            accounts.push(account);
            indices[account] = accounts.length;
        } else {
            if (index == 0) return false;
            address last = accounts[accounts.length - 1];
            accounts[index - 1] = last;
            indices[last] = index;
            accounts.pop();
            delete indices[account];
        }
        return true;
    }

    struct Context {
        TaxLaunchHook hook;
        TaxLaunchTokenDeployer tokenDeployer;
        TaxDividendDeployer dividendDeployer;
        TaxFeeMath.TaxPolicy admittedPolicy;
    }
    error InvalidConfig();
    error TokenMismatch();
    error NotImmutable();
    error OutOfBounds();

    function create(
        Context memory context,
        Core.LaunchParams calldata params,
        Core.LaunchPreparation memory preparation,
        address[] storage defaultExclusions,
        address originalCreator
    ) public returns (address token, PoolId poolId, PoolKey memory key) {
        TaxLaunchToken.GenesisParams memory genesis = tokenParams(params, preparation.supply, context.hook);
        token = context.tokenDeployer.deploy(preparation.scopedSalt, genesis);
        if (token != preparation.predictedToken) revert TokenMismatch();
        address dividend;
        if (params.taxConfiguration.dividendAllocationShare != 0) {
            dividend = context.dividendDeployer.deploy(preparation.scopedSalt);
            if (dividend == params.creatorFeeRecipient || dividend == params.integratorFeeRecipient) {
                revert InvalidConfig();
            }
            if (dividend == context.admittedPolicy.protocolFeeConfiguration.protocolFeeRecipient) {
                revert InvalidConfig();
            }
            TaxDividend(payable(dividend))
                .initialize(
                    TaxDividend.Initialization({
                    factory: address(this),
                    taxToken: token,
                    quoteToken: params.quoteToken,
                    hook: address(context.hook),
                    feeEscrow: FeeEscrow(payable(context.hook.feeEscrow())),
                    minimumDividendHolding: params.taxConfiguration.minimumDividendHolding,
                    defaultExclusions: defaultExclusions
                })
                );
            TaxLaunchToken(token).initializeDividend(dividend);
        }
        TaxLaunchToken asset = TaxLaunchToken(token);
        if (
            asset.factory() != address(this) || asset.totalSupply() != preparation.supply
                || asset.supplyCap() != preparation.supply || asset.decimals() != 18
                || asset.hasRole(asset.DEFAULT_ADMIN_ROLE(), originalCreator)
                || asset.metadataAuthority() != genesis.metadataAuthority
                || asset.hasRole(asset.METADATA_ROLE(), address(this)) != params.metadataEditable
        ) revert NotImmutable();
        Currency c0 = Currency.wrap(params.quoteToken);
        Currency c1 = Currency.wrap(token);
        if (preparation.tokenIsCurrency0) {
            c0 = Currency.wrap(token);
            c1 = Currency.wrap(params.quoteToken);
        }
        key = PoolKey(c0, c1, 0, preparation.spacing, IHooks(address(context.hook)));
        int24 initialTick = preparation.startTick;
        if (preparation.tokenIsCurrency0) initialTick -= preparation.spacing;
        if (initialTick < TickMath.MIN_TICK || initialTick > TickMath.MAX_TICK) revert OutOfBounds();
        context.hook.poolManager().initialize(key, TickMath.getSqrtPriceAtTick(initialTick));
        TaxLaunchHook.PoolRegistration memory registration = TaxLaunchHook.PoolRegistration({
            token: token,
            creator: originalCreator,
            launcher: msg.sender,
            creatorFeeRecipient: params.creatorFeeRecipient,
            feeSlots: params.feeSlots,
            integratorFeeRecipient: params.integratorFeeRecipient,
            dividend: dividend,
            launchTime: uint48(block.timestamp),
            antiSnipeEnabled: params.antiSnipeEnabled,
            admittedPolicy: context.admittedPolicy,
            taxConfiguration: params.taxConfiguration
        });
        context.hook.registerPool(key, registration);
        context.hook.seedLiquidity(key, preparation.seedPositions, preparation.tokenIsCurrency0);
        return (token, key.toId(), key);
    }

    function predictTokenAddress(
        TaxLaunchTokenDeployer deployer,
        Core.LaunchParams calldata params,
        bytes32 salt,
        uint256 supply,
        TaxLaunchHook hook
    ) public view returns (address) {
        return deployer.predictTokenAddress(salt, tokenParams(params, supply, hook));
    }

    function tokenInitCodeHash(
        TaxLaunchTokenDeployer deployer,
        Core.LaunchParams calldata params,
        uint256 supply,
        TaxLaunchHook hook
    ) public view returns (bytes32) {
        return deployer.tokenInitCodeHash(tokenParams(params, supply, hook));
    }

    function tokenParams(Core.LaunchParams calldata params, uint256 supply, TaxLaunchHook hook)
        internal
        view
        returns (TaxLaunchToken.GenesisParams memory genesis)
    {
        address metadataAuthority;
        if (params.metadataEditable) metadataAuthority = address(this);
        genesis.factory = address(this);
        genesis.dividendsEnabled = params.taxConfiguration.dividendAllocationShare != 0;
        genesis.tokenName = params.tokenName;
        genesis.tokenSymbol = params.tokenSymbol;
        genesis.tokenContractURI = params.tokenContractURI;
        genesis.metadataAuthority = metadataAuthority;
        genesis.initialRecipient = address(hook);
        genesis.initialSupply = supply;
        genesis.metadataKeys = params.metadataKeys;
        genesis.metadataValues = params.metadataValues;
    }
}

src/tax/TaxLaunchToken.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ITaxDividend} from "./interfaces/ITaxDividend.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";

/// @title TaxLaunchToken
/// @notice Fixed-supply ERC20 for the separate tax suite, with optional permanent dividend binding. The constructor mints once to
///         one factory-supplied genesis recipient. There is no owner, minter, burner, pauser, upgrade hook, or admin.
contract TaxLaunchToken is IERC20, IERC20Metadata, IERC20Errors {
    struct GenesisParams {
        address factory;
        bool dividendsEnabled;
        string tokenName;
        string tokenSymbol;
        string tokenContractURI;
        address metadataAuthority;
        address initialRecipient;
        uint256 initialSupply;
        string[] metadataKeys;
        string[] metadataValues;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = bytes32(0);
    bytes32 public constant METADATA_ROLE = keccak256("METADATA_ROLE");

    uint8 public constant decimals = 18;

    address public immutable factory;
    address public dividend;
    bool public immutable dividendsEnabled;
    address private immutable _genesisRecipient;
    address public immutable metadataAuthority;
    uint256 public immutable supplyCap;

    string private _name;
    string private _symbol;
    string public contractURI;

    mapping(address account => uint256 balance) private _balances;
    mapping(address owner => mapping(address spender => uint256 amount)) private _allowances;
    mapping(string metadataKey => string metadataValue) public extraMetadata;

    event DividendInitialized(address indexed dividendContract);

    event ContractURIUpdated(address indexed updater, string newContractURI);
    event NameUpdated(address indexed updater, string newName);
    event SymbolUpdated(address indexed updater, string newSymbol);
    event ExtraMetadataUpdated(address indexed updater, string metadataKey, string metadataValue);

    error InvalidConfig();
    error MetadataUnauthorized(address account);

    constructor(GenesisParams memory genesisParams) {
        if (
            genesisParams.factory == address(0) || bytes(genesisParams.tokenName).length == 0
                || bytes(genesisParams.tokenSymbol).length == 0 || genesisParams.initialRecipient == address(0)
                || genesisParams.initialSupply == 0
                || genesisParams.metadataKeys.length != genesisParams.metadataValues.length
        ) revert InvalidConfig();

        factory = genesisParams.factory;
        dividendsEnabled = genesisParams.dividendsEnabled;
        _genesisRecipient = genesisParams.initialRecipient;
        metadataAuthority = genesisParams.metadataAuthority;
        _name = genesisParams.tokenName;
        _symbol = genesisParams.tokenSymbol;
        contractURI = genesisParams.tokenContractURI;
        supplyCap = genesisParams.initialSupply;
        _balances[genesisParams.initialRecipient] = genesisParams.initialSupply;
        emit Transfer(address(0), genesisParams.initialRecipient, genesisParams.initialSupply);

        for (uint256 i = 0; i < genesisParams.metadataKeys.length; i++) {
            string memory metadataKey = genesisParams.metadataKeys[i];
            if (bytes(metadataKey).length == 0) revert InvalidConfig();
            string memory metadataValue = genesisParams.metadataValues[i];
            extraMetadata[metadataKey] = metadataValue;
            emit ExtraMetadataUpdated(genesisParams.factory, metadataKey, metadataValue);
        }
    }

    function name() external view returns (string memory) {
        return _name;
    }

    /// @dev Factory-only initialization within creation, before genesis tokens can move. Disabled tokens cannot attach one.
    function initializeDividend(address dividendContract) external {
        if (msg.sender != factory || !dividendsEnabled || dividend != address(0) || dividendContract.code.length == 0) {
            revert InvalidConfig();
        }
        ITaxDividend tracker = ITaxDividend(dividendContract);
        if (tracker.taxToken() != address(this) || tracker.owner() != factory || tracker.hook() != _genesisRecipient) {
            revert InvalidConfig();
        }
        dividend = dividendContract;
        emit DividendInitialized(dividendContract);
    }

    function symbol() external view returns (string memory) {
        return _symbol;
    }

    function totalSupply() external view returns (uint256) {
        return supplyCap;
    }

    function balanceOf(address account) external view returns (uint256) {
        return _balances[account];
    }

    function allowance(address owner, address spender) external view returns (uint256) {
        return _allowances[owner][spender];
    }

    function transfer(address to, uint256 amount) external returns (bool) {
        _transfer(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        uint256 allowed = _allowances[from][msg.sender];
        if (allowed != type(uint256).max) {
            if (allowed < amount) revert ERC20InsufficientAllowance(msg.sender, allowed, amount);
            unchecked {
                _allowances[from][msg.sender] = allowed - amount;
            }
        }
        _transfer(from, to, amount);
        return true;
    }

    function updateName(string calldata newName) external onlyMetadata {
        if (bytes(newName).length == 0) revert InvalidConfig();
        _name = newName;
        emit NameUpdated(msg.sender, newName);
    }

    function updateSymbol(string calldata newSymbol) external onlyMetadata {
        if (bytes(newSymbol).length == 0) revert InvalidConfig();
        _symbol = newSymbol;
        emit SymbolUpdated(msg.sender, newSymbol);
    }

    function updateContractURI(string calldata newContractURI) external onlyMetadata {
        contractURI = newContractURI;
        emit ContractURIUpdated(msg.sender, newContractURI);
    }

    function updateExtraMetadata(string calldata metadataKey, string calldata metadataValue) external onlyMetadata {
        if (bytes(metadataKey).length == 0) revert InvalidConfig();
        extraMetadata[metadataKey] = metadataValue;
        emit ExtraMetadataUpdated(msg.sender, metadataKey, metadataValue);
    }

    function hasRole(bytes32 role, address account) external view returns (bool granted) {
        return role == METADATA_ROLE && account != address(0) && account == metadataAuthority;
    }

    modifier onlyMetadata() {
        if (msg.sender != metadataAuthority) revert MetadataUnauthorized(msg.sender);
        _;
    }

    function _transfer(address from, address to, uint256 amount) internal {
        if (dividendsEnabled && dividend == address(0)) revert InvalidConfig();
        if (from == address(0)) revert ERC20InvalidSender(address(0));
        if (to == address(0)) revert ERC20InvalidReceiver(address(0));
        uint256 bal = _balances[from];
        if (bal < amount) revert ERC20InsufficientBalance(from, bal, amount);
        unchecked {
            _balances[from] = bal - amount;
            _balances[to] += amount;
        }
        emit Transfer(from, to, amount);
        address tracker = dividend;
        if (tracker != address(0)) {
            ITaxDividend(tracker).setShare(from, _balances[from]);
            if (to != from) ITaxDividend(tracker).setShare(to, _balances[to]);
        }
    }

    function _approve(address owner, address spender, uint256 amount) internal {
        if (owner == address(0)) revert ERC20InvalidApprover(address(0));
        if (spender == address(0)) revert ERC20InvalidSpender(address(0));
        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }
}

src/tax/TaxLaunchTokenDeployer.sol

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

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

interface ITaxLaunchTokenFactory {
    function tokenDeployer() external view returns (address);
}

/// @title TaxLaunchTokenDeployer
/// @notice One-purpose CREATE2 deployer for ERC20 launch tokens. It keeps token creation bytecode out of the
///         ERC20 launchpad factory while preserving deterministic token addresses and genesis metadata.
contract TaxLaunchTokenDeployer {
    address public immutable factoryInitializer;
    address public factory;

    error AlreadyInitialized();
    error InvalidConfig();
    error TokenAlreadyExists(address token);
    error Unauthorized();

    constructor(address factoryInitializerAddress) {
        if (factoryInitializerAddress == address(0)) revert InvalidConfig();
        factoryInitializer = factoryInitializerAddress;
    }

    function initializeFactory(address factoryAddress) external {
        if (msg.sender != factoryInitializer) revert Unauthorized();
        if (factory != address(0)) revert AlreadyInitialized();
        if (factoryAddress == address(0) || factoryAddress.code.length == 0) revert InvalidConfig();
        if (ITaxLaunchTokenFactory(factoryAddress).tokenDeployer() != address(this)) revert InvalidConfig();
        factory = factoryAddress;
    }

    function predictTokenAddress(bytes32 scopedSalt, TaxLaunchToken.GenesisParams calldata genesisParams)
        external
        view
        returns (address predictedToken)
    {
        return _predictTokenAddress(scopedSalt, genesisParams);
    }

    function tokenInitCodeHash(TaxLaunchToken.GenesisParams calldata genesisParams)
        external
        pure
        returns (bytes32 initCodeHash)
    {
        return _tokenInitCodeHash(genesisParams);
    }

    function deploy(bytes32 scopedSalt, TaxLaunchToken.GenesisParams calldata genesisParams)
        external
        returns (address token)
    {
        address factoryAddress = factory;
        if (msg.sender != factoryAddress) revert Unauthorized();
        if (genesisParams.factory != factoryAddress) revert InvalidConfig();
        token = _predictTokenAddress(scopedSalt, genesisParams);
        if (token.code.length != 0) revert TokenAlreadyExists(token);
        return address(new TaxLaunchToken{salt: scopedSalt}(genesisParams));
    }

    function _predictTokenAddress(bytes32 scopedSalt, TaxLaunchToken.GenesisParams calldata genesisParams)
        internal
        view
        returns (address predictedToken)
    {
        bytes32 initCodeHash = _tokenInitCodeHash(genesisParams);
        return
            address(
                uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), scopedSalt, initCodeHash))))
            );
    }

    function _tokenInitCodeHash(TaxLaunchToken.GenesisParams calldata genesisParams)
        internal
        pure
        returns (bytes32 initCodeHash)
    {
        return keccak256(abi.encodePacked(type(TaxLaunchToken).creationCode, abi.encode(genesisParams)));
    }
}

src/tax/TaxLaunchValidation.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxLaunchOperations} from "./TaxLaunchOperations.sol";
import {ITaxDividendClaimHelper} from "./interfaces/ITaxDividendClaimHelper.sol";
import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";
import {TaxLaunchpadFactoryCore} from "./TaxLaunchpadFactoryCore.sol";
import {TaxLaunchHook} from "./TaxLaunchHook.sol";
import {TaxLaunchToken} from "./TaxLaunchToken.sol";
import {ITaxLaunchTokenFactory} from "./TaxLaunchTokenDeployer.sol";
import {ITaxDividendFactory, TaxDividendDeployer} from "./TaxDividendDeployer.sol";
import {TaxFeeMath} from "./TaxFeeMath.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {LiquidityAmounts} from "v4-core/test/utils/LiquidityAmounts.sol";
import {AnnouncementRegistry} from "../AnnouncementRegistry.sol";
import {ILaunchBuyAdapter} from "../interfaces/ILaunchBuyAdapter.sol";

/// @notice Stateless validation and genesis calculations, with no asset forwarding or recovery functionality.
contract TaxLaunchValidation {
    uint256 private constant BPS = TaxSuiteConstants.BPS;
    int24 private constant TAIL = type(int24).max;
    uint256 private constant MAX_BANDS = TaxSuiteConstants.MAX_BANDS;
    error InvalidConfig();
    error OutOfBounds();
    error MisalignedOffset();
    error AntiSnipeUnavailable();

    struct RecipientContext {
        address factory;
        TaxLaunchHook hook;
        address tokenDeployer;
        address dividendDeployer;
        address dividendImplementation;
        address dividendClaimHelper;
        address announcementRegistry;
        address launchBuyAdapter;
        address launchBuyRouter;
        address launchBuySwapCaller;
        bool checkLaunchRecords;
    }

    function validatePoolRegistration(TaxLaunchHook.PoolRegistration calldata registration)
        external
        view
        returns (uint8 creatorSlotIndex)
    {
        TaxLaunchHook hook = TaxLaunchHook(msg.sender);
        bool enabled = TaxFeeMath.validateTax(
            registration.taxConfiguration, registration.admittedPolicy, TaxLaunchToken(registration.token).totalSupply()
        );
        if (registration.antiSnipeEnabled && registration.admittedPolicy.antiSnipeConfiguration.windowSeconds == 0) {
            revert TaxLaunchHook.AntiSnipeUnavailable();
        }
        if (enabled != (registration.dividend != address(0)) || registration.creator == address(0)) {
            revert TaxLaunchHook.InvalidFeeConfig();
        }
        _validateHookRecipient(registration.creatorFeeRecipient, hook);
        _validateHookRecipient(registration.admittedPolicy.protocolFeeConfiguration.protocolFeeRecipient, hook);
        if (registration.integratorFeeRecipient != address(0)) {
            _validateHookRecipient(registration.integratorFeeRecipient, hook);
        } else if (registration.taxConfiguration.integratorAllocationShare != 0) {
            revert TaxLaunchHook.InvalidFeeConfig();
        }
        if (
            registration.dividend != address(0)
                && (registration.creatorFeeRecipient == registration.dividend
                    || registration.integratorFeeRecipient == registration.dividend
                    || registration.admittedPolicy.protocolFeeConfiguration.protocolFeeRecipient
                        == registration.dividend)
        ) revert TaxLaunchHook.InvalidFeeConfig();
        if (registration.feeSlots.length != 0) {
            creatorSlotIndex = _validateFeeSlots(registration, TaxLaunchpadFactoryCore(hook.factory()));
        }
    }

    function _validateHookRecipient(address recipient, TaxLaunchHook hook) private view {
        if (
            recipient == address(0) || recipient == address(hook) || recipient == hook.factory()
                || recipient == hook.feeEscrow() || recipient == address(hook.poolManager())
                || hook.isDividendContract(recipient)
        ) revert TaxLaunchHook.InvalidFeeConfig();
    }

    function _validateFeeSlots(TaxLaunchHook.PoolRegistration calldata registration, TaxLaunchpadFactoryCore factory)
        private
        view
        returns (uint8 creatorSlotIndex)
    {
        TaxLaunchHook.FeeSlotInput[] calldata slots = registration.feeSlots;
        if (slots.length > 7) revert TaxLaunchHook.InvalidFeeSlots();
        RecipientContext memory context = _recipientContext(factory, factory.hook());
        uint256 totalWeight;
        for (uint256 i; i < slots.length; ++i) {
            TaxLaunchHook.FeeSlotInput calldata slot = slots[i];
            if (slot.relativeWeightBps == 0) revert TaxLaunchHook.InvalidFeeSlots();
            totalWeight += slot.relativeWeightBps;
            _validateRecipient(slot.recipient, context);
            _validateRecipient(slot.admin, context);
            if (slot.recipient == registration.token || slot.admin == registration.token) {
                revert TaxLaunchHook.InvalidFeeConfig();
            }
            if (slot.recipient == registration.dividend || slot.admin == registration.dividend) {
                revert InvalidConfig();
            }
            if (slot.isCreator) {
                if (
                    creatorSlotIndex != 0 || slot.recipient != registration.creatorFeeRecipient
                        || slot.admin != registration.creator
                ) {
                    revert TaxLaunchHook.InvalidFeeSlots();
                }
                creatorSlotIndex = uint8(i + 1);
            }
        }
        if (totalWeight != BPS) revert TaxLaunchHook.InvalidFeeSlots();
    }

    function validateFeeRecipient(address recipient, TaxLaunchpadFactoryCore factory) external view {
        _validateRecipient(recipient, _recipientContext(factory, factory.hook()));
    }

    function validateLaunchRecipients(
        TaxLaunchpadFactoryCore factory,
        address creatorFeeRecipient,
        address integratorFeeRecipient,
        address predictedToken,
        bytes32 scopedSalt,
        bool dividendsEnabled
    ) external view {
        RecipientContext memory context = _recipientContext(factory, factory.hook());
        address predictedDividend;
        if (dividendsEnabled) {
            predictedDividend = TaxDividendDeployer(context.dividendDeployer).predictDividendAddress(scopedSalt);
        }
        _validateLaunchRecipient(creatorFeeRecipient, context, predictedToken, predictedDividend);
        if (integratorFeeRecipient != address(0)) {
            _validateLaunchRecipient(integratorFeeRecipient, context, predictedToken, predictedDividend);
        }
        _validateConfiguredRecipients(factory, context, predictedToken, predictedDividend);
    }

    function validateFactoryWiring(TaxLaunchpadFactoryCore factory) external view {
        TaxLaunchHook hook = factory.hook();
        address registry = factory.announcementRegistry();
        address escrow = hook.feeEscrow();
        if (
            registry == address(0) || registry.code.length == 0
                || AnnouncementRegistry(registry).factory() != address(factory) || !hook.wired()
                || hook.factory() != address(factory) || escrow == address(0) || escrow.code.length == 0
        ) revert InvalidConfig();
        RecipientContext memory context = _recipientContext(factory, hook);
        if (ITaxDividendClaimHelper(context.dividendClaimHelper).factory() != address(factory)) revert InvalidConfig();
        _validateConfiguredRecipients(factory, context, address(0), address(0));
    }

    /// @dev The derived constructor supplies bindings explicitly; the factory has no runtime getters yet.
    function validateInitialDeploymentRecipients(
        address protocolFeeRecipient,
        address factory,
        TaxLaunchHook hook,
        address tokenDeployer,
        TaxDividendDeployer dividendDeployer
    ) external view {
        RecipientContext memory context = _initialRecipientContext(factory, hook);
        context.tokenDeployer = tokenDeployer;
        context.dividendDeployer = address(dividendDeployer);
        context.dividendImplementation = address(dividendDeployer.implementation());
        context.dividendClaimHelper = dividendDeployer.implementation().claimHelper();
        if (ITaxDividendClaimHelper(context.dividendClaimHelper).hook() != address(hook)) revert InvalidConfig();
        _validateRecipient(protocolFeeRecipient, context);
    }

    function validateLaunchTax(
        TaxFeeMath.TaxConfiguration calldata tax,
        TaxFeeMath.TaxPolicy calldata policy,
        uint256 supply,
        bool antiSnipeEnabled
    ) external pure {
        TaxFeeMath.validateTax(tax, policy, supply);
        if (antiSnipeEnabled && policy.antiSnipeConfiguration.windowSeconds == 0) revert AntiSnipeUnavailable();
    }

    function previewTaxConfiguration(
        TaxFeeMath.TaxConfiguration calldata tax,
        TaxFeeMath.TaxPolicy calldata policy,
        uint256 supply,
        uint64 configVersion
    ) external pure returns (TaxFeeMath.TaxConfigurationPreview memory preview) {
        preview.dividendsEnabled = TaxFeeMath.validateTax(tax, policy, supply);
        preview.configVersion = configVersion;
        preview.minimumDividendHoldingRequirement = policy.minimumDividendHoldingRequirement;
        preview.buyRates = TaxFeeMath.rates(tax.buyTaxRate, policy.protocolFeeConfiguration, tax, 0);
        preview.sellRates = TaxFeeMath.rates(tax.sellTaxRate, policy.protocolFeeConfiguration, tax, 0);
    }

    function resolveSeedPositions(
        TaxLaunchpadFactoryCore.Band[] memory tmpl,
        int24 startTick,
        int24 spacing,
        bool tokenIsCurrency0,
        uint256 supply
    ) external pure returns (TaxLaunchHook.SeedPosition[] memory positions) {
        positions = new TaxLaunchHook.SeedPosition[](tmpl.length);
        // forge-lint: disable-next-line(divide-before-multiply) the truncation IS the alignment
        int24 maxUsable = (TickMath.MAX_TICK / spacing) * spacing;
        // forge-lint: disable-next-line(divide-before-multiply) the truncation IS the alignment
        int24 minUsable = (TickMath.MIN_TICK / spacing) * spacing;

        for (uint256 i = 0; i < tmpl.length; i++) {
            if (tmpl[i].lowerOffset % spacing != 0) revert MisalignedOffset();
            if (tmpl[i].upperOffset != TAIL && tmpl[i].upperOffset % spacing != 0) revert MisalignedOffset();

            int24 tickLower;
            int24 tickUpper;
            if (tokenIsCurrency0) {
                tickLower = startTick + tmpl[i].lowerOffset;
                tickUpper = tmpl[i].upperOffset == TAIL ? maxUsable : startTick + tmpl[i].upperOffset;
            } else {
                tickUpper = startTick - tmpl[i].lowerOffset;
                tickLower = tmpl[i].upperOffset == TAIL ? minUsable : startTick - tmpl[i].upperOffset;
            }
            if (tickLower >= tickUpper) revert OutOfBounds();

            uint256 amount = supply * tmpl[i].supplyShareBps / BPS;
            uint160 sqrtA = TickMath.getSqrtPriceAtTick(tickLower);
            uint160 sqrtB = TickMath.getSqrtPriceAtTick(tickUpper);
            uint128 liquidity = tokenIsCurrency0
                ? LiquidityAmounts.getLiquidityForAmount0(sqrtA, sqrtB, amount)
                : LiquidityAmounts.getLiquidityForAmount1(sqrtA, sqrtB, amount);
            if (liquidity == 0 || liquidity >= uint128(type(int128).max)) revert OutOfBounds();

            positions[i] =
                TaxLaunchHook.SeedPosition({tickLower: tickLower, tickUpper: tickUpper, liquidity: liquidity});
        }
    }

    function validateBandTemplate(TaxLaunchpadFactoryCore.Band[] memory newBands, int24 spacing) external pure {
        if (newBands.length == 0 || newBands.length > MAX_BANDS) revert OutOfBounds();
        if (newBands[0].lowerOffset != 0) revert InvalidConfig();
        uint256 totalBps;
        for (uint256 i = 0; i < newBands.length; i++) {
            bool isTail = newBands[i].upperOffset == TAIL;
            if (
                newBands[i].lowerOffset < 0 || newBands[i].supplyShareBps == 0 || (isTail && i != newBands.length - 1)
                    || (!isTail && newBands[i].upperOffset <= newBands[i].lowerOffset)
            ) {
                revert InvalidConfig();
            }
            if (newBands[i].lowerOffset % spacing != 0 || (!isTail && newBands[i].upperOffset % spacing != 0)) {
                revert MisalignedOffset();
            }
            totalBps += newBands[i].supplyShareBps;
        }
        if (totalBps != BPS) revert InvalidConfig();
    }

    function validateTaxPolicy(
        TaxFeeMath.TaxPolicy calldata policy,
        uint256 supply,
        address factory,
        TaxLaunchHook hook
    ) external view {
        TaxFeeMath.validatePolicy(policy, supply);
        _validateRecipient(
            policy.protocolFeeConfiguration.protocolFeeRecipient,
            _recipientContext(TaxLaunchpadFactoryCore(factory), hook)
        );
    }

    /// @dev Constructor validation uses explicit bindings before runtime getters exist.
    function validateInitialTaxPolicy(
        TaxFeeMath.TaxPolicy calldata policy,
        uint256 supply,
        address factory,
        TaxLaunchHook hook
    ) external view {
        TaxFeeMath.validatePolicy(policy, supply);
        _validateRecipient(
            policy.protocolFeeConfiguration.protocolFeeRecipient, _initialRecipientContext(factory, hook)
        );
    }

    function _initialRecipientContext(address factory, TaxLaunchHook hook)
        private
        view
        returns (RecipientContext memory context)
    {
        context.factory = factory;
        context.hook = hook;
        context.launchBuyAdapter = hook.launchBuyAdapter();
        if (context.launchBuyAdapter != address(0)) {
            if (context.launchBuyAdapter.code.length == 0) revert InvalidConfig();
            ILaunchBuyAdapter adapter = ILaunchBuyAdapter(context.launchBuyAdapter);
            context.launchBuyRouter = adapter.router();
            context.launchBuySwapCaller = adapter.swapCaller();
            if (
                context.launchBuyRouter == address(0) || context.launchBuyRouter.code.length == 0
                    || context.launchBuySwapCaller == address(0) || context.launchBuySwapCaller.code.length == 0
            ) revert InvalidConfig();
        }
    }

    function _recipientContext(TaxLaunchpadFactoryCore factory, TaxLaunchHook hook)
        private
        view
        returns (RecipientContext memory context)
    {
        context = _initialRecipientContext(address(factory), hook);
        context.tokenDeployer = ITaxLaunchTokenFactory(address(factory)).tokenDeployer();
        context.dividendDeployer = ITaxDividendFactory(address(factory)).dividendDeployer();
        context.dividendImplementation = address(TaxDividendDeployer(context.dividendDeployer).implementation());
        context.dividendClaimHelper = TaxDividendDeployer(context.dividendDeployer).implementation().claimHelper();
        context.announcementRegistry = factory.announcementRegistry();
        context.checkLaunchRecords = true;
    }

    function _validateConfiguredRecipients(
        TaxLaunchpadFactoryCore factory,
        RecipientContext memory context,
        address predictedToken,
        address predictedDividend
    ) private view {
        _validateLaunchRecipient(
            factory.taxPolicy().protocolFeeConfiguration.protocolFeeRecipient,
            context,
            predictedToken,
            predictedDividend
        );
    }

    function _validateLaunchRecipient(
        address recipient,
        RecipientContext memory context,
        address predictedToken,
        address predictedDividend
    ) private view {
        if (recipient == predictedToken || recipient == predictedDividend) {
            revert InvalidConfig();
        }
        _validateRecipient(recipient, context);
    }

    function _validateRecipient(address recipient, RecipientContext memory context) private view {
        TaxLaunchHook hook = context.hook;
        if (
            recipient == address(0) || recipient == context.factory || recipient == address(hook)
                || recipient == address(hook.poolManager()) || recipient == hook.feeEscrow()
                || hook.isDividendContract(recipient) || recipient == address(this)
                || recipient == address(TaxLaunchOperations) || recipient == context.tokenDeployer
                || recipient == context.dividendDeployer || recipient == context.dividendImplementation
                || recipient == context.dividendClaimHelper || recipient == context.announcementRegistry
                || recipient == context.launchBuyAdapter || recipient == context.launchBuyRouter
                || recipient == context.launchBuySwapCaller
        ) revert InvalidConfig();
        if (context.checkLaunchRecords && TaxLaunchpadFactoryCore(context.factory).isLaunchToken(recipient)) {
            revert InvalidConfig();
        }
    }
}

src/tax/TaxLaunchpadFactoryCore.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxSuiteConstants} from "./TaxSuiteConstants.sol";
import {ITaxFeeAdmin} from "./interfaces/ITaxFeeAdmin.sol";

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {TaxLaunchValidation} from "./TaxLaunchValidation.sol";

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

import {TaxFeeMath} from "./TaxFeeMath.sol";
import {TaxDividend} from "./TaxDividend.sol";
import {TaxLaunchToken} from "./TaxLaunchToken.sol";

import {TaxLaunchHook} from "./TaxLaunchHook.sol";
import {AnnouncementRegistry} from "../AnnouncementRegistry.sol";
import {ICreatorRightsReceiver} from "../interfaces/ICreatorRightsReceiver.sol";
import {ILaunchTokenMetadata} from "../interfaces/ILaunchTokenMetadata.sol";
import {ILaunchBuyAdapter} from "../interfaces/ILaunchBuyAdapter.sol";

/// @title TaxLaunchpadFactoryCore
/// @notice Shared genesis + governance for single-sided Uniswap v4 launchpads. Concrete factories provide the
///         token creation primitive while this core keeps quote registry, creator rights, pool creation, seed math,
///         locked-liquidity invariants, fee configuration, and event emission consistent across chains.
abstract contract TaxLaunchpadFactoryCore is Ownable2Step, ReentrancyGuard, ITaxFeeAdmin {
    /// @notice Sentinel `upperOffset` meaning "extend to the furthest usable tick on the token side".
    int24 internal constant TAIL = type(int24).max;

    uint256 public constant MIN_SUPPLY = TaxSuiteConstants.MIN_SUPPLY;
    uint256 public constant MAX_SUPPLY = TaxSuiteConstants.MAX_SUPPLY;
    uint256 public constant PERCENTAGE_SCALE = TaxSuiteConstants.PERCENTAGE_SCALE;
    uint256 internal constant MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH = TaxSuiteConstants.MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH;

    IPoolManager public immutable poolManager;
    TaxLaunchHook public immutable hook;
    TaxLaunchValidation public immutable launchValidation;

    /// @notice A registered quote. `startTickToken0Frame` is the opening tick assuming the launch token sorts
    ///         as currency0; it is negated at launch when the token is currency1. This single per-quote dial
    ///         folds in the quote's decimals + USD price, so each quote can open at a consistent market cap.
    struct QuoteConfig {
        bool registered;
        uint8 quoteDecimals;
        int24 startTickToken0Frame;
    }

    mapping(address quoteToken => QuoteConfig config) internal _quoteConfig;

    /// @notice A band of the single-sided seed, as tick offsets from the start tick on the token side
    ///         (`lowerOffset` nearer spot, `upperOffset` farther; `TAIL` = to the usable edge) plus a share
    ///         of supply in bps. Reused across every quote; each launch freezes the template it used.
    struct Band {
        int24 lowerOffset;
        int24 upperOffset;
        uint16 supplyShareBps;
    }

    Band[] internal _bandTemplate;

    address[] internal _defaultDividendExclusions;
    mapping(address => uint256) private _defaultExclusionIndex;
    uint256 public constant MAX_DIVIDEND_BATCH_SIZE = TaxSuiteConstants.MAX_BATCH_SIZE;
    event DefaultDividendExclusionUpdated(address indexed account, bool excluded, uint64 configVersion);
    event LaunchTaxConfigured(
        PoolId indexed poolId,
        address indexed token,
        uint64 indexed configVersion,
        TaxFeeMath.TaxPolicy admittedPolicy,
        TaxFeeMath.TaxConfiguration taxConfiguration,
        address integratorFeeRecipient,
        bool antiSnipeEnabled
    );
    error DividendsDisabled();
    error AntiSnipeUnavailable();
    // Keep delegated validation errors in the factory ABI for existing error decoders.
    error InvalidTaxBounds();
    error InvalidTaxConfiguration();

    error InvalidProtocolFeeConfiguration();
    error InvalidMinimumDividendHoldingRequirement();
    error InvalidFeeSchedule();
    TaxLaunchOperations.PolicyState internal _policyState;

    function taxPolicy() public view override returns (TaxFeeMath.TaxPolicy memory) {
        return _policyState.policy;
    }

    function previewTaxConfiguration(TaxFeeMath.TaxConfiguration calldata configuration)
        external
        view
        override
        returns (TaxFeeMath.TaxConfigurationPreview memory)
    {
        return launchValidation.previewTaxConfiguration(configuration, _policyState.policy, launchSupply, configVersion);
    }

    struct CreatorRights {
        address originalCreator;
        address currentCreator;
        address pendingCreator;
        address creatorFeeRecipient;
        PoolId poolId;
        bool metadataEditable;
    }

    mapping(address token => CreatorRights rights) internal _creatorRights;
    address public creatorAdmin;
    address public pendingCreatorAdmin;

    uint256 public launchSupply;
    int24 public tickSpacing;
    uint256 public nativeLaunchFee;
    address public announcementRegistry;
    uint64 public configVersion = 1;
    mapping(bytes32 scopedSalt => bool used) public isLaunchSaltUsed;

    struct LaunchParams {
        address creator;
        TaxLaunchHook.FeeSlotInput[] feeSlots;
        string tokenName;
        string tokenSymbol;
        string tokenContractURI;
        bytes32 creatorSalt;
        address quoteToken;
        uint64 expectedConfigVersion;
        uint64 deadline;
        bool metadataEditable;
        string[] metadataKeys;
        string[] metadataValues;
        TaxFeeMath.TaxConfiguration taxConfiguration;
        address creatorFeeRecipient;
        address integratorFeeRecipient;
        bool antiSnipeEnabled;
    }

    struct LaunchBuyParams {
        address fundingToken;
        uint256 amountIn;
        uint256 minAmountOut;
        bytes routeData;
    }

    struct LaunchPreparation {
        address creator;
        uint256 supply;
        bytes32 scopedSalt;
        address predictedToken;
        bool tokenIsCurrency0;
        int24 spacing;
        int24 startTick;
        TaxLaunchHook.SeedPosition[] seedPositions;
    }

    event QuoteRegistered(address indexed quoteToken, uint8 quoteDecimals, int24 startTickToken0Frame, uint64 revision);
    event QuoteStartTickUpdated(
        address indexed quoteToken, int24 previousStartTickToken0Frame, int24 newStartTickToken0Frame, uint64 revision
    );
    event QuoteUnregistered(address indexed quoteToken, uint64 revision);
    event BandTemplateUpdated(uint256 bandCount);
    event LaunchSupplyUpdated(uint256 previousLaunchSupply, uint256 newLaunchSupply);
    event TickSpacingUpdated(int24 previousTickSpacing, int24 newTickSpacing);
    event AnnouncementRegistrySet(address indexed announcementRegistry);
    event LaunchBuyAdapterUpdated(address indexed previousLaunchBuyAdapter, address indexed newLaunchBuyAdapter);
    event ConfigVersionUpdated(uint64 newConfigVersion);
    event Launched(
        address indexed token,
        PoolId indexed poolId,
        address indexed originalCreator,
        address quoteToken,
        uint256 launchSupply,
        int24 tickSpacing
    );
    event NativeLaunchFeePaid(address indexed payer, address indexed recipient, uint256 amount);
    event NativeLaunchFeeUpdated(uint256 previousNativeLaunchFee, uint256 newNativeLaunchFee);
    event LaunchBuyExecuted(
        address indexed token,
        PoolId indexed poolId,
        address indexed originalCreator,
        address fundingToken,
        uint256 amountIn,
        uint256 amountOut,
        address launchBuyAdapter
    );
    event CreatorRightsTransferProposed(
        address indexed token, address indexed currentCreator, address indexed pendingCreator
    );
    event CreatorRightsTransferCancelled(
        address indexed token, address indexed currentCreator, address indexed cancelledPendingCreator
    );
    event CreatorRightsTransferred(
        address indexed token,
        address indexed previousCreator,
        address indexed newCreator,
        address previousCreatorFeeRecipient,
        address newCreatorFeeRecipient
    );
    event CreatorFeeRecipientUpdated(
        address indexed token, address indexed previousCreatorFeeRecipient, address indexed newCreatorFeeRecipient
    );
    event CreatorAdminTransferStarted(address indexed currentCreatorAdmin, address indexed pendingCreatorAdmin);
    event CreatorAdminTransferCancelled(
        address indexed currentCreatorAdmin, address indexed cancelledPendingCreatorAdmin
    );
    event CreatorAdminTransferred(address indexed previousCreatorAdmin, address indexed newCreatorAdmin);
    event CreatorAdminRevoked(address indexed previousCreatorAdmin);

    error InvalidConfig();
    error EmptyTokenNameOrSymbol();
    error QuoteNotRegistered();
    error QuoteAlreadyRegistered();
    error OutOfBounds();
    error TokenMismatch();
    error MisalignedOffset();
    error NotImmutable();
    error LaunchSaltUsed(bytes32 scopedSalt);
    error StaleConfig(uint64 expectedConfigVersion, uint64 actualConfigVersion);
    error LaunchExpired(uint64 deadline);
    error InvalidNativeLaunchFeePayment();
    error NativeLaunchFeeTransferFailed();
    error UnknownLaunchToken();
    error NotCurrentCreator();
    error NotPendingCreator();
    error NotOwnerOrCreatorAdmin();
    error NotPendingCreatorAdmin();
    error UnsafeOwnershipRenunciation();
    error InvalidCreatorRightsReceiver();
    error MetadataNotEditable();
    error LaunchBuyAdapterNotConfigured();
    error InvalidLaunchBuyParams();
    error InvalidLaunchBuyPayment(uint256 expectedValue, uint256 actualValue);

    /// @notice Genesis economics supplied explicitly at deploy. Each field is validated with the same logic as
    ///         its governance setter and stays tunable for future launches.
    struct FactoryInitialization {
        uint256 launchSupply;
        int24 tickSpacing;
        TaxFeeMath.TaxPolicy taxPolicy;
        Band[] bandTemplate;
    }

    constructor(
        IPoolManager poolManagerAddress,
        TaxLaunchHook launchHook,
        FactoryInitialization memory initialFactoryConfiguration
    ) Ownable(msg.sender) {
        if (
            address(poolManagerAddress) == address(0) || address(poolManagerAddress).code.length == 0
                || address(launchHook) == address(0) || address(launchHook).code.length == 0
                || address(launchHook.poolManager()) != address(poolManagerAddress)
        ) revert InvalidConfig();
        poolManager = poolManagerAddress;
        hook = launchHook;
        launchValidation = new TaxLaunchValidation();
        _setLaunchSupply(initialFactoryConfiguration.launchSupply);
        _applyTickSpacing(initialFactoryConfiguration.tickSpacing);
        TaxLaunchOperations.initializeTaxPolicy(
            _policyState, initialFactoryConfiguration.taxPolicy, launchValidation, hook, launchSupply
        );
        _applyBandTemplate(initialFactoryConfiguration.bandTemplate);
        TaxLaunchOperations.emitTaxPolicy(_policyState, configVersion);
    }

    // ============================================================
    //                          CREATE
    // ============================================================

    function createLaunch(LaunchParams calldata launchParams)
        external
        payable
        nonReentrant
        returns (address token, PoolId poolId)
    {
        if (msg.value != nativeLaunchFee) revert InvalidNativeLaunchFeePayment();
        LaunchPreparation memory preparation = _prepareLaunch(launchParams, msg.sender);
        _payNativeLaunchFee(msg.sender);
        (token, poolId,) = _createLaunch(launchParams, preparation.creator, preparation);
    }

    function createLaunchAndBuy(LaunchParams calldata launchParams, LaunchBuyParams calldata launchBuyParams)
        external
        payable
        nonReentrant
        returns (address token, PoolId poolId, uint256 amountOut)
    {
        address adapter = hook.launchBuyAdapter();
        if (adapter == address(0)) revert LaunchBuyAdapterNotConfigured();
        if (
            launchBuyParams.amountIn == 0 || launchBuyParams.minAmountOut == 0 || launchBuyParams.routeData.length == 0
                || launchBuyParams.routeData.length > MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH
        ) revert InvalidLaunchBuyParams();

        address fundingToken = launchBuyParams.fundingToken;
        uint256 expectedValue = nativeLaunchFee;
        if (fundingToken == address(0)) {
            expectedValue += launchBuyParams.amountIn;
        } else if (fundingToken.code.length == 0) {
            revert InvalidLaunchBuyParams();
        }
        if (msg.value != expectedValue) revert InvalidLaunchBuyPayment(expectedValue, msg.value);

        LaunchPreparation memory preparation = _prepareLaunch(launchParams, msg.sender);
        PoolKey memory poolKey;
        (token, poolId, poolKey) = _createLaunch(launchParams, preparation.creator, preparation);
        if (fundingToken == token) revert InvalidLaunchBuyParams();

        ILaunchBuyAdapter.LaunchBuyRequest memory request = ILaunchBuyAdapter.LaunchBuyRequest({
            originalCreator: msg.sender,
            launchToken: token,
            quoteToken: launchParams.quoteToken,
            poolKey: poolKey,
            fundingToken: fundingToken,
            amountIn: launchBuyParams.amountIn,
            minAmountOut: launchBuyParams.minAmountOut,
            deadline: launchParams.deadline,
            routeData: launchBuyParams.routeData
        });
        uint256 valueForAdapter = fundingToken == address(0) ? launchBuyParams.amountIn : 0;
        amountOut = hook.executeLaunchBuy{value: valueForAdapter}(poolId, request);
        _payNativeLaunchFee(msg.sender);

        emit LaunchBuyExecuted(
            token, poolId, preparation.creator, fundingToken, launchBuyParams.amountIn, amountOut, adapter
        );
    }

    function _createLaunch(
        LaunchParams calldata launchParams,
        address originalCreator,
        LaunchPreparation memory preparation
    ) internal returns (address token, PoolId poolId, PoolKey memory poolKey) {
        (token, poolId, poolKey) = _createLaunchPool(launchParams, originalCreator, preparation);

        _creatorRights[token] = CreatorRights({
            originalCreator: originalCreator,
            currentCreator: originalCreator,
            pendingCreator: address(0),
            creatorFeeRecipient: launchParams.creatorFeeRecipient,
            poolId: poolId,
            metadataEditable: launchParams.metadataEditable
        });

        AnnouncementRegistry(announcementRegistry).registerToken(token);
        emit LaunchTaxConfigured(
            poolId,
            token,
            configVersion,
            _policyState.policy,
            launchParams.taxConfiguration,
            launchParams.integratorFeeRecipient,
            launchParams.antiSnipeEnabled
        );
        emit Launched(token, poolId, originalCreator, launchParams.quoteToken, preparation.supply, preparation.spacing);
    }

    function _prepareLaunch(LaunchParams calldata launchParams, address originalCreator)
        internal
        returns (LaunchPreparation memory preparation)
    {
        if (launchParams.expectedConfigVersion != configVersion) {
            revert StaleConfig(launchParams.expectedConfigVersion, configVersion);
        }
        // forge-lint: disable-next-line(block-timestamp) user-supplied transaction expiry, not economic timing
        if (block.timestamp > launchParams.deadline) revert LaunchExpired(launchParams.deadline);
        if (bytes(launchParams.tokenName).length == 0 || bytes(launchParams.tokenSymbol).length == 0) {
            revert EmptyTokenNameOrSymbol();
        }
        if (!_quoteConfig[launchParams.quoteToken].registered) revert QuoteNotRegistered();
        if (launchParams.metadataKeys.length != launchParams.metadataValues.length) revert InvalidConfig();
        for (uint256 i = 0; i < launchParams.metadataKeys.length; i++) {
            if (bytes(launchParams.metadataKeys[i]).length == 0) revert InvalidConfig();
        }

        launchValidation.validateLaunchTax(
            launchParams.taxConfiguration, _policyState.policy, launchSupply, launchParams.antiSnipeEnabled
        );
        if (
            launchParams.taxConfiguration.integratorAllocationShare != 0
                && launchParams.integratorFeeRecipient == address(0)
        ) revert InvalidConfig();
        _beforeCreateLaunch(launchParams);

        preparation.supply = launchSupply;
        preparation.scopedSalt = keccak256(abi.encode(originalCreator, launchParams.creatorSalt));
        if (isLaunchSaltUsed[preparation.scopedSalt]) revert LaunchSaltUsed(preparation.scopedSalt);
        isLaunchSaltUsed[preparation.scopedSalt] = true;
        preparation.predictedToken = _predictTokenAddress(launchParams, preparation.scopedSalt, preparation.supply);
        _validatePredictedToken(preparation.predictedToken);
        preparation.creator = launchParams.creator == address(0) ? originalCreator : launchParams.creator;
        _validateCreatorRightsAddress(preparation.predictedToken, preparation.creator);
        launchValidation.validateLaunchRecipients(
            this,
            launchParams.creatorFeeRecipient,
            launchParams.integratorFeeRecipient,
            preparation.predictedToken,
            preparation.scopedSalt,
            launchParams.taxConfiguration.dividendAllocationShare != 0
        );
        preparation.tokenIsCurrency0 = uint160(preparation.predictedToken) < uint160(launchParams.quoteToken);
        preparation.spacing = tickSpacing;
        preparation.startTick =
            _resolveAlignedStartTick(launchParams.quoteToken, preparation.tokenIsCurrency0, preparation.spacing);
        preparation.seedPositions = _resolveSeedPositions(
            preparation.startTick, preparation.spacing, preparation.tokenIsCurrency0, preparation.supply
        );
    }

    function _payNativeLaunchFee(address payer) internal {
        uint256 amount = nativeLaunchFee;
        if (amount == 0) return;
        (bool success,) =
            payable(_policyState.policy.protocolFeeConfiguration.protocolFeeRecipient).call{value: amount}("");
        if (!success) revert NativeLaunchFeeTransferFailed();
        emit NativeLaunchFeePaid(payer, _policyState.policy.protocolFeeConfiguration.protocolFeeRecipient, amount);
    }

    function _beforeCreateLaunch(LaunchParams calldata launchParams) internal view virtual;

    function _predictTokenAddress(LaunchParams calldata launchParams, bytes32 scopedSalt, uint256 currentLaunchSupply)
        internal
        view
        virtual
        returns (address predictedToken);

    function _createLaunchPool(LaunchParams calldata params, address creator, LaunchPreparation memory preparation)
        internal
        virtual
        returns (address token, PoolId poolId, PoolKey memory poolKey);

    function _validatePredictedToken(address) internal view virtual {}

    function _resolveAlignedStartTick(address quoteToken, bool tokenIsCurrency0, int24 spacing)
        internal
        view
        returns (int24)
    {
        int24 frame = _quoteConfig[quoteToken].startTickToken0Frame;
        int24 startTick = tokenIsCurrency0 ? frame : -frame;
        // forge-lint: disable-next-line(divide-before-multiply) the truncation IS the alignment
        return (startTick / spacing) * spacing;
    }

    /// @notice Resolve the band template into absolute positions for this launch's ordering and supply.
    function _resolveSeedPositions(int24 startTick, int24 spacing, bool tokenIsCurrency0, uint256 supply)
        internal
        view
        returns (TaxLaunchHook.SeedPosition[] memory)
    {
        return launchValidation.resolveSeedPositions(_bandTemplate, startTick, spacing, tokenIsCurrency0, supply);
    }

    // ============================================================
    //                       GOVERNANCE (future launches only)
    // ============================================================

    function setBandTemplate(Band[] calldata newBandTemplate) external onlyOwner nonReentrant {
        _applyBandTemplate(newBandTemplate);
        _bumpConfigVersion();
    }

    /// @dev Validate + store the seed band template. Shared by the constructor and the governance setter.
    function _applyBandTemplate(Band[] memory newBands) internal {
        launchValidation.validateBandTemplate(newBands, tickSpacing);
        delete _bandTemplate;
        for (uint256 i; i < newBands.length; ++i) {
            _bandTemplate.push(newBands[i]);
        }
        emit BandTemplateUpdated(newBands.length);
    }

    // ============================================================
    //                       CREATOR RIGHTS
    // ============================================================

    function creatorRights(address token) external view returns (CreatorRights memory rights) {
        rights = _requireCreatorRights(token);
    }

    /// @notice Whether this factory has recorded a completed launch; not a registry of external tokens.
    function isLaunchToken(address token) external view returns (bool) {
        return _creatorRights[token].originalCreator != address(0);
    }

    function currentCreatorOf(address token) external view returns (address currentCreator) {
        currentCreator = _creatorRights[token].currentCreator;
        if (currentCreator == address(0)) revert UnknownLaunchToken();
    }

    function transferCreatorAdmin(address newCreatorAdmin) external onlyOwner nonReentrant {
        _validateCreatorAdminAddress(newCreatorAdmin);
        if (newCreatorAdmin == pendingCreatorAdmin) return;
        pendingCreatorAdmin = newCreatorAdmin;
        emit CreatorAdminTransferStarted(creatorAdmin, newCreatorAdmin);
    }

    function acceptCreatorAdmin() external nonReentrant {
        address pending = pendingCreatorAdmin;
        if (msg.sender != pending || pending == address(0)) revert NotPendingCreatorAdmin();
        address previous = creatorAdmin;
        creatorAdmin = pending;
        pendingCreatorAdmin = address(0);
        emit CreatorAdminTransferred(previous, pending);
    }

    function cancelCreatorAdminTransfer() external onlyOwner nonReentrant {
        address pending = pendingCreatorAdmin;
        if (pending == address(0)) return;
        pendingCreatorAdmin = address(0);
        emit CreatorAdminTransferCancelled(creatorAdmin, pending);
    }

    function revokeCreatorAdmin() external onlyOwner nonReentrant {
        address previousCreatorAdmin = creatorAdmin;
        address cancelledPendingCreatorAdmin = pendingCreatorAdmin;
        if (previousCreatorAdmin == address(0) && cancelledPendingCreatorAdmin == address(0)) return;
        creatorAdmin = address(0);
        pendingCreatorAdmin = address(0);
        if (cancelledPendingCreatorAdmin != address(0)) {
            emit CreatorAdminTransferCancelled(previousCreatorAdmin, cancelledPendingCreatorAdmin);
        }
        if (previousCreatorAdmin != address(0)) emit CreatorAdminRevoked(previousCreatorAdmin);
    }

    function proposeCreatorRightsTransfer(address token, address newCreator) external nonReentrant {
        CreatorRights storage rights = _requireCurrentCreator(token);
        _validateCreatorRightsAddress(token, newCreator);
        if (newCreator == rights.currentCreator) revert InvalidConfig();
        if (newCreator == rights.pendingCreator) return;
        rights.pendingCreator = newCreator;
        emit CreatorRightsTransferProposed(token, rights.currentCreator, newCreator);
    }

    function cancelCreatorRightsTransfer(address token) external nonReentrant {
        CreatorRights storage rights = _requireCurrentCreator(token);
        address pending = rights.pendingCreator;
        if (pending == address(0)) return;
        rights.pendingCreator = address(0);
        emit CreatorRightsTransferCancelled(token, rights.currentCreator, pending);
    }

    function acceptCreatorRightsTransfer(address token) external nonReentrant {
        CreatorRights storage rights = _requireCreatorRights(token);
        if (msg.sender != rights.pendingCreator || msg.sender == address(0)) revert NotPendingCreator();
        TaxLaunchOperations.transferCreatorRights(rights, token, msg.sender, launchValidation, hook);
    }

    function setCreatorFeeRecipient(address token, address newCreatorFeeRecipient) external nonReentrant {
        TaxLaunchOperations.setCreatorFeeRecipient(
            _requireCurrentCreator(token), token, newCreatorFeeRecipient, launchValidation, hook
        );
    }

    function safeTransferCreatorRights(address token, address rightsReceiver, bytes calldata callbackData)
        external
        payable
        nonReentrant
    {
        CreatorRights storage rights = _requireCurrentCreator(token);
        _validateCreatorRightsAddress(token, rightsReceiver);
        if (rightsReceiver == rights.currentCreator || rightsReceiver.code.length == 0) {
            revert InvalidCreatorRightsReceiver();
        }
        address previousCreator = rights.currentCreator;
        TaxLaunchOperations.transferCreatorRights(rights, token, rightsReceiver, launchValidation, hook);
        bytes4 selector = ICreatorRightsReceiver(rightsReceiver).onCreatorRightsReceived{value: msg.value}(
            previousCreator, token, callbackData
        );
        if (selector != ICreatorRightsReceiver.onCreatorRightsReceived.selector) {
            revert InvalidCreatorRightsReceiver();
        }
    }

    function updateTokenName(address token, string calldata newName) external nonReentrant {
        _requireMetadataEditor(token);
        ILaunchTokenMetadata(token).updateName(newName);
    }

    function updateTokenSymbol(address token, string calldata newSymbol) external nonReentrant {
        _requireMetadataEditor(token);
        ILaunchTokenMetadata(token).updateSymbol(newSymbol);
    }

    function updateTokenContractURI(address token, string calldata newContractURI) external nonReentrant {
        _requireMetadataEditor(token);
        ILaunchTokenMetadata(token).updateContractURI(newContractURI);
    }

    function updateTokenExtraMetadata(address token, string calldata metadataKey, string calldata metadataValue)
        external
        nonReentrant
    {
        _requireMetadataEditor(token);
        ILaunchTokenMetadata(token).updateExtraMetadata(metadataKey, metadataValue);
    }

    function _requireCreatorRights(address token) internal view returns (CreatorRights storage rights) {
        rights = _creatorRights[token];
        if (rights.originalCreator == address(0)) revert UnknownLaunchToken();
    }

    function _requireCurrentCreator(address token) internal view returns (CreatorRights storage rights) {
        rights = _requireCreatorRights(token);
        if (msg.sender != rights.currentCreator) revert NotCurrentCreator();
    }

    function _requireMetadataEditor(address token) internal view {
        CreatorRights storage rights = _requireCurrentCreator(token);
        if (!rights.metadataEditable) revert MetadataNotEditable();
    }

    function _validateCreatorRightsAddress(address token, address account) internal view {
        if (
            account == address(0) || account == token || account == address(this) || account == address(hook)
                || account == address(poolManager) || account == hook.feeEscrow() || account == announcementRegistry
                || hook.isDividendContract(account)
        ) revert InvalidConfig();
    }

    function _validateCreatorAdminAddress(address newCreatorAdmin) internal view {
        if (newCreatorAdmin == creatorAdmin || _creatorRights[newCreatorAdmin].originalCreator != address(0)) {
            revert InvalidConfig();
        }
        _validateCreatorRightsAddress(address(0), newCreatorAdmin);
    }

    function setTaxPolicy(TaxFeeMath.TaxPolicy calldata policy) external override onlyOwner {
        _applyTaxPolicy(policy);
    }

    function setTaxFeeBounds(TaxFeeMath.TaxFeeBounds calldata bounds) external override onlyOwner {
        TaxFeeMath.TaxPolicy memory policy = _policyState.policy;
        policy.taxFeeBounds = bounds;
        _applyTaxPolicy(policy);
    }

    function setProtocolFeeConfiguration(TaxFeeMath.ProtocolFeeConfiguration calldata configuration)
        external
        override
        onlyOwner
    {
        TaxFeeMath.TaxPolicy memory policy = _policyState.policy;
        policy.protocolFeeConfiguration = configuration;
        _applyTaxPolicy(policy);
    }

    function setAntiSnipeConfiguration(TaxFeeMath.AntiSnipeConfiguration calldata configuration)
        external
        override
        onlyOwner
    {
        TaxFeeMath.TaxPolicy memory policy = _policyState.policy;
        policy.antiSnipeConfiguration = configuration;
        _applyTaxPolicy(policy);
    }

    function setMinimumDividendHoldingRequirement(uint256 minimumHolding) external override onlyOwner {
        TaxFeeMath.TaxPolicy memory policy = _policyState.policy;
        policy.minimumDividendHoldingRequirement = minimumHolding;
        _applyTaxPolicy(policy);
    }

    function _applyTaxPolicy(TaxFeeMath.TaxPolicy memory policy) internal {
        // Policy validation makes only static external calls. Keep no-ops write-free while rejecting
        // policy mutation from an active launch, payout or other guarded factory operation.
        if (_reentrancyGuardEntered()) revert ReentrancyGuardReentrantCall();
        if (!TaxLaunchOperations.applyTaxPolicy(_policyState, policy, launchValidation, hook, launchSupply)) return;
        _bumpConfigVersion();
        TaxLaunchOperations.emitTaxPolicy(_policyState, configVersion);
    }

    function defaultDividendExclusions() external view returns (address[] memory) {
        return _defaultDividendExclusions;
    }

    function setDefaultDividendExclusion(address account, bool excluded) external onlyOwner nonReentrant {
        if (!TaxLaunchOperations.setDefaultExclusion(
                _defaultDividendExclusions, _defaultExclusionIndex, account, excluded
            )) return;
        _bumpConfigVersion();
        emit DefaultDividendExclusionUpdated(account, excluded, configVersion);
    }

    function dividendOf(address token) public view returns (address) {
        _requireCreatorRights(token);
        return TaxLaunchToken(token).dividend();
    }

    function setLaunchDividendExclusions(address token, address[] calldata accounts, bool excluded)
        external
        nonReentrant
    {
        TaxDividend dividend = _requireDividendAdmin(token);
        if (accounts.length == 0 || accounts.length > MAX_DIVIDEND_BATCH_SIZE) revert OutOfBounds();
        for (uint256 i; i < accounts.length; ++i) {
            if (excluded) dividend.excludeAddress(accounts[i]);
            else dividend.unexcludeAddress(accounts[i]);
        }
    }

    function setLaunchDividendReceiver(address token, address holder, address receiver) external nonReentrant {
        _requireDividendAdmin(token).setDividendReceiver(holder, receiver);
    }

    function refreshLaunchDividendShares(address token, address[] calldata holders) external nonReentrant {
        _requireDividendAdmin(token).refreshShares(holders);
    }

    function emergencyWithdrawDividendAssets(address token, address asset, uint256 amount, address recipient)
        external
        nonReentrant
    {
        _requireDividendAdmin(token).emergencyWithdraw(asset, amount, recipient);
    }

    function _requireDividendAdmin(address token) internal view returns (TaxDividend) {
        _requireOwnerOrCreatorAdmin();
        address dividend = dividendOf(token);
        if (dividend == address(0)) revert DividendsDisabled();
        return TaxDividend(payable(dividend));
    }

    function _requireOwnerOrCreatorAdmin() internal view {
        if (msg.sender == address(0) || (msg.sender != owner() && msg.sender != creatorAdmin)) {
            revert NotOwnerOrCreatorAdmin();
        }
    }

    function quoteConfig(address quoteToken)
        external
        view
        returns (bool registered, uint8 quoteDecimals, int24 startTickToken0Frame)
    {
        QuoteConfig storage configuration = _quoteConfig[quoteToken];
        return (configuration.registered, configuration.quoteDecimals, configuration.startTickToken0Frame);
    }

    function setLaunchSupply(uint256 newLaunchSupply) external onlyOwner nonReentrant {
        if (newLaunchSupply == launchSupply) return;
        _setLaunchSupply(newLaunchSupply);
        _bumpConfigVersion();
    }

    function setTickSpacing(int24 newTickSpacing) external onlyOwner nonReentrant {
        if (newTickSpacing == tickSpacing) return;
        _applyTickSpacing(newTickSpacing);
        _bumpConfigVersion();
    }

    /// @dev Validate + store the tick spacing. Shared by the constructor and the governance setter.
    function _applyTickSpacing(int24 spacing) internal {
        if (spacing <= 0 || spacing > 16_384) revert OutOfBounds();
        for (uint256 i = 0; i < _bandTemplate.length; i++) {
            if (
                _bandTemplate[i].lowerOffset % spacing != 0
                    || (_bandTemplate[i].upperOffset != TAIL && _bandTemplate[i].upperOffset % spacing != 0)
            ) revert MisalignedOffset();
        }
        emit TickSpacingUpdated(tickSpacing, spacing);
        tickSpacing = spacing;
    }

    function setAnnouncementRegistry(address newAnnouncementRegistry) external onlyOwner nonReentrant {
        if (announcementRegistry != address(0)) revert InvalidConfig();
        if (
            newAnnouncementRegistry == address(0) || newAnnouncementRegistry.code.length == 0
                || AnnouncementRegistry(newAnnouncementRegistry).factory() != address(this)
        ) {
            revert InvalidConfig();
        }
        announcementRegistry = newAnnouncementRegistry;
        _bumpConfigVersion();
        emit AnnouncementRegistrySet(newAnnouncementRegistry);
    }

    function launchBuyAdapter() external view returns (address adapter) {
        return hook.launchBuyAdapter();
    }

    function setLaunchBuyAdapter(address newLaunchBuyAdapter) external onlyOwner nonReentrant {
        address previousAdapter = hook.launchBuyAdapter();
        if (newLaunchBuyAdapter == previousAdapter) return;
        hook.setLaunchBuyAdapter(newLaunchBuyAdapter);
        _bumpConfigVersion();
        emit LaunchBuyAdapterUpdated(previousAdapter, newLaunchBuyAdapter);
    }

    function setNativeLaunchFee(uint256 newNativeLaunchFee) external onlyOwner nonReentrant {
        uint256 previousNativeLaunchFee = nativeLaunchFee;
        if (newNativeLaunchFee == previousNativeLaunchFee) return;
        nativeLaunchFee = newNativeLaunchFee;
        _bumpConfigVersion();
        emit NativeLaunchFeeUpdated(previousNativeLaunchFee, newNativeLaunchFee);
    }

    function bandTemplate() external view returns (Band[] memory bands) {
        return _bandTemplate;
    }

    function _setLaunchSupply(uint256 supply) internal {
        if (supply < MIN_SUPPLY || supply > MAX_SUPPLY) revert OutOfBounds();
        if (_policyState.policy.minimumDividendHoldingRequirement > supply) {
            revert InvalidMinimumDividendHoldingRequirement();
        }
        emit LaunchSupplyUpdated(launchSupply, supply);
        launchSupply = supply;
    }

    /// @dev Reserve one `tickSpacing` of headroom from both tick extremes.
    function _validateStartTickFrame(int24 frame) internal view {
        int24 spacing = tickSpacing;
        if (frame < TickMath.MIN_TICK + spacing || frame > TickMath.MAX_TICK - spacing) revert OutOfBounds();
    }

    function _bumpConfigVersion() internal {
        configVersion++;
        emit ConfigVersionUpdated(configVersion);
    }

    function _requireLaunchCreationWiring() internal view virtual {
        launchValidation.validateFactoryWiring(this);
    }

    function renounceOwnership() public virtual override onlyOwner {
        if (creatorAdmin != address(0) || pendingCreatorAdmin != address(0) || hook.launchBuyAdapter() != address(0)) {
            revert UnsafeOwnershipRenunciation();
        }
        super.renounceOwnership();
    }
}

src/tax/TaxSuiteConstants.sol

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

/// @notice Shared compile-time limits. Public contract getters remain aliases for ABI compatibility.
library TaxSuiteConstants {
    uint256 internal constant BPS = 10_000;
    uint256 internal constant PERCENTAGE_SCALE = 100_000_000;
    uint256 internal constant RATE_SCALE = 10 ** 24;
    uint32 internal constant MAX_TOTAL_FEE_RATE = 99_000_000;
    uint256 internal constant MAX_BATCH_SIZE = 64;
    uint256 internal constant MAX_BANDS = 10;
    uint256 internal constant MAX_LAUNCH_BUY_ROUTE_DATA_LENGTH = 4_096;
    uint256 internal constant MIN_SUPPLY = 1_000_000e18;
    uint256 internal constant MAX_SUPPLY = 1_000_000_000_000e18;
    address internal constant BURN_SINK = 0x000000000000000000000000000000000000dEaD;
}

src/tax/interfaces/ILaunchConsent.sol

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

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

/// @notice Optional interface for an integrator contract that wants a say in launches that name it.
/// @dev The hook asks once, when it registers the pool. Wallet integrators are never asked.
interface ILaunchConsent {
    struct LaunchContext {
        address token;
        address quoteToken;
        address creator;
        bool antiSnipeEnabled;
        TaxFeeMath.TaxConfiguration taxConfiguration;
    }

    /// @return verdict `LaunchConsent.REJECTED` blocks the launch. Every other outcome allows it:
    ///         another value, a revert, no code for this selector, or no answer within the gas limit.
    function launchConsent(LaunchContext calldata context) external view returns (bytes4 verdict);
}

src/tax/interfaces/ITaxDividend.sol

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

/// @notice Synchronous shares, fee accrual and holder-authorized withdrawals with lazy funding.
/// @dev Factory administration uses the typed TaxDividend contract, not an arbitrary executor.
interface ITaxDividend {
    function owner() external view returns (address);
    function taxToken() external view returns (address);
    function hook() external view returns (address);
    function claimHelper() external view returns (address);
    function feeEscrow() external view returns (address);
    function poolManager() external view returns (address);
    function rewardToken() external view returns (address);
    function minimumDividendHolding() external view returns (uint256);
    /// @notice Supply the raw launched-token balance; the tracker applies minimum and exclusion rules.
    function setShare(address holder, uint256 share) external;
    function totalShares() external view returns (uint256);
    function notifyDividendFee(uint256 amount) external;
    function pendingDividendFunding() external view returns (uint256);
    function availableRewardBacking() external view returns (uint256);
    function requiredRewardBacking() external view returns (uint256);
    function rewardBackingDeficit() external view returns (uint256);
    function withdrawDividends() external returns (bool paid);
    function withdrawDividendsFor(address holder, bool unwrapWrappedNative) external returns (bool paid);
    function withdrawableDividendOf(address holder) external view returns (uint256);
    function receiverOf(address holder) external view returns (address);
    function excludedFromDividends(address holder) external view returns (bool);
}

src/tax/interfaces/ITaxDividendClaimHelper.sol

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

interface ITaxDividendClaimHelper {
    struct Claim {
        address token;
        bool unwrapWrappedNative;
    }

    function hook() external view returns (address);
    function factory() external view returns (address);
    function claimDividends(Claim[] calldata claims) external returns (uint256 paidCount, bool[] memory paid);
}

src/tax/interfaces/ITaxFeeAdmin.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TaxFeeMath} from "../TaxFeeMath.sol";

/// @notice One inclusive tax policy, with atomic complete and focused future-launch updates.
interface ITaxFeeAdmin {
    event TaxPolicyUpdated(uint64 indexed configVersion, TaxFeeMath.TaxPolicy policy);
    function setTaxPolicy(TaxFeeMath.TaxPolicy calldata policy) external;
    function setTaxFeeBounds(TaxFeeMath.TaxFeeBounds calldata bounds) external;
    function setProtocolFeeConfiguration(TaxFeeMath.ProtocolFeeConfiguration calldata configuration) external;
    function setAntiSnipeConfiguration(TaxFeeMath.AntiSnipeConfiguration calldata configuration) external;
    function setMinimumDividendHoldingRequirement(uint256 minimumHolding) external;
    function taxPolicy() external view returns (TaxFeeMath.TaxPolicy memory);
    function previewTaxConfiguration(TaxFeeMath.TaxConfiguration calldata configuration)
        external
        view
        returns (TaxFeeMath.TaxConfigurationPreview memory);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/tax/TaxLaunchOperations.sol": {
      "TaxLaunchOperations": "0x533179df1316420a83c20e6bd6ec092ae82aa967"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "base-std/=lib/base-std/src/",
    "base-std-test/=lib/base-std/test/",
    "v4-core/=lib/v4-core/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "solmate/=lib/v4-core/lib/solmate/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.