Skip to content
Verified contractExactMIT

FeeConsolidatorV3

Address0xd0cfcc5d02e09e6784c3f834a4ae4a5ebb5f51d9
Balance

0 ETH

 

Transactions

15

 

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
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,359,866
Creation transaction
0x0d2b9de8e5…dd02f5cdad

53 files

src/FeeConsolidatorV3.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";

import {FeeConsolidator, IConsolidatorRegistry} from "./FeeConsolidator.sol";
import {V3SwapExecutor} from "./V3SwapExecutor.sol";
import {IFeeVault} from "./interfaces/IFeeVault.sol";
import {IUniswapV3Factory} from "./interfaces/external/IUniswapV3.sol";

/// @title FeeConsolidatorV3
/// @notice `FeeConsolidator` whose registry routes may also contain Uniswap v3 hops.
/// @dev A v3 hop is a registry `PoolKey` with tick spacing zero (`V3RouteLib`). Everything about
///      a hop except the swap itself is the shared v4 code: the same reference-tick deviation
///      guard (the reference table is keyed by the hop's key hash), the same minimum output
///      `max(spot, reference) * (1 - maxSlippageBps - hopFee)`, the same full-fill requirement,
///      the same in-swap bounds, and the same failure behaviour (a revert is caught by the caller,
///      the raw amount stays held).
///
///      The swap is a direct call to the factory's v3 pool, made by `V3SwapExecutor` (a small
///      contract this one deploys; it is the pool's swap callback and holds nothing between
///      calls), not through SwapRouter02 or the Universal Router: no router approval, no Permit2
///      and no extra contract in the trust path besides the executor. The output is measured here
///      from the balance difference.
///
///      There is no deadline argument: a conversion is never signed or queued, it executes
///      inside the transaction that triggers it, so `block.timestamp` is its deadline.
contract FeeConsolidatorV3 is FeeConsolidator {
    using SafeERC20 for IERC20;

    /// @notice The contract that swaps on v3 pools for this one (it holds the immutable v3 factory).
    V3SwapExecutor public immutable executor;

    constructor(
        address owner_,
        IPoolManager poolManager_,
        IConsolidatorRegistry quoteRegistry_,
        IFeeVault vault_,
        address weth_,
        uint256 maxSlippageBps_,
        uint256 maxDeviationTicks_,
        IUniswapV3Factory v3Factory_
    )
        FeeConsolidator(
            owner_, poolManager_, quoteRegistry_, vault_, weth_, maxSlippageBps_, maxDeviationTicks_
        )
    {
        if (address(v3Factory_) == address(0)) revert ZeroAddress();
        executor = new V3SwapExecutor(v3Factory_, address(this), address(poolManager_));
    }

    /// @inheritdoc FeeConsolidator
    function _v3Spot(PoolKey memory key)
        internal
        view
        override
        returns (uint160 sqrtPriceX96, int24 tick)
    {
        return executor.spot(Currency.unwrap(key.currency0), Currency.unwrap(key.currency1), key.fee);
    }

    /// @inheritdoc FeeConsolidator
    /// @dev The input goes from the pool manager straight to the executor, the pool pays the
    ///      output straight into the pool manager (`sync` before, `settle` after), and the output
    ///      is what `settle` measured at the pool manager: the minimum output applies to what
    ///      arrived. Every pool manager delta of this contract is unchanged by the pair except
    ///      for the swapped currency pair, exactly as after a v4 swap.
    function _hopV3(PoolKey memory key, bool zeroForOne, uint256 amount)
        internal
        override
        returns (uint256 out)
    {
        (Currency cIn, Currency cOut) =
            zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
        poolManager.take(cIn, address(executor), amount);
        poolManager.sync(cOut);
        executor.swap(Currency.unwrap(cIn), Currency.unwrap(cOut), key.fee, amount);
        out = poolManager.settle();
    }
}

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/openzeppelin-contracts/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * 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.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    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/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

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

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 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/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20} from "../IERC20.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

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.
 *
 * IMPORTANT: Deprecated in favor of accessing `msg.sender` and `msg.data` directly. This contract, along with its
 * `_msgSender`, `_msgData` and `_contextSuffixLength` functions, will be removed in v6.0, where contracts read
 * `msg.sender` and `msg.data` directly. Contracts that override `_msgSender`/`_msgData` (e.g. to support
 * meta-transactions) will lose that extension point; plan the migration before upgrading.
 */
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/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

/**
 * @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // 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;

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.sol.eta.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.sol.eta.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

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 {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.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,
        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,
        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,
        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,
        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, 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,
        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";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.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);

    /// @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);

    /// @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/FixedPoint128.sol

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

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}

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/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/LiquidityMath.sol

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

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

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/Position.sol

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

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        // calculate accumulated fees. overflow in the subtraction of fee growth is expected
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

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/StateLibrary.sol

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

import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
    /// @notice index of pools mapping in the PoolManager
    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));

    /// @notice index of feeGrowthGlobal0X128 in Pool.State
    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;

    // feeGrowthGlobal1X128 offset in Pool.State = 2

    /// @notice index of liquidity in Pool.State
    uint256 public constant LIQUIDITY_OFFSET = 3;

    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
    uint256 public constant TICKS_OFFSET = 4;

    /// @notice index of tickBitmap mapping in Pool.State
    uint256 public constant TICK_BITMAP_OFFSET = 5;

    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
    uint256 public constant POSITIONS_OFFSET = 6;

    /**
     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
     * @dev Corresponds to pools[poolId].slot0
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
     * @return tick The current tick of the pool.
     * @return protocolFee The protocol fee of the pool.
     * @return lpFee The swap fee of the pool.
     */
    function getSlot0(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        bytes32 data = manager.extsload(stateSlot);

        //   24 bits  |24bits|24bits      |24 bits|160 bits
        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96
        assembly ("memory-safe") {
            // bottom 160 bits of data
            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            // next 24 bits of data
            tick := signextend(2, shr(160, data))
            // next 24 bits of data
            protocolFee := and(shr(184, data), 0xFFFFFF)
            // last 24 bits of data
            lpFee := and(shr(208, data), 0xFFFFFF)
        }
    }

    /**
     * @notice Retrieves the tick information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve information for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128
        )
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // read all 3 words of the TickInfo struct
        bytes32[] memory data = manager.extsload(slot, 3);
        assembly ("memory-safe") {
            let firstWord := mload(add(data, 32))
            liquidityNet := sar(128, firstWord)
            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            feeGrowthOutside0X128 := mload(add(data, 64))
            feeGrowthOutside1X128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve liquidity for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     */
    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint128 liquidityGross, int128 liquidityNet)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        bytes32 value = manager.extsload(slot);
        assembly ("memory-safe") {
            liquidityNet := sar(128, value)
            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }
    }

    /**
     * @notice Retrieves the fee growth outside a tick range of a pool
     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve fee growth for.
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // offset by 1 word, since the first word is liquidityGross + liquidityNet
        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
        assembly ("memory-safe") {
            feeGrowthOutside0X128 := mload(add(data, 32))
            feeGrowthOutside1X128 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     * @dev Note that feeGrowthGlobal can be artificially inflated
     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State, `uint256 feeGrowthGlobal0X128`
        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);

        // read the 2 words of feeGrowthGlobal
        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
        assembly ("memory-safe") {
            feeGrowthGlobal0 := mload(add(data, 32))
            feeGrowthGlobal1 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves total the liquidity of a pool.
     * @dev Corresponds to pools[poolId].liquidity
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return liquidity The liquidity of the pool.
     */
    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `uint128 liquidity`
        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);

        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Retrieves the tick bitmap of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].tickBitmap[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve the bitmap for.
     * @return tickBitmap The bitmap of the tick.
     */
    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
        internal
        view
        returns (uint256 tickBitmap)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int16 => uint256) tickBitmap;`
        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);

        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]
        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));

        tickBitmap = uint256(manager.extsload(slot));
    }

    /**
     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param poolId The ID of the pool.
     * @param owner The owner of the liquidity position.
     * @param tickLower The lower tick of the liquidity range.
     * @param tickUpper The upper tick of the liquidity range.
     * @param salt The bytes32 randomness to further distinguish position state.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(
        IPoolManager manager,
        PoolId poolId,
        address owner,
        int24 tickLower,
        int24 tickUpper,
        bytes32 salt
    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);

        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
    }

    /**
     * @notice Retrieves the position information of a pool at a specific position ID.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);

        // read all 3 words of the Position.State struct
        bytes32[] memory data = manager.extsload(slot, 3);

        assembly ("memory-safe") {
            liquidity := mload(add(data, 32))
            feeGrowthInside0LastX128 := mload(add(data, 64))
            feeGrowthInside1LastX128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity of a position.
     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     */
    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);
        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Calculate the fee growth inside a tick range of a pool
     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tickLower The lower tick of the range.
     * @param tickUpper The upper tick of the range.
     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
     */
    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);

        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickLower);
        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickUpper);
        (, int24 tickCurrent,,) = getSlot0(manager, poolId);
        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            }
        }
    }

    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
    }

    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int24 => TickInfo) ticks`
        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);

        // slot key of the tick key: `pools[poolId].ticks[tick]
        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
    }

    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(bytes32 => Position.State) positions;`
        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}

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/src/types/PoolOperation.sol

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

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

/// @notice Parameter struct for `ModifyLiquidity` pool operations
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 Parameter struct for `Swap` pool operations
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;
}

src/FeeConsolidator.sol

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

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {LPFeeLibrary} from "v4-core/libraries/LPFeeLibrary.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";

import {DonationAsset} from "./interfaces/IDonationAsset.sol";
import {IEpochGovernor} from "./interfaces/IEpochGovernor.sol";
import {IFeeConsolidator} from "./interfaces/IFeeConsolidator.sol";
import {IFeeVault} from "./interfaces/IFeeVault.sol";
import {IQuoteRegistry} from "./interfaces/IQuoteRegistry.sol";
import {V3RouteLib} from "./libraries/V3RouteLib.sol";

interface IConsolidatorRegistry is IQuoteRegistry {
    function routeOf(address asset) external view returns (PoolKey[] memory);
    function routeToOf(address asset, DonationAsset da) external view returns (PoolKey[] memory);
    function settlementAsset() external view returns (address);
}

interface IHookOracle {
    function twapTick(address token, uint32 window)
        external
        view
        returns (bool ok, int24 twapTick);
}

/// @dev `IVaradaHook.feeConfig` read as its first word only (`baseFeeBps`), which keeps the
///      returndata decoding small; the call and selector are the same.
interface IHookBaseFee {
    function feeConfig(address token) external view returns (uint24 baseFeeBps);
}

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

/// @title FeeConsolidator
/// @notice Converts raw pool fees (the launched token and its quote asset) into the settlement
///         asset (USDC) through Uniswap v4 and credits them to the FeeVault.
/// @dev Flow: a source (the hook, the LP locker) delivers raw fees and calls `consolidate`. The
///      amount is recorded as held. If the pool manager is locked, the consolidator unlocks it
///      and swaps along the route (token pool first for the token side, then the quote asset's
///      registry route) atomically; the USDC is forwarded to the vault in the same transaction.
///      If the route reverts for any reason (paused or non-compliant Ondo token, no liquidity,
///      guard violation) the raw amount stays held, `ConsolidationFailed` is emitted, and
///      `retry` can be called by anyone. If the pool manager is already unlocked (the hook runs
///      inside a swap) nothing can be swapped yet, so the amount is simply held for `retry`.
///
///      Price guards, applied to every hop:
///       1. spot must be within `maxDeviationTicks` of a reference: the hook's TWAP for the
///          token's own pool, an owner seeded moving reference for registry route pools;
///       2. execution must return at least `max(spot, reference) * (1 - maxSlippageBps - hopFee)`.
///          The minimum is measured against the reference too, so pushing spot inside the
///          deviation band cannot widen the slippage allowance (the band and the tolerance never
///          add up).
///      Claim conversions run inside a trader's swap (`convertClaims` with `inSwap`) use the
///      tighter `inSwapMaxDeviationTicks` / `inSwapMaxSlippageBps` instead.
///      A failed guard fails closed (the raw balance is held), never executes at a bad price.
///      References follow spot slowly (`_moveReference`), after each successful hop and through
///      the permissionless `syncReference`, so a market that moved stays convertible.
///
///      Moving reference of a route pool: the reference follows spot after every successful hop
///      or `syncReference` (a fraction of `REFERENCE_WINDOW` per elapsed time, capped per move)
///      but never leaves `anchor ± maxDriftTicks`. The anchor itself follows the reference at a
///      bounded rate, at most `maxDriftTicks` per `ANCHOR_PERIOD`, with the elapsed time counted
///      for one period at most. A sustained trend no faster than that rate is followed without
///      the owner, while quiet time cannot be banked: whatever the history, a burst of
///      manipulated moves over a time `T` moves the reference at most
///      `2 * maxDriftTicks + maxDriftTicks * T / ANCHOR_PERIOD` away from where the market was.
///      A faster move or a gap fails closed until the market returns, the anchor catches up, or
///      the owner re-anchors.
///
///      Epoch attribution: every held raw amount is tagged with the epoch in which it was earned
///      (the current epoch for hook fees, the epochs of the accrual interval for LP fees). A swap
///      spends the oldest tags first and splits its output over them in proportion, so the vault
///      credits each epoch with what it earned, whoever triggers the swap and whenever. Before an
///      epoch is settled the vault calls `flushThrough`, so fees still held for that epoch are
///      swapped into it first rather than left to roll over to a later epoch.
///      `convertClaims` (live-donation tokens) never holds anything: it converts the caller's
///      claims and pays the settlement asset out in the same call, so it leaves every holding,
///      epoch tag and owed total untouched and never deposits into the vault.
contract FeeConsolidator is IFeeConsolidator, IUnlockCallback, Ownable2Step, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using StateLibrary for IPoolManager;
    using TransientStateLibrary for IPoolManager;
    using PoolIdLibrary for PoolKey;
    using SafeCast for uint256;

    /// @notice Per-pool reference tick for pools outside the hook oracle.
    struct Reference {
        int24 tick;
        /// @dev Time up to which the elapsed time has been applied to `tick`.
        uint40 updatedAt;
        bool set;
        /// @dev Centre of the band the moving tick stays in (`anchor ± maxDriftTicks`). Set by
        ///      the owner, then moved toward `tick` at a bounded rate.
        int24 anchor;
        /// @dev Time up to which the elapsed time has been applied to `anchor`.
        uint40 anchoredAt;
    }

    /// @dev Held raw fees of one (token, currency), packed in one slot. Parts tagged with epochs
    ///      below `last` live in `_heldIn` and sum to `older`; the part tagged `last` is
    ///      `total - older` and is kept here, so a hold in the newest epoch (every hook fee) is a
    ///      single slot write. The epochs are kept when `total` returns to zero, so the slot stays
    ///      non-zero and the next hold is not charged a fresh slot. 104 bits hold about 2e31,
    ///      above the whole supply of a launched token (1e29) or of any registry quote asset.
    struct Holding {
        uint104 total;
        uint104 older;
        /// @dev Lowest epoch that may hold a part (exact when `older` is zero: then `last`).
        uint24 first;
        uint24 last;
    }

    uint256 internal constant BPS = 10_000;
    /// @notice Hard ceiling for `maxSlippageBps`.
    uint256 internal constant MAX_SLIPPAGE_CEILING_BPS = 2000;
    /// @notice Highest pool fee a hop may charge.
    uint256 internal constant MAX_HOP_FEE_BPS = 1000;
    /// @notice TWAP window used for the token's own pool.
    uint32 internal constant TWAP_WINDOW = 30 minutes;
    /// @notice Time over which a reference moves fully to spot after a successful hop.
    uint256 internal constant REFERENCE_WINDOW = 1 days;
    /// @notice Initial in-swap deviation bound, in ticks (about 3%).
    uint256 public constant DEFAULT_IN_SWAP_DEVIATION_TICKS = 300;
    /// @notice Initial in-swap slippage bound, in basis points.
    uint256 public constant DEFAULT_IN_SWAP_SLIPPAGE_BPS = 100;
    /// @notice The anchor moves toward the reference by at most `maxDriftTicks` per this
    ///         period, and at most one period of elapsed time counts, so quiet time cannot be
    ///         saved up and spent in a burst.
    uint256 public constant ANCHOR_PERIOD = 7 days;
    /// @notice Highest `maxDeviationTicks` (and so `maxDriftTicks`): the full usable tick range.
    uint256 public constant MAX_TICK_SPAN = uint256(int256(TickMath.MAX_TICK)) * 2;
    /// @notice Most epochs one accrual interval is spread over; anything older is attributed
    ///         to the oldest of them.
    uint256 public constant MAX_ACCRUAL_EPOCHS = 52;

    IPoolManager public immutable poolManager;
    IConsolidatorRegistry public immutable quoteRegistry;
    IFeeVault public immutable vault;
    /// @notice The governor whose epochs fees are attributed to (the vault's governor).
    IEpochGovernor public immutable governor;
    /// @inheritdoc IFeeConsolidator
    address public immutable settlementAsset;
    address public immutable weth;

    /// @inheritdoc IFeeConsolidator
    uint256 public maxSlippageBps;
    /// @notice Largest tolerated distance, in ticks (about one basis point each), between spot
    ///         and its reference.
    uint256 public maxDeviationTicks;
    /// @notice Half width of the band around the anchor that the reference stays in, and the
    ///         most the anchor moves per `ANCHOR_PERIOD`, in ticks. At most `maxDeviationTicks`.
    uint256 public maxDriftTicks;
    /// @notice Deviation bound for claim conversions inside a trader's swap (the effective bound
    ///         is the smaller of this and `maxDeviationTicks`).
    uint256 public inSwapMaxDeviationTicks;
    /// @notice Slippage bound for claim conversions inside a trader's swap (the effective bound
    ///         is the smaller of this and `maxSlippageBps`).
    uint256 public inSwapMaxSlippageBps;

    /// @notice The hook that registers pools.
    address public hook;
    mapping(address account => bool allowed) public isSource;

    mapping(address token => PoolKey) private _poolKeys;
    mapping(address token => address quote) public quoteOf;
    mapping(address token => mapping(address currency => Holding)) private _holdings;
    /// @dev Parts of a holding tagged below its `last` epoch (token => currency => epoch).
    mapping(address => mapping(address => mapping(uint256 => uint256))) private _heldIn;
    /// @dev Owed per currency across tokens, stored plus one once used so the slot never
    ///      returns to zero (see `totalHeld`).
    mapping(address currency => uint256) private _owedPlusOne;
    mapping(PoolId id => Reference) public references;

    event SourceSet(address indexed account, bool allowed);
    event HookSet(address indexed hook);
    event PoolRegistered(address indexed token, address indexed quote, PoolId indexed poolId);
    event MaxDeviationTicksUpdated(uint256 ticks);
    event MaxDriftTicksUpdated(uint256 ticks);
    event ReferenceSet(PoolId indexed poolId, int24 tick);
    event ReferenceSynced(PoolId indexed poolId, int24 spotTick, int24 tick);
    event InSwapBoundsUpdated(uint256 maxDeviationTicks, uint256 maxSlippageBps);
    event Rescued(address indexed currency, address indexed to, uint256 amount);

    error ZeroAddress();
    error SettlementMismatch();
    error HookAlreadySet();
    error UnknownToken(address token);
    error InvalidCurrency(address token, address currency);
    error PoolAlreadyRegistered(address token);
    error QuoteNotRoutable(address quote);
    error NoRoute(address currency);
    error PoolManagerBusy();
    error PoolNotInitialized(PoolId id);
    error PartialFill(uint256 spent, uint256 expected);
    error HopFeeTooHigh(uint256 feeBps);
    error OracleUnavailable(address token);
    error ReferenceNotSet(PoolId id);
    error PriceDeviation(int24 spotTick, int24 referenceTick);
    error UnbackedDeposit(address currency, uint256 balance, uint256 required);
    error NothingToRescue(address currency);
    error AmountExceedsHeld(uint256 amount, uint256 held);
    error InvalidDeviation(uint256 ticks);
    error InvalidDrift(uint256 ticks);
    error V3Unsupported();

    function _checkSource() private view {
        if (!isSource[msg.sender]) revert NotAuthorized();
    }

    modifier onlySelf() {
        if (msg.sender != address(this)) revert NotAuthorized();
        _;
    }

    constructor(
        address owner_,
        IPoolManager poolManager_,
        IConsolidatorRegistry quoteRegistry_,
        IFeeVault vault_,
        address weth_,
        uint256 maxSlippageBps_,
        uint256 maxDeviationTicks_
    ) Ownable(owner_) {
        if (
            address(poolManager_) == address(0) || address(quoteRegistry_) == address(0)
                || address(vault_) == address(0) || weth_ == address(0)
        ) revert ZeroAddress();
        if (maxSlippageBps_ > MAX_SLIPPAGE_CEILING_BPS) revert InvalidSlippage(maxSlippageBps_);
        if (maxDeviationTicks_ > MAX_TICK_SPAN) revert InvalidDeviation(maxDeviationTicks_);
        address settlement = vault_.settlementAsset();
        if (
            settlement == address(0) || quoteRegistry_.settlementAsset() != settlement
                || quoteRegistry_.donationToken(DonationAsset.Usdc) != settlement
                || quoteRegistry_.donationToken(DonationAsset.Eth) != weth_
        ) revert SettlementMismatch();
        IEpochGovernor governor_ = vault_.governor();
        if (address(governor_) == address(0)) revert ZeroAddress();
        poolManager = poolManager_;
        quoteRegistry = quoteRegistry_;
        vault = vault_;
        governor = governor_;
        weth = weth_;
        settlementAsset = settlement;
        maxSlippageBps = maxSlippageBps_;
        maxDeviationTicks = maxDeviationTicks_;
        // Default drift band: a fraction of the deviation guard, so the guard stays meaningful.
        maxDriftTicks = maxDeviationTicks_ / 2;
        inSwapMaxDeviationTicks = DEFAULT_IN_SWAP_DEVIATION_TICKS;
        inSwapMaxSlippageBps = DEFAULT_IN_SWAP_SLIPPAGE_BPS;
    }

    receive() external payable {
        // Only the unwrap of WETH is expected to send native ETH.
        if (msg.sender != weth && msg.sender != address(poolManager)) revert NotAuthorized();
    }

    // ------------------------------------------------------------------ administration

    /// @notice Sets the hook (once). The hook is also a fee source and the only pool registrar.
    function setHook(address hook_) external onlyOwner {
        if (hook_ == address(0)) revert ZeroAddress();
        if (hook != address(0)) revert HookAlreadySet();
        hook = hook_;
        isSource[hook_] = true;
        emit HookSet(hook_);
        emit SourceSet(hook_, true);
    }

    /// @notice Allows or disallows an account (hook, LP locker) to deliver fees.
    function setSource(address account, bool allowed) external onlyOwner {
        if (account == address(0)) revert ZeroAddress();
        isSource[account] = allowed;
        emit SourceSet(account, allowed);
    }

    /// @notice Sets the maximum slippage versus spot in basis points.
    function setMaxSlippageBps(uint256 bps) external onlyOwner {
        if (bps > MAX_SLIPPAGE_CEILING_BPS) revert InvalidSlippage(bps);
        maxSlippageBps = bps;
        emit MaxSlippageBpsUpdated(bps);
    }

    /// @notice Sets the maximum tick distance between spot and its reference.
    /// @dev Also resets `maxDriftTicks` to half of it (the constructor default), so the drift
    ///      band and anchor rate scale with the guard and never exceed it. The per hop reference
    ///      step cap is derived from it (a tenth, at least one tick). Call `setMaxDriftTicks`
    ///      afterwards for another ratio.
    function setMaxDeviationTicks(uint256 ticks) external onlyOwner {
        if (ticks > MAX_TICK_SPAN) revert InvalidDeviation(ticks);
        maxDeviationTicks = ticks;
        maxDriftTicks = ticks / 2;
        emit MaxDeviationTicksUpdated(ticks);
        emit MaxDriftTicksUpdated(ticks / 2);
    }

    /// @notice Sets the half width of the anchor band, which is also the most the anchor moves
    ///         per `ANCHOR_PERIOD`. Zero pins the reference to the anchor.
    function setMaxDriftTicks(uint256 ticks) external onlyOwner {
        if (ticks > maxDeviationTicks) revert InvalidDrift(ticks);
        maxDriftTicks = ticks;
        emit MaxDriftTicksUpdated(ticks);
    }

    /// @notice Sets the deviation and slippage bounds of claim conversions run inside a trader's
    ///         swap. Each is further capped by the general bound when used.
    function setInSwapBounds(uint256 deviationTicks, uint256 slippageBps) external onlyOwner {
        if (slippageBps > MAX_SLIPPAGE_CEILING_BPS) revert InvalidSlippage(slippageBps);
        if (deviationTicks > MAX_TICK_SPAN) revert InvalidDeviation(deviationTicks);
        inSwapMaxDeviationTicks = deviationTicks;
        inSwapMaxSlippageBps = slippageBps;
        emit InSwapBoundsUpdated(deviationTicks, slippageBps);
    }

    /// @notice Seeds the reference of route pools with their current spot tick.
    /// @dev Owner judgement: only seed while the pool trades at a fair price. Also used to
    ///      re-anchor a pool after a legitimate large move (for example an Ondo reopening gap).
    function seedReferences(PoolKey[] calldata keys) external onlyOwner {
        for (uint256 i; i < keys.length; ++i) {
            PoolId id = keys[i].toId();
            (uint160 sqrtPriceX96, int24 tick) = _spot(keys[i], id);
            if (sqrtPriceX96 == 0) revert PoolNotInitialized(id);
            _setReference(id, tick);
        }
    }

    /// @notice Sets a pool reference explicitly (for example from an external price).
    function setReference(PoolKey calldata key, int24 tick) external onlyOwner {
        _setReference(key.toId(), tick);
    }

    function _setReference(PoolId id, int24 tick) private {
        references[id] =
            Reference(tick, uint40(block.timestamp), true, tick, uint40(block.timestamp));
        emit ReferenceSet(id, tick);
    }

    /// @notice Moves the reference of route pool `key` toward its current spot, exactly as a
    ///         successful hop would (time weighted, capped step, clamped to the anchor band).
    ///         Permissionless, so a reference keeps following a market whose conversions fail the
    ///         price guards. A single manipulated spot moves it by at most one capped step.
    function syncReference(PoolKey calldata key) external nonReentrant returns (int24 tick) {
        PoolId id = key.toId();
        if (!references[id].set) revert ReferenceNotSet(id);
        (uint160 sqrtPriceX96, int24 spot) = _spot(key, id);
        if (sqrtPriceX96 == 0) revert PoolNotInitialized(id);
        _moveReference(id, spot);
        tick = references[id].tick;
        emit ReferenceSynced(id, spot, tick);
    }

    /// @notice Sends balances not owed to any token (dust, accidental transfers) to `to`.
    function rescueExcess(address currency, address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        uint256 balance = IERC20(currency).balanceOf(address(this));
        uint256 owed = totalHeld(currency);
        if (balance <= owed) revert NothingToRescue(currency);
        uint256 excess = balance - owed;
        IERC20(currency).safeTransfer(to, excess);
        emit Rescued(currency, to, excess);
    }

    // ------------------------------------------------------------------ pool registration

    /// @notice Records the pool of a launched token. Called by the hook when the pool initializes.
    function registerPool(address token, PoolKey calldata key) external {
        if (msg.sender != hook) revert NotAuthorized();
        if (quoteOf[token] != address(0)) revert PoolAlreadyRegistered(token);
        address c0 = Currency.unwrap(key.currency0);
        address c1 = Currency.unwrap(key.currency1);
        address quote = c0 == token ? c1 : c0;
        if (c0 != token && c1 != token) revert InvalidCurrency(token, token);
        if (quote == settlementAsset || token == settlementAsset) revert QuoteNotRoutable(quote);
        if (
            !quoteRegistry.isAllowed(quote)
                || !quoteRegistry.hasRouteTo(quote, vault.donationAssetOf(token))
        ) revert QuoteNotRoutable(quote);
        _poolKeys[token] = key;
        quoteOf[token] = quote;
        emit PoolRegistered(token, quote, key.toId());
    }

    // ------------------------------------------------------------------ consolidation

    /// @inheritdoc IFeeConsolidator
    function consolidate(address token, address currency, uint256 amount) external nonReentrant {
        if (!_receive(token, currency, amount)) return;
        uint256 total = _hold(token, currency, governor.currentEpoch(), amount);
        _attempt(token, currency, total);
    }

    /// @inheritdoc IFeeConsolidator
    function consolidateAccrued(
        address token,
        address currency,
        uint256 amount,
        uint256 accruedSince
    ) external nonReentrant {
        if (!_receive(token, currency, amount)) return;
        _holdOver(token, currency, amount, accruedSince);
        _attempt(token, currency, _holdings[token][currency].total);
    }

    /// @inheritdoc IFeeConsolidator
    /// @dev Reverts with the route's reason on failure, so the caller learns why.
    function retry(address token, address currency)
        external
        nonReentrant
        returns (uint256 settlementOut)
    {
        return _retry(token, currency, _holdings[token][currency].total);
    }

    /// @notice Like `retry` but consolidates only `amount` (for balances too large for the pool).
    function retryAmount(address token, address currency, uint256 amount)
        external
        nonReentrant
        returns (uint256 settlementOut)
    {
        return _retry(token, currency, amount);
    }

    /// @inheritdoc IFeeConsolidator
    /// @dev Never reverts on a route failure (it emits `ConsolidationFailed`). Swaps the whole
    ///      held balance of a currency, oldest tags first, so dust of an old epoch travels with
    ///      newer fees; `retryAmount` remains for a balance too large for the pool.
    function flushThrough(address token, uint256 epoch) external nonReentrant returns (bool clear) {
        address quote = quoteOf[token];
        // Nothing can be held for a token without a pool.
        if (quote == address(0)) return true;
        bool locked = !poolManager.isUnlocked();
        clear = _flushCurrency(token, token, epoch, locked);
        if (!_flushCurrency(token, quote, epoch, locked)) clear = false;
    }

    /// @inheritdoc IFeeConsolidator
    function heldFees(address token, address currency) external view returns (uint256) {
        return _holdings[token][currency].total;
    }

    /// @inheritdoc IFeeConsolidator
    function heldFeesIn(address token, address currency, uint256 epoch)
        external
        view
        returns (uint256)
    {
        Holding memory h = _holdings[token][currency];
        if (h.total == 0 || epoch > h.last) return 0;
        if (epoch == h.last) return h.total - h.older;
        return _heldIn[token][currency][epoch];
    }

    /// @inheritdoc IFeeConsolidator
    function heldThrough(address token, address currency, uint256 epoch)
        public
        view
        returns (bool)
    {
        Holding memory h = _holdings[token][currency];
        if (h.total == 0 || h.first > epoch) return false;
        // The newest part is never empty while anything is held (older parts are spent first).
        if (h.last <= epoch) return true;
        mapping(uint256 => uint256) storage parts = _heldIn[token][currency];
        for (uint256 e = h.first; e <= epoch; ++e) {
            if (parts[e] != 0) return true;
        }
        return false;
    }

    /// @notice Raw amount of `currency` owed to all tokens (held, not yet consolidated).
    function totalHeld(address currency) public view returns (uint256) {
        uint256 stored = _owedPlusOne[currency];
        return stored == 0 ? 0 : stored - 1;
    }

    /// @notice Executes a route. Callable by this contract only, so failures can be caught.
    function execute(address token, address currency, uint256 amount)
        external
        onlySelf
        returns (uint256)
    {
        return _execute(token, currency, amount);
    }

    /// @dev Checks a delivery and books it as owed. Returns false for a zero amount.
    function _receive(address token, address currency, uint256 amount) private returns (bool) {
        _checkSource();
        address quote = quoteOf[token];
        if (quote == address(0)) revert UnknownToken(token);
        if (currency != token && currency != quote) revert InvalidCurrency(token, currency);
        if (amount == 0) return false;

        uint256 owed = totalHeld(currency) + amount;
        _owedPlusOne[currency] = owed + 1;
        // Never account for what was not delivered.
        uint256 balance = IERC20(currency).balanceOf(address(this));
        if (balance < owed) revert UnbackedDeposit(currency, balance, owed);
        return true;
    }

    /// @dev Adds `amount` to the held balance, tagged with accrual `epoch`. Returns the new
    ///      held total.
    function _hold(address token, address currency, uint256 epoch, uint256 amount)
        private
        returns (uint256)
    {
        Holding memory h = _holdings[token][currency];
        if (amount == 0) return h.total;
        uint24 e = epoch.toUint24();
        if (h.total == 0) {
            h.first = e;
            h.last = e;
            h.older = 0;
        } else if (e > h.last) {
            // A newer epoch: the current newest part moves to `_heldIn` (once per epoch).
            _heldIn[token][currency][h.last] = h.total - h.older;
            h.older = h.total;
            h.last = e;
        } else if (e < h.last) {
            _heldIn[token][currency][e] += amount;
            if (h.older == 0 || e < h.first) h.first = e;
            h.older = (uint256(h.older) + amount).toUint104();
        }
        uint256 total = uint256(h.total) + amount;
        h.total = total.toUint104();
        _holdings[token][currency] = h;
        return total;
    }

    /// @dev Spreads `amount`, earned evenly over `[since, now]`, across the epochs of that
    ///      interval by the time each covers. The oldest epoch takes the rounding remainder.
    function _holdOver(address token, address currency, uint256 amount, uint256 since) private {
        uint256 current = governor.currentEpoch();
        uint256 oldest = current >= MAX_ACCRUAL_EPOCHS ? current - (MAX_ACCRUAL_EPOCHS - 1) : 0;
        uint256 floor = governor.epochStart(oldest);
        if (since < floor) since = floor;
        if (since >= block.timestamp) {
            _hold(token, currency, current, amount);
            return;
        }

        uint256 total = block.timestamp - since;
        uint256 remaining = amount;
        uint256 end = block.timestamp;
        for (uint256 epoch = current;; --epoch) {
            uint256 start = governor.epochStart(epoch);
            if (start > end) start = end;
            if (start <= since || epoch == oldest) {
                _hold(token, currency, epoch, remaining);
                return;
            }
            uint256 part = FullMath.mulDiv(amount, end - start, total);
            _hold(token, currency, epoch, part);
            remaining -= part;
            end = start;
        }
    }

    /// @dev Takes `amount` (at most the held total) from the held balance, oldest accrual epoch
    ///      first, and returns the parts taken with their epochs.
    function _release(address token, address currency, uint256 amount)
        private
        returns (uint256[] memory epochs, uint256[] memory parts)
    {
        Holding memory h = _holdings[token][currency];
        _owedPlusOne[currency] -= amount;

        // Every part is tagged between `first` and `last`, so this many slots always suffice.
        uint256 slots = uint256(h.last) - h.first + 1;
        epochs = new uint256[](slots);
        parts = new uint256[](slots);
        uint256 count;
        uint256 remaining = amount;
        uint256 e = h.first;
        mapping(uint256 => uint256) storage older = _heldIn[token][currency];
        while (remaining != 0 && h.older != 0) {
            uint256 bucket = older[e];
            if (bucket != 0) {
                uint256 take = bucket < remaining ? bucket : remaining;
                older[e] = bucket - take;
                h.older -= uint104(take);
                epochs[count] = e;
                parts[count] = take;
                ++count;
                remaining -= take;
                if (take < bucket) break;
            }
            ++e;
        }
        if (remaining != 0) {
            // The rest comes from the newest part (`amount` never exceeds the total).
            epochs[count] = h.last;
            parts[count] = remaining;
            ++count;
        }
        h.first = h.older == 0 ? h.last : uint24(e);
        h.total -= uint104(amount);
        _holdings[token][currency] = h;
        assembly ("memory-safe") {
            mstore(epochs, count)
            mstore(parts, count)
        }
    }

    function _retry(address token, address currency, uint256 amount) private returns (uint256) {
        uint256 held = _holdings[token][currency].total;
        if (held == 0 || amount == 0) revert NothingToConsolidate(token, currency);
        if (amount > held) revert AmountExceedsHeld(amount, held);
        if (poolManager.isUnlocked()) revert PoolManagerBusy();
        return _execute(token, currency, amount);
    }

    /// @dev Tries to swap the whole held balance of `currency` if any part of it is tagged
    ///      `epoch` or older. Returns whether no such part is held afterwards.
    function _flushCurrency(address token, address currency, uint256 epoch, bool locked)
        private
        returns (bool)
    {
        if (!heldThrough(token, currency, epoch)) return true;
        if (!locked) return false;
        return _tryExecute(token, currency, _holdings[token][currency].total);
    }

    /// @dev Runs `execute` on this contract and reports whether it succeeded; a failure is
    ///      logged with its reason and never reverts.
    function _tryExecute(address token, address currency, uint256 amount) private returns (bool) {
        try this.execute(token, currency, amount) returns (uint256) {
            return true;
        } catch (bytes memory reason) {
            emit ConsolidationFailed(token, currency, amount, reason);
            return false;
        }
    }

    function _attempt(address token, address currency, uint256 amount) private {
        if (amount == 0) return;
        if (poolManager.isUnlocked()) {
            // Inside a pool manager flow (the hook during a swap): hold and settle later.
            emit ConsolidationFailed(
                token, currency, amount, abi.encodeWithSelector(PoolManagerBusy.selector)
            );
            return;
        }
        _tryExecute(token, currency, amount);
    }

    /// @dev Swaps `amount` of held `currency` and credits the output to the accrual epochs of
    ///      the parts spent, in proportion (the newest part takes the rounding remainder), in
    ///      one vault deposit. A dust amount whose route rounds to zero output is consumed and
    ///      credits nothing (every hop's minimum output is then zero, so no amount that is worth
    ///      something can end like this).
    function _execute(address token, address currency, uint256 amount)
        private
        returns (uint256 out)
    {
        (uint256[] memory epochs, uint256[] memory parts) = _release(token, currency, amount);

        // `currency` is the token or its quote asset, never the settlement asset itself.
        address target = _targetOf(token);
        if (currency == target) {
            // A WETH-quoted token whose donation asset is ETH: nothing to convert.
            out = amount;
        } else {
            bytes memory result =
                poolManager.unlock(abi.encode(token, currency, amount, address(this)));
            out = abi.decode(result, (uint256));
        }

        if (out != 0) {
            IERC20(target).safeTransfer(address(vault), out);
            // Each part becomes its share of the output; the last one takes the remainder.
            uint256 n = parts.length;
            uint256 left = out;
            for (uint256 i; i + 1 < n; ++i) {
                uint256 share = FullMath.mulDiv(out, parts[i], amount);
                parts[i] = share;
                left -= share;
            }
            parts[n - 1] = left;
            vault.depositFees(token, epochs, parts);
        }
        emit FeesConsolidated(token, currency, amount, out);
    }

    /// @inheritdoc IFeeConsolidator
    /// @dev For the live-donation hook, which holds its fees as ERC-6909 claims and converts them
    ///      inside the pool manager flow it is already in (a swap, or its own unlock for retries).
    ///      Burning the caller's claims as its operator credits this contract with `amount` of
    ///      `currency`; every hop is the same `_hop` as consolidation (reference-tick guard,
    ///      slippage and hop-fee bound, full fill, reference move), with the in-swap bounds when
    ///      `inSwap` (the trader chooses when an in-line conversion runs and can move route pools
    ///      in the same transaction, so it gets the tightest guard), and the settlement asset is
    ///      taken straight to `to`. Every pool manager delta of this contract is zero when it
    ///      returns. Never calls `sync`; the only `settle` is the native one inside the WETH
    ///      unwrap hop, so the caller must make sure no currency is synced (the live hook checks).
    ///      The token-pool TWAP guard is not used: the claims are never in a launched token.
    function convertClaims(address currency, uint256 amount, address to, bool inSwap)
        external
        nonReentrant
        returns (uint256 out)
    {
        return _convertClaims(currency, amount, to, inSwap, DonationAsset.Usdc);
    }

    /// @inheritdoc IFeeConsolidator
    /// @dev Same as `convertClaims` with a chosen donation asset: `Eth` converts into WETH (a
    ///      route ending in native ETH is wrapped; a WETH claim is paid out as is).
    function convertClaimsTo(
        address currency,
        uint256 amount,
        address to,
        bool inSwap,
        DonationAsset da
    ) external nonReentrant returns (uint256 out) {
        return _convertClaims(currency, amount, to, inSwap, da);
    }

    function _convertClaims(
        address currency,
        uint256 amount,
        address to,
        bool inSwap,
        DonationAsset da
    ) private returns (uint256 out) {
        _checkSource();
        if (to == address(0)) revert ZeroAddress();
        if (amount == 0) revert NothingToConsolidate(address(0), currency);
        if (!poolManager.isUnlocked()) revert PoolManagerLocked();
        address target = _donationToken(da);
        PoolKey[] memory route = quoteRegistry.routeToOf(currency, da);
        if (route.length == 0 && currency != target) revert NoRoute(currency);

        poolManager.burn(msg.sender, Currency.wrap(currency).toId(), amount);
        address current;
        (current, out) = _walk(route, currency, amount, address(0), false, inSwap);
        if (out == 0) revert SlippageTooHigh(0, 1);

        _payOut(current, out, target, to);
        emit ClaimsConverted(msg.sender, currency, to, amount, out);
    }

    // ------------------------------------------------------------------ unlock callback

    /// @inheritdoc IUnlockCallback
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager)) revert NotAuthorized();
        (address token, address currencyIn, uint256 amountIn, address to) =
            abi.decode(data, (address, address, uint256, address));
        return abi.encode(_convertIn(token, currencyIn, amountIn, to, false));
    }

    /// @dev Pays `amountIn` of `currencyIn` into the (unlocked) pool manager, runs it along its
    ///      route and pays the result to `to`. Token zero marks a donation conversion (WETH into
    ///      the settlement asset for an Endaoment push), which reverts when nothing comes out;
    ///      a consolidation of dust may end in zero. `tight` selects the in-swap bounds.
    function _convertIn(
        address token,
        address currencyIn,
        uint256 amountIn,
        address to,
        bool tight
    ) private returns (uint256 amount) {
        address target;
        PoolKey[] memory route;
        bool tokenHop;
        if (token == address(0)) {
            target = settlementAsset;
            route = quoteRegistry.routeOf(weth);
            if (route.length == 0) revert NoRoute(weth);
        } else {
            target = _targetOf(token);
            route = _routeFor(token, currencyIn);
            tokenHop = currencyIn == token;
        }

        poolManager.sync(Currency.wrap(currencyIn));
        IERC20(currencyIn).safeTransfer(address(poolManager), amountIn);
        poolManager.settle();

        address current;
        (current, amount) = _walk(route, currencyIn, amountIn, token, tokenHop, tight);
        if (token == address(0) && amount == 0) revert SlippageTooHigh(0, 1);
        _payOut(current, amount, target, to);
    }

    /// @dev Pays `amount` of `current` (the end of a route) to `to` as `target`: taken straight
    ///      when it is the target, or taken as native ETH and wrapped when the target is WETH.
    function _payOut(address current, uint256 amount, address target, address to) private {
        if (current == target) {
            poolManager.take(Currency.wrap(current), to, amount);
        } else if (current == address(0) && target == weth) {
            poolManager.take(Currency.wrap(address(0)), address(this), amount);
            IWETH(weth).deposit{value: amount}();
            if (to != address(this)) IERC20(weth).safeTransfer(to, amount);
        } else {
            revert NoRoute(current);
        }
    }

    /// @dev The currency a token's fees consolidate into: USDC or WETH.
    function _targetOf(address token) private view returns (address) {
        return _donationToken(vault.donationAssetOf(token));
    }

    /// @dev The currency of a donation asset. Equal to the registry's `donationToken` (checked at
    ///      construction), without the external call.
    function _donationToken(DonationAsset da) private view returns (address) {
        return da == DonationAsset.Usdc ? settlementAsset : weth;
    }

    /// @inheritdoc IFeeConsolidator
    /// @dev For the vaults pushing an `Eth` cause pool to Endaoment, which takes USDC. Pulls
    ///      `amount` WETH from the caller (exact allowance), swaps it into USDC along the WETH
    ///      route of the registry with the same price guards as consolidation, and pays the
    ///      USDC to `to`. Outside a pool manager flow it unlocks the manager itself; inside one
    ///      (a live vault pushing within a swap) it runs inline with the tight in-swap bounds.
    ///      Reverts on any guard failure, so the caller keeps its WETH and retries later.
    function convertDonation(uint256 amount, address to)
        external
        nonReentrant
        returns (uint256 out)
    {
        _checkSource();
        if (to == address(0)) revert ZeroAddress();
        if (amount == 0) revert NothingToConsolidate(address(0), weth);
        IERC20(weth).safeTransferFrom(msg.sender, address(this), amount);

        if (poolManager.isUnlocked()) {
            out = _convertIn(address(0), weth, amount, to, true);
        } else {
            out = abi.decode(
                poolManager.unlock(abi.encode(address(0), weth, amount, to)), (uint256)
            );
        }
        emit DonationConverted(msg.sender, amount, out);
    }

    function _routeFor(address token, address currency)
        private
        view
        returns (PoolKey[] memory route)
    {
        address quote = quoteOf[token];
        PoolKey[] memory quoteRoute =
            quoteRegistry.routeToOf(quote, vault.donationAssetOf(token));
        if (currency == quote) return quoteRoute;
        if (currency != token) revert InvalidCurrency(token, currency);

        route = new PoolKey[](quoteRoute.length + 1);
        route[0] = _poolKeys[token];
        for (uint256 i; i < quoteRoute.length; ++i) {
            route[i + 1] = quoteRoute[i];
        }
    }

    /// @dev Runs `amount` of `current` through every hop of `route`. `tokenHop` marks the first hop
    ///      as the token's own pool; `inSwap` selects the in-swap bounds and, as the trader can
    ///      move pools in the same transaction, forbids hooked route pools.
    function _walk(
        PoolKey[] memory route,
        address current,
        uint256 amount,
        address token,
        bool tokenHop,
        bool inSwap
    ) private returns (address, uint256) {
        for (uint256 i; i < route.length; ++i) {
            if (inSwap && address(route[i].hooks) != address(0)) revert HookedRouteHop(i);
            (current, amount) = _hop(route[i], current, amount, token, tokenHop && i == 0, inSwap);
        }
        return (current, amount);
    }

    /// @dev Swaps `amount` of `current` exact-input through `key`, applying the price guards.
    ///      `inSwap` selects the in-swap deviation and slippage bounds.
    function _hop(
        PoolKey memory key,
        address current,
        uint256 amount,
        address token,
        bool tokenHop,
        bool inSwap
    ) private returns (address next, uint256 out) {
        // WETH to a native ETH pool: unwrap inside the unlock.
        if (
            current == weth && Currency.unwrap(key.currency0) != weth
                && Currency.unwrap(key.currency1) != weth
        ) {
            poolManager.take(Currency.wrap(weth), address(this), amount);
            IWETH(weth).withdraw(amount);
            poolManager.settle{value: amount}();
            current = address(0);
        }

        bool zeroForOne = current == Currency.unwrap(key.currency0);
        if (!zeroForOne && current != Currency.unwrap(key.currency1)) revert NoRoute(current);

        int24 tick;
        {
            uint256 minOut;
            (minOut, tick) = _prepare(
                key, amount, zeroForOne, token, tokenHop, inSwap
            );
            out = V3RouteLib.isV3(key)
                ? _hopV3(key, zeroForOne, amount)
                : _swapV4(key, zeroForOne, amount);
            if (out < minOut) revert SlippageTooHigh(out, minOut);
        }

        if (!tokenHop) _moveReference(key.toId(), tick);
        next = Currency.unwrap(zeroForOne ? key.currency1 : key.currency0);
    }

    /// @dev Reads the pool, runs the deviation guard of a hop and returns the least output the hop
    ///      may produce together with the spot tick.
    function _prepare(
        PoolKey memory key,
        uint256 amount,
        bool zeroForOne,
        address token,
        bool tokenHop,
        bool inSwap
    ) private view returns (uint256 minOut, int24 tick) {
        PoolId id = key.toId();
        uint256 slippage;
        uint256 expected;
        {
            uint160 sqrtPriceX96;
            (sqrtPriceX96, tick) = _spot(key, id);
            if (sqrtPriceX96 == 0) revert PoolNotInitialized(id);
            uint256 deviation;
            (slippage, deviation) = _bounds(inSwap);
            int24 referenceTick = _checkDeviation(key, id, tick, token, tokenHop, deviation);
            expected = _bestQuote(amount, sqrtPriceX96, referenceTick, zeroForOne);
        }
        uint256 tolerance = slippage + _hopFeeBps(key, id, token, tokenHop);
        minOut = (expected * (BPS - tolerance)) / BPS;
    }

    /// @dev The slippage and deviation bounds in force (the in-swap ones are only ever tighter).
    function _bounds(bool inSwap) private view returns (uint256 slippage, uint256 deviation) {
        slippage = maxSlippageBps;
        deviation = maxDeviationTicks;
        if (inSwap) {
            if (inSwapMaxSlippageBps < slippage) slippage = inSwapMaxSlippageBps;
            if (inSwapMaxDeviationTicks < deviation) deviation = inSwapMaxDeviationTicks;
        }
    }

    /// @dev Expected output at the better of spot and the reference: a spot pushed below the
    ///      reference (inside the band) does not lower the minimum.
    function _bestQuote(uint256 amount, uint160 sqrtPriceX96, int24 referenceTick, bool zeroForOne)
        private
        pure
        returns (uint256 expected)
    {
        expected = _quote(amount, sqrtPriceX96, zeroForOne);
        uint256 atReference = _quote(amount, TickMath.getSqrtPriceAtTick(referenceTick), zeroForOne);
        if (atReference > expected) expected = atReference;
    }

    /// @dev Exact-input swap through a v4 pool inside the unlock; requires a full fill.
    function _swapV4(PoolKey memory key, bool zeroForOne, uint256 amount)
        private
        returns (uint256 out)
    {
        BalanceDelta delta = poolManager.swap(
            key,
            SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amount),
                sqrtPriceLimitX96: zeroForOne
                    ? TickMath.MIN_SQRT_PRICE + 1
                    : TickMath.MAX_SQRT_PRICE - 1
            }),
            ""
        );
        int128 spent = zeroForOne ? delta.amount0() : delta.amount1();
        int128 received = zeroForOne ? delta.amount1() : delta.amount0();
        if (spent >= 0 || uint256(uint128(-spent)) != amount) {
            revert PartialFill(spent >= 0 ? 0 : uint256(uint128(-spent)), amount);
        }
        out = received > 0 ? uint256(uint128(received)) : 0;
    }

    /// @dev Spot of a route pool, v3 or v4 (a v3 hop has no pool manager state).
    function _spot(PoolKey memory key, PoolId id)
        private
        view
        returns (uint160 sqrtPriceX96, int24 tick)
    {
        if (V3RouteLib.isV3(key)) return _v3Spot(key);
        (sqrtPriceX96, tick,,) = poolManager.getSlot0(id);
    }

    /// @dev Spot of a v3 pool as `(sqrtPriceX96, tick)`; zero when the pool does not exist.
    ///      Overridden by `FeeConsolidatorV3`; the base contract routes through v4 only.
    function _v3Spot(PoolKey memory) internal view virtual returns (uint160, int24) {
        revert V3Unsupported();
    }

    /// @dev A v3 hop inside the pool manager flow; returns the output received. The input is a
    ///      credit of this contract at the pool manager: it is taken out, swapped on the v3 pool,
    ///      and the output is paid back in as a credit, so the next hop (or the final `take`)
    ///      sees the same accounting as after a v4 hop. Reverts unless the whole amount is spent.
    ///      Overridden by `FeeConsolidatorV3`.
    function _hopV3(PoolKey memory, bool, uint256) internal virtual returns (uint256) {
        revert V3Unsupported();
    }

    /// @dev Output of `amount` at price `sqrtPriceX96`, before fees and impact: `amount` times
    ///      the price (squared sqrt price, or its inverse), in two rounded-down steps. One
    ///      `mulDiv` call site serves both steps and both directions to keep the code small.
    function _quote(uint256 amount, uint160 sqrtPriceX96, bool zeroForOne)
        private
        pure
        returns (uint256)
    {
        (uint256 num, uint256 den) =
            zeroForOne ? (uint256(sqrtPriceX96), uint256(1 << 96)) : (uint256(1 << 96), uint256(sqrtPriceX96));
        for (uint256 i; i < 2; ++i) {
            amount = FullMath.mulDiv(amount, num, den);
        }
        return amount;
    }

    /// @dev Reverts unless `spotTick` is within `maxTicks` of the hop's reference; returns it.
    function _checkDeviation(
        PoolKey memory key,
        PoolId id,
        int24 spotTick,
        address token,
        bool tokenHop,
        uint256 maxTicks
    ) private view returns (int24 referenceTick) {
        if (tokenHop) {
            (bool ok, int24 twap) = IHookOracle(address(key.hooks)).twapTick(token, TWAP_WINDOW);
            if (!ok) revert OracleUnavailable(token);
            referenceTick = twap;
        } else {
            Reference memory ref = references[id];
            if (!ref.set) revert ReferenceNotSet(id);
            referenceTick = ref.tick;
        }
        int256 diff = int256(spotTick) - int256(referenceTick);
        if (uint256(diff < 0 ? -diff : diff) > maxTicks) {
            revert PriceDeviation(spotTick, referenceTick);
        }
    }

    /// @dev After a successful hop or a `syncReference`: first moves the anchor toward the
    ///      reference by at most `maxDriftTicks` per `ANCHOR_PERIOD` of elapsed time (one period
    ///      at most counts), then moves the reference toward spot by the elapsed fraction of
    ///      `REFERENCE_WINDOW`, each step capped at a tenth of `maxDeviationTicks` (at least one
    ///      tick), and clamps it to `anchor ± maxDriftTicks`.
    ///      A clock whose step rounds to zero keeps its elapsed time, so frequent moves (an
    ///      in-line conversion on every swap) still add up and cannot freeze the reference. A
    ///      clock already at its target restarts, so a quiet pool banks nothing.
    function _moveReference(PoolId id, int24 spotTick) private {
        Reference memory r = references[id];
        int256 drift = int256(maxDriftTicks); // at most MAX_TICK_SPAN
        uint256 nowTs = block.timestamp;

        int256 gap = int256(r.tick) - int256(r.anchor);
        if (gap == 0) {
            r.anchoredAt = uint40(nowTs);
        } else {
            uint256 dt = nowTs - r.anchoredAt;
            if (dt > ANCHOR_PERIOD) dt = ANCHOR_PERIOD;
            int256 allowance = (drift * int256(dt)) / int256(ANCHOR_PERIOD);
            if (allowance != 0) {
                if (gap > allowance) gap = allowance;
                if (gap < -allowance) gap = -allowance;
                r.anchor = int24(int256(r.anchor) + gap);
                r.anchoredAt = uint40(nowTs);
            }
        }

        int256 diff = int256(spotTick) - int256(r.tick);
        if (diff == 0) {
            // Already at spot: nothing is owed for the elapsed time.
            r.updatedAt = uint40(nowTs);
        } else {
            uint256 dt = nowTs - r.updatedAt;
            if (dt > REFERENCE_WINDOW) dt = REFERENCE_WINDOW;
            int256 step = (diff * int256(dt)) / int256(REFERENCE_WINDOW);
            if (step != 0) {
                int256 cap = int256(maxDeviationTicks / 10);
                if (cap == 0) cap = 1;
                if (step > cap) step = cap;
                if (step < -cap) step = -cap;
                r.tick = int24(int256(r.tick) + step);
                r.updatedAt = uint40(nowTs);
            }
        }

        // Keep the reference in the band (also after the owner narrows `maxDriftTicks`).
        int256 lo = int256(r.anchor) - drift;
        int256 hi = int256(r.anchor) + drift;
        if (lo < TickMath.MIN_TICK) lo = TickMath.MIN_TICK;
        if (hi > TickMath.MAX_TICK) hi = TickMath.MAX_TICK;
        if (r.tick < lo) r.tick = int24(lo);
        if (r.tick > hi) r.tick = int24(hi);
        references[id] = r;
    }

    /// @dev Pool fee of a hop in basis points, rounded up.
    function _hopFeeBps(PoolKey memory key, PoolId id, address token, bool tokenHop)
        private
        view
        returns (uint256 feeBps)
    {
        if (tokenHop) {
            // The token pool uses an overridden dynamic fee equal to the token's base fee.
            feeBps = IHookBaseFee(address(key.hooks)).feeConfig(token);
        } else {
            uint256 pips = key.fee;
            if (LPFeeLibrary.isDynamicFee(key.fee)) {
                // A v3 hop has no dynamic fee, so only a v4 hop reaches this.
                (,,, uint24 lpFee) = poolManager.getSlot0(id);
                pips = lpFee;
            }
            feeBps = (pips + 99) / 100;
        }
        if (feeBps > MAX_HOP_FEE_BPS) revert HopFeeTooHigh(feeBps);
    }
}

src/V3SwapExecutor.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";

import {
    IUniswapV3Factory,
    IUniswapV3Pool,
    IUniswapV3SwapCallback
} from "./interfaces/external/IUniswapV3.sol";

/// @title V3SwapExecutor
/// @notice Executes one exact-input swap on a Uniswap v3 pool for the fee consolidator, and is the
///         swap callback of that pool.
/// @dev Kept out of the consolidator so the consolidator's runtime stays under the contract size
///      limit and so the callback has a single, tiny trust boundary. Holds no funds between calls
///      and has no owner: only `consolidator` may call `swap`. The consolidator sends the input
///      here, `swap` pays the pool from it in the callback (the pool is the factory's pool of the
///      sorted pair and fee, nothing else), and the output goes straight to the consolidator.
///      The callback is authenticated by transient storage written only around the pool call: the
///      pool address and the input amount. It is cleared before paying, so a second callback in the
///      same swap pays nothing.
contract V3SwapExecutor is IUniswapV3SwapCallback {
    using SafeERC20 for IERC20;
    using SafeCast for uint256;

    IUniswapV3Factory public immutable factory;
    address public immutable consolidator;
    /// @notice Where the output goes (the consolidator settles it into its pool manager credit).
    address public immutable poolManager;

    /// @dev Transient slots of the callback context (fixed constants, used nowhere else).
    bytes32 private constant _POOL_SLOT =
        0x6d1a0d5ff7e85a1c3a3ed7f0c2b9f0a6f9d1d8e3b4ad6c7d3a95ed6f1b2c4a01;
    bytes32 private constant _TOKEN_SLOT =
        0x6d1a0d5ff7e85a1c3a3ed7f0c2b9f0a6f9d1d8e3b4ad6c7d3a95ed6f1b2c4a02;
    bytes32 private constant _AMOUNT_SLOT =
        0x6d1a0d5ff7e85a1c3a3ed7f0c2b9f0a6f9d1d8e3b4ad6c7d3a95ed6f1b2c4a03;

    error NotConsolidator();
    error V3PoolMissing(address token0, address token1, uint24 fee);
    error V3CallbackUnauthorized();
    /// @dev Same signature as `FeeConsolidator.PartialFill`, so callers see one selector.
    error PartialFill(uint256 spent, uint256 expected);

    constructor(IUniswapV3Factory factory_, address consolidator_, address poolManager_) {
        factory = factory_;
        consolidator = consolidator_;
        poolManager = poolManager_;
    }

    /// @notice The factory's pool of the sorted pair `(token0, token1)` and `fee`; reverts when the
    ///         shape is wrong or the pool does not exist.
    function poolOf(address token0, address token1, uint24 fee)
        public
        view
        returns (IUniswapV3Pool pool)
    {
        if (token0 == address(0) || token0 >= token1) revert V3PoolMissing(token0, token1, fee);
        pool = IUniswapV3Pool(factory.getPool(token0, token1, fee));
        if (address(pool) == address(0)) revert V3PoolMissing(token0, token1, fee);
    }

    /// @notice Spot of the pool of `(token0, token1, fee)`.
    function spot(address token0, address token1, uint24 fee)
        external
        view
        returns (uint160 sqrtPriceX96, int24 tick)
    {
        (sqrtPriceX96, tick,,,,,) = poolOf(token0, token1, fee).slot0();
    }

    /// @notice Swaps `amount` of `tokenIn` (already held here) for `tokenOut`, sending the output
    ///         to the consolidator. Reverts unless the whole amount is spent.
    function swap(address tokenIn, address tokenOut, uint24 fee, uint256 amount) external {
        if (msg.sender != consolidator) revert NotConsolidator();
        bool zeroForOne = tokenIn < tokenOut;
        IUniswapV3Pool pool =
            zeroForOne ? poolOf(tokenIn, tokenOut, fee) : poolOf(tokenOut, tokenIn, fee);

        _setContext(address(pool), tokenIn, amount);
        (int256 amount0, int256 amount1) = pool.swap(
            poolManager,
            zeroForOne,
            amount.toInt256(),
            zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1,
            ""
        );
        _setContext(address(0), address(0), 0);

        int256 spent = zeroForOne ? amount0 : amount1;
        if (spent <= 0 || uint256(spent) != amount) {
            revert PartialFill(spent <= 0 ? 0 : uint256(spent), amount);
        }
    }

    /// @inheritdoc IUniswapV3SwapCallback
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata)
        external
        override
    {
        (address pool, address tokenIn, uint256 expected) = _context();
        // Cleared first: a second callback in the same swap pays nothing.
        _setContext(address(0), address(0), 0);
        if (pool == address(0) || msg.sender != pool) revert V3CallbackUnauthorized();

        int256 owed = amount0Delta > 0 ? amount0Delta : amount1Delta;
        // A partial fill pays less than asked (`swap` then reports it). Never more.
        if (owed <= 0 || uint256(owed) > expected) revert V3CallbackUnauthorized();
        IERC20(tokenIn).safeTransfer(pool, uint256(owed));
    }

    function _setContext(address pool, address tokenIn, uint256 amount) private {
        bytes32 p = _POOL_SLOT;
        bytes32 t = _TOKEN_SLOT;
        bytes32 a = _AMOUNT_SLOT;
        assembly ("memory-safe") {
            tstore(p, pool)
            tstore(t, tokenIn)
            tstore(a, amount)
        }
    }

    function _context() private view returns (address pool, address tokenIn, uint256 amount) {
        bytes32 p = _POOL_SLOT;
        bytes32 t = _TOKEN_SLOT;
        bytes32 a = _AMOUNT_SLOT;
        assembly ("memory-safe") {
            pool := tload(p)
            tokenIn := tload(t)
            amount := tload(a)
        }
    }
}

src/interfaces/ICuratorRegistry.sol

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

/// @title ICuratorRegistry
/// @notice One curator agent per cause category, named `<label>.agent.<parent>`. Each week an
///         agent submits, for the next epoch, per region: a Merkle root of up to `MAX_PICKS` ranked
///         catalogue picks and an urgency weight. `EpochGovernor` reads them to build ballots.
/// @dev A pick leaf is the OpenZeppelin standard-tree leaf of
///      `(uint8 rank, uint32 catalogIndex, bytes32 orgId)`; ranks run `0..count-1`. Picks are not
///      checked on submission: the governor skips any pick whose catalogue entry is not that org.
interface ICuratorRegistry {
    struct Agent {
        uint256 agentId;
        address signer;
        address vault;
        bool active;
        bytes32 labelhash;
        string label;
        string description;
    }

    struct Curation {
        bytes32 picksRoot;
        uint8 count;
        uint16 weight;
        uint32 catalogVersion;
    }

    struct CurationInput {
        uint8 regionBit;
        bytes32 picksRoot;
        uint8 count;
        uint16 weight;
    }

    event AgentRegistered(
        uint8 indexed categoryBit,
        uint256 indexed agentId,
        string label,
        address signer,
        address vault
    );
    event SignerSet(uint8 indexed categoryBit, address signer);
    event ActiveSet(uint8 indexed categoryBit, bool active);
    event AgentURISet(uint8 indexed categoryBit, string agentURI);
    event DescriptionSet(uint8 indexed categoryBit, string description);
    event AgentWalletLinked(uint8 indexed categoryBit, address wallet);
    event GovernorSet(address governor);
    /// @notice One per region in a weekly submission; `reportRef` is the Swarm reference of the
    ///         full report (picks with scores, reasons, sources, and the newsletter).
    event CurationSet(
        uint16 indexed bucket,
        uint256 indexed epoch,
        bytes32 picksRoot,
        uint8 count,
        uint16 weight,
        uint32 catalogVersion
    );
    event CurationsSubmitted(
        uint8 indexed categoryBit, uint256 indexed epoch, uint32 catalogVersion, bytes32 reportRef
    );
    /// @notice The owner dropped `bucket`'s curation for `epoch` (`voidCurations`).
    event CurationVoided(uint16 indexed bucket, uint256 indexed epoch);

    error ZeroAddress();
    error UnknownAgent(uint8 categoryBit);
    error AgentExists(uint8 categoryBit);
    error LabelTaken(bytes32 labelhash);
    error InvalidCategory(uint8 categoryBit);
    error InvalidRegion(uint8 regionBit);
    error NotSigner(uint8 categoryBit, address caller);
    error AgentInactive(uint8 categoryBit);
    error NotNextEpoch(uint256 epoch);
    error InvalidCuration();
    error GovernorAlreadySet();
    error GovernorNotSet();

    function MAX_PICKS() external view returns (uint8);
    function MAX_WEIGHT() external view returns (uint16);

    function registerAgent(
        uint8 categoryBit,
        string calldata label,
        address signer,
        string calldata agentURI,
        string calldata description
    ) external returns (uint256 agentId, address vault);

    function submitCurations(
        uint8 categoryBit,
        uint256 epoch,
        uint32 catalogVersion,
        bytes32 reportRef,
        CurationInput[] calldata curations
    ) external;

    /// @notice Owner only. Deletes the curations of `buckets` for `epoch`, so ballots and rounds of
    ///         that epoch not yet prepared skip them and fill with rotation. For picks committed
    ///         but never served, or a bad root: unlike pausing the agent, it touches one epoch
    ///         only, so the agent stays active and can submit the next epoch's picks. Only the next
    ///         epoch's curation can be submitted again.
    function voidCurations(uint256 epoch, uint16[] calldata buckets) external;

    function agentOf(uint8 categoryBit) external view returns (Agent memory);
    function isRegistered(uint8 categoryBit) external view returns (bool);
    function signerOf(uint8 categoryBit) external view returns (address);
    function categoryOfLabelhash(bytes32 labelhash)
        external
        view
        returns (bool found, uint8 categoryBit);
    function categoryOfNode(bytes32 node) external view returns (bool found, uint8 categoryBit);
    /// @notice Namehash of `agent.<parent>`.
    function agentsNode() external view returns (bytes32);

    function curationOf(uint16 bucket, uint256 epoch) external view returns (Curation memory);

    /// @notice Usable curations of `buckets` for `epoch` under `catalogVersion`: zeroed for a bucket
    ///         with no agent, an inactive agent, nothing submitted (or voided), or another catalogue
    ///         version.
    function curationsFor(uint256 epoch, uint32 catalogVersion, uint16[] calldata buckets)
        external
        view
        returns (Curation[] memory);

    function currentEpoch() external view returns (uint256);
}

src/interfaces/IDonationAsset.sol

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

/// @notice The asset a token's fees are consolidated into and its cause pool is kept in.
/// @dev `Usdc` is the original behaviour (value 0, the default). `Eth` is held on chain as WETH;
///      the donation itself always reaches Endaoment as USDC (converted at push time).
enum DonationAsset {
    Usdc,
    Eth
}

src/interfaces/IEpochGovernor.sol

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

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

/// @title IEpochGovernor
/// @notice Weekly epochs in which token holders choose the cause receiving the cause pool.
/// @dev Each epoch of a token is a poll on the pluggable voting scheme. Its ballot is prepared at
///      the start of the epoch from the token's cause focus (fixed at launch) and the cause
///      catalogue version in effect at that time:
///      - up to `PINNED_MAX` causes pinned by the token's controller (its "shortlist"), each proven
///        to be a catalogue entry inside the focus;
///      - then curator agents' picks for the focus buckets, when published;
///      - the rest filled by rotation: draw `k` is pool entry
///        `keccak256(abi.encode(token, epoch, version, k)) % poolSize`, skipping blocked causes and
///        repeats, so over time every charity in the focus reaches a ballot. When the pool is not
///        larger than the free slots, the whole pool is taken in order.
///      Ballot size: the owner sets a protocol cap (`ballotSizeCap`, `MIN_OPTIONS..MAX_OPTIONS`,
///      `MAX_OPTIONS` by default) and a token's controller may choose its own size
///      (`setBallotSize`, zero to follow the cap). An epoch gets
///      `min(choice or cap, cap, scheme.MAX_OPTIONS())`. Pins and the size follow one timing rule:
///      both are read when the epoch's ballot is prepared, so a change applies to the current
///      epoch while its ballot is unprepared (nobody can vote before that) and otherwise from the
///      next epoch. A prepared ballot keeps its size (`ballotSizeFor`) and its option count
///      (`ballotCommitment`), which closing and finalizing use. Smaller ballots cost voters less:
///      the scheme packs three counters per encrypted tally word, so a ballot costs
///      `ceil(size / 3)` word updates and multiples of 3 waste no counter.
///      Anyone may prepare a ballot by supplying the entries and Merkle proofs for exactly those
///      draws (`prepareBallot`); the filler has no choice in what is drawn.
///      Voters do not call the governor: they call
///      `IVotingScheme.castBallot(address(governor), token, epoch, ballot)` on the scheme the epoch
///      was opened with, which calls back `authorizeBallot` so the governor can check eligibility
///      and return the voter's weight. Ballots are accepted only once the epoch is opened (by
///      `prepareBallot` or `openEpoch`), and their option index refers to the ballot order of
///      `BallotPrepared`. The governor stores only a commitment to that ballot
///      (`ballotCommitment`); finalizing an epoch with ballots takes the org ids back. Weight is
///      the voter's lowest vote checkpoint over the hold window
///      `[holdFromFor(token, epoch), snapshotFor(token, epoch)]`, in whole tokens. The snapshot is
///      `snapshotOf(epoch)` (the second before the epoch starts), except in the epoch a token
///      launches in, which predates the token and uses its `launchSnapshotOf` instead. The window
///      is `holdWindow()` (by default the whole previous epoch), so a position held only around
///      the public snapshot carries no weight. A token's launch epoch and the epoch after it start
///      the window at `launchSnapshotOf - min(launchSnapshotDelay, launch epoch end -
///      launchSnapshotOf) / 2` instead, the later half of the launch delay (fixed when the token
///      registered). Ballots are accepted only in the last `votingWindow()` of an epoch
///      (`votingOpensAt`); weights are fixed at the snapshot before the epoch starts, so trading
///      during the epoch's first phase cannot change that epoch's weights. The voter and weight are public; the choice
///      is as private as the scheme makes it.
interface IEpochGovernor {
    /// @notice A pinned cause: catalogue entry `(bucket, index, orgId)` and its Merkle proof
    ///         against the latest catalogue version.
    struct Pin {
        bytes32 orgId;
        uint16 bucket;
        uint32 index;
        bytes32[] proof;
    }

    /// @notice The catalogue entry at a rotation draw's pool index, with its Merkle proof. The
    ///         bucket and index are derived by the governor.
    struct Draw {
        bytes32 orgId;
        bytes32[] proof;
    }

    /// @notice A curated pick (bucket and rank derived by the governor): the pick leaf
    ///         `(rank, catalogIndex, pickOrgId)` with its proof against the agent's picks root, and
    ///         the catalogue entry actually at `(bucket, catalogIndex)` with its catalogue proof
    ///         (ignored when the index is past the bucket). The pick counts only when both orgs match.
    struct CuratedDraw {
        uint32 catalogIndex;
        bytes32 pickOrgId;
        bytes32[] pickProof;
        bytes32 entryOrgId;
        bytes32[] entryProof;
    }

    /// @notice Emitted when a vote is cast. `voteRef` is opaque so private schemes can replace it.
    event VoteCast(address indexed token, uint256 indexed epoch, bytes32 voteRef);

    /// @notice Emitted when an epoch is finalized with its winning cause.
    event EpochFinalized(address indexed token, uint256 indexed epoch, bytes32 causeId);

    /// @notice Emitted when an epoch's poll is opened with its frozen options.
    event EpochOpened(address indexed token, uint256 indexed epoch, bytes32[] options);

    /// @notice Emitted when a token registered in the epoch it was created in gets a launch
    ///         snapshot, at which the weights of that epoch are read.
    event LaunchSnapshotSet(address indexed token, uint256 indexed epoch, uint256 snapshot);

    /// @notice Emitted when an epoch's poll is closed and the tally requested.
    event EpochClosed(address indexed token, uint256 indexed epoch);

    /// @notice Emitted when an epoch with no ballots falls back to the default cause.
    event NoVoteFallbackApplied(address indexed token, uint256 indexed epoch, bytes32 causeId);

    /// @notice Emitted when an epoch with ballots falls back to the default cause because no
    ///         valid final tally arrived within `tallyGrace` after the epoch ended.
    event TallyTimeoutFallbackApplied(
        address indexed token, uint256 indexed epoch, bytes32 causeId
    );

    /// @notice Emitted when closing an epoch could not request the tally from its scheme (for
    ///         example because the scheme no longer lists this governor). `closeEpoch` may be
    ///         retried; otherwise the epoch falls back to the default cause after `tallyGrace`.
    event EpochCloseFailed(address indexed token, uint256 indexed epoch);

    /// @notice Emitted with every token shortlist change: the epoch from which `causes` apply.
    event ShortlistScheduled(
        address indexed token, uint256 indexed effectiveFrom, bytes32[] causes
    );

    /// @notice Emitted when an epoch's ballot is fixed: the options' catalogue org ids in ballot
    ///         order (cause id = `keccak256(orgId)`). `pinned` options come first, then curated
    ///         picks, then the rotation draws. This log is the only record of the org ids: the
    ///         governor keeps `ballotCommitment`, and `finalizeEpoch` of an epoch with ballots takes
    ///         them back. With fewer than `MIN_OPTIONS` options the epoch is not opened and finalizes
    ///         to the default cause.
    event BallotPrepared(
        address indexed token,
        uint256 indexed epoch,
        uint32 catalogVersion,
        uint256 poolSize,
        uint8 pinned,
        bytes32[] orgIds
    );

    event SchemeUpdated(address indexed scheme);
    /// @notice The epoch schedule changed: from epoch `startEpoch` (starting at `startTime`)
    ///         epochs last `length` seconds, ballots are accepted in the last `votingWindow`
    ///         seconds of each, and weights look back `holdWindow` seconds from the snapshot. Takes
    ///         effect from the next epoch, except before the first token registers, when it
    ///         re-anchors epoch zero (`startEpoch` 0).
    event EpochScheduleSet(
        uint256 startEpoch,
        uint256 startTime,
        uint256 length,
        uint256 votingWindow,
        uint256 holdWindow
    );
    /// @notice `tallyGrace` changed (applies immediately).
    event TallyGraceSet(uint256 grace);
    /// @notice `launchSnapshotDelay` changed (applies to tokens registered afterwards).
    event LaunchSnapshotDelaySet(uint256 delay);
    /// @notice `curationGrace` changed.
    event CurationGraceSet(uint256 grace);
    event CuratorRegistrySet(address curators);
    /// @notice No longer emitted (`requestCurationSkip` reverts); kept for indexers.
    event CurationSkipRequested(address indexed token, uint256 indexed epoch, uint256 skipAt);
    /// @notice Curated phase of a ballot: `drawn` picks checked, `included` of them on the ballot.
    event CuratedPicksUsed(
        address indexed token, uint256 indexed epoch, uint8 drawn, uint8 included
    );
    event FactorySet(address indexed factory);
    event DefaultCauseSet(bytes32 indexed causeId);
    event ShortlistSet(address indexed token, bytes32[] causes);
    /// @notice The protocol's largest ballot size changed. Also emitted at deployment.
    event BallotSizeCapSet(uint8 cap);
    /// @notice A token's controller chose its ballot size (zero: follow `ballotSizeCap`), applying
    ///         from epoch `effectiveFrom` (the current one when its ballot is not prepared yet).
    event BallotSizeSet(address indexed token, uint8 size, uint256 effectiveFrom);

    error NotFactory();
    error NotScheme(address caller);
    error NotController(address token, address caller);
    error TokenNotRegistered(address token);
    error EpochNotEnded(uint256 epoch);
    error EpochNotCurrent(uint256 epoch);
    /// @notice A ballot before the epoch's voting window opened at `opensAt`.
    error VotingNotOpen(uint256 epoch, uint256 opensAt);
    /// @notice A duration outside `[min, max]`.
    error DurationOutOfRange(uint256 value, uint256 min, uint256 max);
    error EpochNotOpened(address token, uint256 epoch);
    error EpochAlreadyOpened(address token, uint256 epoch);
    error EpochAlreadyClosed(address token, uint256 epoch);
    error EpochAlreadyFinalized(address token, uint256 epoch);
    error TallyNotFinal(address token, uint256 epoch);
    error InvalidTally(address token, uint256 epoch);
    /// @notice `finalizeEpoch` options do not match the ballot commitment.
    error BallotMismatch(address token, uint256 epoch);
    error InactiveCause(bytes32 causeId);
    error InvalidShortlist();
    error NoShortlist(address token);
    error NotInCatalog(bytes32 orgId);
    error OutOfFocus(bytes32 orgId, uint16 bucket);
    error BallotAlreadyPrepared(address token, uint256 epoch);
    /// @notice The ballot needs more draws than were supplied; `needed` is the next draw index.
    error IncompleteBallot(address token, uint256 epoch, uint256 needed);
    error TooManyDraws(uint256 supplied, uint256 used);
    error InvalidDraw(uint256 k);
    error PoolTooSmall(address token, uint256 poolSize);
    error IncompleteCuratedBallot(address token, uint256 epoch, uint256 needed);
    error TooManyCuratedDraws(uint256 supplied, uint256 used);
    error InvalidCuratedDraw(uint256 k);
    error CuratorRegistryAlreadySet();
    error CurationSkipAlreadyRequested(address token, uint256 epoch);
    /// @notice Published curations can no longer be skipped (`requestCurationSkip`).
    error CurationSkipDisabled(address token, uint256 epoch);
    error InvalidVote();
    error AlreadyVoted(address voter);
    error NoVotes(address token, uint256 epoch);
    error ZeroAddress();
    error FactoryAlreadySet();
    error InsufficientGas();
    /// @notice A ballot size outside `MIN_OPTIONS..MAX_OPTIONS` (zero is allowed for a token).
    error BallotSizeOutOfRange(uint256 size);
    /// @notice More pins than the token's current ballot size holds.
    error ShortlistTooLong(uint256 pins, uint256 size);

    // ------------------------------------------------------------------ constants / config

    /// @notice Shortest value of any owner-set duration (epoch, voting window, hold window,
    ///         graces).
    function MIN_DURATION() external view returns (uint256);

    /// @notice Longest value of any owner-set duration.
    function MAX_DURATION() external view returns (uint256);

    /// @notice Length in seconds of the current epoch (7 days by default). The length of any
    ///         epoch is `epochScheduleFor(epoch)`.
    function epochLength() external view returns (uint256);

    /// @notice Seconds at the end of the current epoch during which ballots are accepted (the
    ///         whole epoch by default). The remaining first part of the epoch is the trading phase.
    function votingWindow() external view returns (uint256);

    /// @notice Length of the hold window ending at the current epoch's snapshot (7 days by
    ///         default).
    function holdWindow() external view returns (uint256);

    /// @notice `(length, votingWindow, holdWindow)` in force for `epoch`. For the epoch after the
    ///         current one this is the schedule that will apply to it, including a pending change.
    function epochScheduleFor(uint256 epoch)
        external
        view
        returns (uint256 length, uint256 votingWindow, uint256 holdWindow);

    /// @notice Timestamp from which ballots of `epoch` are accepted: its end minus its voting
    ///         window. Ballots are accepted until the epoch ends.
    function votingOpensAt(uint256 epoch) external view returns (uint256);

    /// @notice Sets the epoch length, the voting window and the hold window, from the next epoch
    ///         (epochs already started keep their schedule). Before the first token registers it
    ///         applies at once, so the very first cycle can be short. Owner only.
    /// @param length Epoch length, `MIN_DURATION..MAX_DURATION`.
    /// @param votingWindow_ Final part of the epoch that accepts ballots, `MIN_DURATION..length`.
    /// @param holdWindow_ Hold window of the epochs' weights, `MIN_DURATION..MAX_DURATION`.
    function setEpochSchedule(uint256 length, uint256 votingWindow_, uint256 holdWindow_) external;

    /// @notice Sets `tallyGrace`. Owner only; applies at once.
    function setTallyGrace(uint256 grace) external;

    /// @notice Sets `launchSnapshotDelay`. Owner only; applies to tokens registered afterwards.
    function setLaunchSnapshotDelay(uint256 delay) external;

    /// @notice Sets `curationGrace`. Owner only.
    function setCurationGrace(uint256 grace) external;

    /// @notice Hard ceiling of every ballot size (further capped by the scheme's `MAX_OPTIONS`).
    function MAX_OPTIONS() external view returns (uint8);

    /// @notice Smallest ballot that opens a poll; also the smallest focus pool a token may launch
    ///         with.
    function MIN_OPTIONS() external view returns (uint8);

    /// @notice Largest number of causes a controller may pin.
    function PINNED_MAX() external view returns (uint8);

    /// @notice Rotation gives up after `DRAW_FACTOR` draws per free slot (repeats are skipped).
    function DRAW_FACTOR() external view returns (uint256);

    /// @notice Ballot size for epochs prepared now of a token that chose none:
    ///         `min(ballotSizeCap, scheme.MAX_OPTIONS())`. A token's own size is `ballotSizeFor`.
    function ballotSize() external view returns (uint256);

    /// @notice Protocol ballot size cap (`MIN_OPTIONS..MAX_OPTIONS`, owner-set, `MAX_OPTIONS` by
    ///         default). It bounds every token's ballot.
    function ballotSizeCap() external view returns (uint8);

    /// @notice The ballot size `token`'s controller chose (zero: follow `ballotSizeCap`). It may
    ///         exceed the cap, which then applies; the size in force is `ballotSizeFor`.
    function ballotSizeChoiceOf(address token) external view returns (uint8);

    /// @notice Ballot size of `token`'s `epoch`: the size it was prepared with, or for an
    ///         unprepared epoch the size it would get if prepared now,
    ///         `min(choice or ballotSizeCap, ballotSizeCap, scheme.MAX_OPTIONS())`. The ballot may
    ///         hold fewer options (`ballotCommitment`) when the pool is small.
    function ballotSizeFor(address token, uint256 epoch) external view returns (uint256);

    /// @notice Cause catalogue that ballots draw from.
    function catalog() external view returns (address);

    /// @notice Seconds after an epoch ends during which its final tally may still arrive; past
    ///         it, an epoch without a valid final tally finalizes to the default cause.
    function tallyGrace() external view returns (uint256);

    /// @notice Longest wait after a token's registration before its launch snapshot (shorter when
    ///         the launch epoch ends sooner: then halfway to its end).
    function launchSnapshotDelay() external view returns (uint256);

    /// @notice Former grace of `requestCurationSkip`. Kept for compatibility: a ballot with
    ///         usable curator picks now always needs its curated draws. Picks committed but
    ///         never served are dropped by the curator registry owner (`voidCurations`).
    function curationGrace() external view returns (uint256);

    /// @notice Timestamp at which epoch 0 starts.
    function epochZeroStart() external view returns (uint256);

    /// @notice Index of the current epoch.
    function currentEpoch() external view returns (uint256);

    /// @notice Start timestamp of `epoch`.
    function epochStart(uint256 epoch) external view returns (uint256);

    /// @notice Timestamp at which voting weights for `epoch` are read (the second before it starts,
    ///         so before the epoch's trading phase).
    function snapshotOf(uint256 epoch) external view returns (uint256);

    /// @notice Timestamp at which `token`'s voting weights for `epoch` are read: `snapshotOf(epoch)`,
    ///         or the token's launch snapshot in the epoch it launched in.
    function snapshotFor(address token, uint256 epoch) external view returns (uint256);

    /// @notice Launch snapshot of a token created in the epoch it was registered in (zero when the
    ///         token had supply at that epoch's snapshot and uses the regular one).
    function launchSnapshotOf(address token) external view returns (uint256);

    /// @notice Start of `token`'s hold window for `epoch`: weights are the lowest vote checkpoint
    ///         over `[holdFromFor, snapshotFor]`.
    function holdFromFor(address token, uint256 epoch) external view returns (uint256);

    /// @notice Voting scheme used for epochs opened from now on.
    function scheme() external view returns (address);

    /// @notice Cause that wins an epoch in which nobody voted (zero means no fallback).
    function defaultCause() external view returns (bytes32);

    /// @notice The token's pinned causes in effect for the current epoch.
    function shortlistOf(address token) external view returns (bytes32[] memory);
    /// @notice Pinned causes in effect for `epoch`. Exact for the current and later epochs; for a
    ///         prepared epoch its `BallotPrepared` options are authoritative.
    function shortlistFor(address token, uint256 epoch) external view returns (bytes32[] memory);
    /// @notice The token's pinned causes scheduled for a later epoch, and that epoch (zero when
    ///         nothing is scheduled). An empty list with a non-zero epoch schedules removing all pins.
    function pendingShortlistOf(address token)
        external
        view
        returns (bytes32[] memory causes, uint256 effectiveFrom);
    /// @notice Catalogue org ids of the pins in effect for `epoch`.
    function shortlistOrgIdsFor(address token, uint256 epoch)
        external
        view
        returns (bytes32[] memory);
    /// @notice Catalogue version and focus pool size an epoch's ballot draws from (the version in
    ///         effect at the epoch's start).
    function poolOf(address token, uint256 epoch)
        external
        view
        returns (uint32 version, uint256 poolSize);
    /// @notice Pool index of rotation draw `k` (see the contract notes).
    function drawIndex(address token, uint256 epoch, uint32 version, uint256 k, uint256 poolSize)
        external
        pure
        returns (uint256);

    // ------------------------------------------------------------------ admin

    /// @notice Registers a token for voting. Callable by the factory only, after the token's focus
    ///         is set; reverts `PoolTooSmall` unless the latest catalogue gives its focus at least
    ///         `MIN_OPTIONS` entries.
    function registerToken(address token) external;

    /// @notice Sets a token's pinned causes (0..PINNED_MAX distinct, unblocked catalogue entries
    ///         inside its focus, no more than its current ballot size) from the next epoch, or
    ///         from the current one if its ballot is not prepared yet. Callable by the token's
    ///         profile controller only. If the size is lowered later, a ballot takes only the
    ///         first `size` unblocked pins.
    function setShortlist(address token, Pin[] calldata pins) external;

    /// @notice Sets a token's ballot size: `MIN_OPTIONS..MAX_OPTIONS`, or zero to follow
    ///         `ballotSizeCap`. A choice above the cap gets the cap. Applies from the next epoch, or
    ///         from the current one if its ballot is not prepared yet (the pins' rule). Callable by
    ///         the token's profile controller only, like `setShortlist`.
    function setBallotSize(address token, uint8 size) external;

    /// @notice Sets the protocol ballot size cap (`MIN_OPTIONS..MAX_OPTIONS`). Owner only. It
    ///         bounds every token, including those that chose more, from each token's next
    ///         unprepared ballot; prepared ballots keep their size.
    function setBallotSizeCap(uint8 cap) external;

    // ------------------------------------------------------------------ lifecycle

    /// @notice Prepares and opens the current epoch's ballot for `token` (see the contract
    ///         notes). Permissionless. `draws` must be exactly the entries the rotation consumes.
    function prepareBallot(address token, uint256 epoch, Draw[] calldata draws) external;
    /// @notice `prepareBallot` with curated draws: the picks the curated phase consumes, in order,
    ///         then the rotation draws. Needed whenever the token's focus buckets have usable
    ///         curations for the epoch and its catalogue version: `prepareBallot` and `openEpoch`
    ///         (no curated draws) then revert `IncompleteCuratedBallot`, at any time.
    function prepareCuratedBallot(
        address token,
        uint256 epoch,
        CuratedDraw[] calldata curated,
        Draw[] calldata draws
    ) external;
    /// @notice Disabled: always reverts `CurationSkipDisabled`. Published curations cannot be
    ///         skipped; the curator registry owner voids picks nobody can get (`voidCurations`).
    function requestCurationSkip(address token, uint256 epoch) external;
    /// @notice Always 0 (`requestCurationSkip` is disabled). Kept for compatibility.
    function curationSkipAt(address token, uint256 epoch) external view returns (uint256);
    /// @notice Sets the curator registry. Owner only, once.
    function setCuratorRegistry(ICuratorRegistry curators_) external;
    /// @notice `prepareBallot` with no draws: works when the ballot needs none (empty pool, or
    ///         pins fill it). Permissionless. Ballots are rejected until the epoch is opened.
    function openEpoch(address token, uint256 epoch) external;

    /// @notice Closes an ended epoch's poll and asks the scheme for the tally. Permissionless. If
    ///         the scheme rejects the request the epoch is still marked closed (`EpochCloseFailed`)
    ///         and the call may be retried.
    function closeEpoch(address token, uint256 epoch) external;

    /// @notice Stores the winning cause of an ended epoch from the scheme's final tally, or the
    ///         default cause when nobody voted or when no valid final tally arrived within
    ///         `tallyGrace` of the epoch's end. Permissionless. Applying a tally needs the
    ///         ballot's org ids in order (`BallotPrepared`), checked against `ballotCommitment`
    ///         (`BallotMismatch` otherwise); without one they are ignored and may be empty.
    function finalizeEpoch(address token, uint256 epoch, bytes32[] calldata orgIds) external;

    // ------------------------------------------------------------------ epoch views

    /// @notice Whether the epoch's ballot has been prepared.
    function isPrepared(address token, uint256 epoch) external view returns (bool);
    /// @notice Commitment to the epoch's ballot, `keccak256(abi.encodePacked(orgIds))` over the
    ///         options' org ids in ballot order, and the option count (both zero if not prepared).
    ///         The org ids themselves are in `BallotPrepared`.
    function ballotCommitment(address token, uint256 epoch)
        external
        view
        returns (bytes32 commitment, uint8 optionCount);

    /// @notice Scheme the epoch was opened with (zero if not opened).
    function epochScheme(address token, uint256 epoch) external view returns (address);

    function isOpened(address token, uint256 epoch) external view returns (bool);
    function isClosed(address token, uint256 epoch) external view returns (bool);

    /// @notice Whether the last `closeEpoch` attempt failed to request the tally.
    function closeFailed(address token, uint256 epoch) external view returns (bool);

    /// @notice Whether the epoch has been finalized.
    function isFinalized(address token, uint256 epoch) external view returns (bool);

    /// @notice Winning cause of a finalized epoch (zero if not finalized).
    function winningCause(address token, uint256 epoch) external view returns (bytes32);

    /// @notice Final weight counted for a cause in a finalized epoch (zero when the cause was not on
    ///         the ballot or the epoch fell back to the default cause).
    function tally(address token, uint256 epoch, bytes32 causeId) external view returns (uint256);

    /// @notice Whether `voter` cast a ballot in the epoch.
    function hasVoted(address token, uint256 epoch, address voter) external view returns (bool);

    /// @notice Number of ballots authorized in the epoch.
    function voterCount(address token, uint256 epoch) external view returns (uint256);

    /// @notice Voting weight of `account` in `epoch`: its lowest vote checkpoint over
    ///         `[holdFromFor(token, epoch), snapshotFor(token, epoch)]`, in whole tokens (zero
    ///         while the snapshot is still in the future).
    function weightOf(address token, uint256 epoch, address account) external view returns (uint64);

    /// @notice Reads at most `maxReads` more vote checkpoints of `account`'s hold window for
    ///         `epoch` and caches the progress, so a ballot over a window with very many
    ///         checkpoints fits in a block. Anyone may call it; it never changes a weight.
    /// @return done Whether the whole window has been read.
    function advanceHoldScan(address token, uint256 epoch, address account, uint256 maxReads)
        external
        returns (bool done);
}

src/interfaces/IFeeConsolidator.sol

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

import {DonationAsset} from "./IDonationAsset.sol";

/// @title IFeeConsolidator
/// @notice Swaps raw fees (token side and quote side) into the settlement asset (USDC) through
///         Uniswap v4 and hands the proceeds to the fee vault. A failed route never reverts the
///         caller: the raw amount is held and can be retried.
interface IFeeConsolidator {
    /// @notice Emitted when raw fees were swapped and forwarded to the vault.
    /// @param token The launched token the fees belong to.
    /// @param currencyIn The raw fee currency that was swapped.
    /// @param amountIn Raw amount swapped.
    /// @param settlementOut Settlement asset amount forwarded to the vault.
    event FeesConsolidated(
        address indexed token, address indexed currencyIn, uint256 amountIn, uint256 settlementOut
    );

    /// @notice Emitted when a route failed and the raw amount is held for retry.
    /// @param reason Revert data of the failed route (may be empty).
    event ConsolidationFailed(
        address indexed token, address indexed currencyIn, uint256 amountIn, bytes reason
    );

    event MaxSlippageBpsUpdated(uint256 maxSlippageBps);

    /// @notice `amount` WETH from `source` became `usdcOut` USDC (an `Eth` cause pool pushed to
    ///         Endaoment, which takes USDC).
    event DonationConverted(address indexed source, uint256 amount, uint256 usdcOut);

    /// @notice Emitted when a source's ERC-6909 claims were converted into the settlement asset.
    /// @param source The source whose claims were burned.
    /// @param currency The claim currency converted.
    /// @param to Recipient of the settlement asset.
    /// @param amountIn Claims burned.
    /// @param settlementOut Settlement asset paid to `to`.
    event ClaimsConverted(
        address indexed source,
        address indexed currency,
        address indexed to,
        uint256 amountIn,
        uint256 settlementOut
    );

    error NotAuthorized();
    error NothingToConsolidate(address token, address currency);
    error SlippageTooHigh(uint256 amountOut, uint256 minOut);
    error InvalidSlippage(uint256 bps);
    /// @notice `convertClaims` needs the caller's already unlocked pool manager flow.
    error PoolManagerLocked();
    /// @notice A route hop goes through a hooked pool while only hookless hops are allowed.
    error HookedRouteHop(uint256 hop);

    /// @notice Settlement asset all fees are converted to (USDC).
    function settlementAsset() external view returns (address);

    /// @notice Receives raw fees for `token` earned in the current epoch. `amount` of `currency`
    ///         must already be transferred before the call. Must not revert on route failure.
    /// @notice WETH, the on-chain form of the `Eth` donation asset.
    function weth() external view returns (address);

    /// @notice Like `convertClaims` with a chosen donation asset (`convertClaims` is `Usdc`).
    function convertClaimsTo(
        address currency,
        uint256 amount,
        address to,
        bool inSwap,
        DonationAsset da
    ) external returns (uint256 out);

    /// @notice Pulls `amount` WETH from the caller and pays the USDC it converts to to `to`.
    function convertDonation(uint256 amount, address to) external returns (uint256 usdcOut);

    function consolidate(address token, address currency, uint256 amount) external;

    /// @notice Like `consolidate`, for fees earned evenly between `accruedSince` and now (LP fees
    ///         settled from a position). The amount is attributed to the epochs of that interval
    ///         in proportion to the time each epoch covers.
    function consolidateAccrued(
        address token,
        address currency,
        uint256 amount,
        uint256 accruedSince
    ) external;

    /// @notice Retries consolidation of held (previously failed) raw fees.
    /// @return settlementOut Settlement asset forwarded to the vault.
    function retry(address token, address currency) external returns (uint256 settlementOut);

    /// @notice Tries to consolidate every held balance of `token` that has a part earned in
    ///         `epoch` or earlier, so those fees reach their own epoch before it is settled.
    ///         Permissionless; never reverts on a route failure.
    /// @return clear True when nothing earned in `epoch` or earlier is held afterwards.
    function flushThrough(address token, uint256 epoch) external returns (bool clear);

    /// @notice Whether part of the held `currency` of `token` was earned in `epoch` or earlier.
    function heldThrough(address token, address currency, uint256 epoch)
        external
        view
        returns (bool);

    /// @notice Raw fees held unconsolidated for `token` in `currency`.
    function heldFees(address token, address currency) external view returns (uint256);

    /// @notice Converts `amount` ERC-6909 claims of `currency` held by the caller into the
    ///         settlement asset along the quote registry route, under the route-pool guards, and
    ///         pays `to`. Source only, inside the caller's unlocked pool manager flow. The caller
    ///         must have made this contract its ERC-6909 operator. Reverts on any failure.
    /// @param inSwap The conversion runs inside a trader's swap (the live hook's in-line
    ///        conversion): every route hop must be hookless, and the tighter in-swap deviation
    ///        and slippage bounds apply instead of the general ones.
    /// @return settlementOut Settlement asset paid to `to`.
    function convertClaims(address currency, uint256 amount, address to, bool inSwap)
        external
        returns (uint256 settlementOut);

    /// @notice Part of `heldFees(token, currency)` earned in `epoch`.
    function heldFeesIn(address token, address currency, uint256 epoch)
        external
        view
        returns (uint256);

    /// @notice Maximum tolerated slippage versus the guard price, in basis points.
    function maxSlippageBps() external view returns (uint256);
}

src/interfaces/IFeeVault.sol

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

import {DonationAsset} from "./IDonationAsset.sol";
import {IEpochGovernor} from "./IEpochGovernor.sol";

/// @title IFeeVault
/// @notice Receives fees already consolidated into the settlement asset (USDC) and splits them
///         between the platform and a per-token cause pool.
interface IFeeVault {
    /// @notice Emitted once per deposit (one consolidation swap) with its totals. The cause
    ///         amount may be spread over several epochs: see `FeesAttributed`.
    /// @param token The launched token the fees belong to.
    /// @param platformAmount Amount credited to the platform.
    /// @param causeAmount Amount credited to the token's cause pool.
    /// @param currency The settlement asset the amounts are denominated in.
    event FeesCollected(
        address indexed token, uint256 platformAmount, uint256 causeAmount, address currency
    );

    /// @notice Emitted for every part of a deposit: the epoch whose cause pool received
    ///         `causeAmount`. The parts of one deposit sum to its `FeesCollected.causeAmount`.
    /// @param epoch The epoch credited (the accrual epoch, or the first unsettled one after it).
    /// @param accrualEpoch The epoch in which the fees were earned.
    event FeesAttributed(
        address indexed token, uint256 indexed epoch, uint256 accrualEpoch, uint256 causeAmount
    );

    /// @notice Emitted when a cause pool is moved to the distributor.
    event Settled(address indexed token, uint256 indexed epoch, address currency, uint256 amount);

    /// @notice Emitted when the platform withdraws accrued fees.
    event PlatformWithdrawn(address indexed currency, address indexed to, uint256 amount);

    error NotAuthorized();
    error EpochNotFinalized(address token, uint256 epoch);
    error AlreadySettled(address token, uint256 epoch);
    error TokenNotRegistered(address token);
    error FutureEpoch(uint256 epoch, uint256 current);
    /// @notice Fees earned in or before `epoch` are still outside the vault (uncollected LP fees
    ///         or held fees whose route fails) and `settleGrace` has not passed.
    error FeesPending(address token, uint256 epoch);

    /// @notice Platform share of fees in basis points (single source of the split).
    function PLATFORM_SHARE_BPS() external view returns (uint256);

    /// @notice Time after an epoch's end during which it cannot be settled while fees earned in
    ///         it are still outstanding; afterwards such fees go to a later epoch.
    function settleGrace() external view returns (uint256);

    /// @notice The settlement asset (USDC) held by the vault.
    function settlementAsset() external view returns (address);

    /// @notice Registers a token. Callable by the factory only.
    function registerToken(address token) external;

    /// @notice Registers `token` with a donation asset (`registerToken(token)` is `Usdc`).
    function registerToken(address token, DonationAsset asset) external;

    /// @notice The asset the cause pool of `token` is kept and settled in.
    function donationAssetOf(address token) external view returns (DonationAsset);

    /// @notice WETH (zero until a consolidator that knows it is set).
    function weth() external view returns (address);

    /// @notice The consolidator allowed to deposit.
    function consolidator() external view returns (address);

    /// @notice Splits and records the settlement asset already transferred to the vault, given
    ///         as parts by the epoch in which they were earned. Callable by the fee consolidator
    ///         only.
    /// @dev Each part's cause share is credited to its accrual epoch, so the time of collection
    ///      does not choose the epoch. If that epoch is already settled, the share goes to the
    ///      first unsettled epoch after it. Emits one `FeesCollected` with the totals and one
    ///      `FeesAttributed` per non-zero part.
    /// @param accrualEpochs Epoch in which each part was earned; at most the current epoch.
    /// @param amounts Settlement asset amount of each part.
    function depositFees(
        address token,
        uint256[] calldata accrualEpochs,
        uint256[] calldata amounts
    ) external;

    /// @notice The governor whose epochs the vault settles against.
    function governor() external view returns (IEpochGovernor);

    /// @notice Platform balance accrued in the settlement asset.
    function platformAccrued() external view returns (uint256);

    /// @notice Cause pool balance of `token` in the settlement asset.
    function causePool(address token) external view returns (uint256);

    /// @notice Moves the cause pool of `token` to the distributor once `epoch` has a winner,
    ///         after bringing in the fees still outstanding for it (LP fees, held fees).
    ///         Reverts with `FeesPending` while those cannot be brought in, until `settleGrace`
    ///         after the epoch's end.
    function settle(address token, uint256 epoch) external;

    /// @notice Withdraws accrued platform fees to the platform treasury.
    function withdrawPlatform() external;
}

src/interfaces/IQuoteRegistry.sol

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

import {DonationAsset} from "./IDonationAsset.sol";

/// @title IQuoteRegistry
/// @notice Allowlist of assets a token's pool may be paired against (any ERC-20 with a route to USDC; `Kind` is only a label).
interface IQuoteRegistry {
    /// @notice Classification of a quote asset.
    enum Kind {
        Native, // WETH and every other non-Ondo crypto asset (a label only; nothing branches on it)
        Ondo // Ondo tokenized asset on Ethereum mainnet
    }

    /// @notice A registered quote asset.
    struct QuoteAsset {
        uint8 decimals;
        Kind kind;
        bool active;
    }

    event QuoteAssetAdded(address indexed asset, uint8 decimals, Kind kind);
    event QuoteAssetDeactivated(address indexed asset);
    event QuoteAssetReactivated(address indexed asset);

    error QuoteAssetAlreadyExists(address asset);
    error QuoteAssetNotFound(address asset);
    error ZeroAddress();

    /// @notice Adds a quote asset; decimals are read from the token by the implementation.
    function addQuoteAsset(address asset, Kind kind) external;

    /// @notice Disables new launches against `asset`; existing pools are unaffected.
    function deactivateQuoteAsset(address asset) external;

    /// @notice Re-enables a previously deactivated asset.
    function reactivateQuoteAsset(address asset) external;

    /// @notice Returns the registered data for `asset` (zeroed if unknown).
    function getQuoteAsset(address asset) external view returns (QuoteAsset memory);

    /// @notice Whether `asset` is registered and active.
    function isAllowed(address asset) external view returns (bool);

    /// @notice Whether a route from `asset` into the donation asset exists (for WETH and `Eth`
    ///         the route is empty by definition: it already is the donation asset).
    function hasRouteTo(address asset, DonationAsset donationAsset) external view returns (bool);

    /// @notice The token a donation asset is held as: the settlement asset (USDC) or WETH.
    function donationToken(DonationAsset donationAsset) external view returns (address);

    /// @notice Number of quote assets ever added.
    function quoteAssetCount() external view returns (uint256);

    /// @notice Quote asset at `index` in insertion order.
    function quoteAssetAt(uint256 index) external view returns (address);
}

src/interfaces/external/IUniswapV3.sol

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

/// @dev The parts of Uniswap v3 core the fee consolidator uses.
interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}

interface IUniswapV3Pool {
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

interface IUniswapV3SwapCallback {
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data)
        external;
}

src/libraries/V3RouteLib.sol

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

import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";

/// @title V3RouteLib
/// @notice Encoding of a Uniswap v3 pool as a route hop, without changing the `PoolKey[]` shape of
///         registry routes.
/// @dev A v3 hop is a `PoolKey` with `tickSpacing == 0`, `hooks == address(0)`, `currency0 <
///      currency1` (both ERC-20, never native ETH) and `fee` one of the four v3 tiers. Uniswap v4
///      rejects a tick spacing of zero, so no real v4 pool can collide with the encoding, and the
///      pool id (`keccak256(abi.encode(key))`) of a v3 hop is only ever used as the key of the
///      consolidator's reference table.
library V3RouteLib {
    /// @dev The marker: no v4 pool has this tick spacing.
    int24 internal constant TICK_SPACING = 0;

    /// @notice Whether `key` encodes a v3 hop (shape marker only; see `isValidV3`).
    function isV3(PoolKey memory key) internal pure returns (bool) {
        return key.tickSpacing == TICK_SPACING;
    }

    /// @notice Whether `fee` is one of the four Uniswap v3 fee tiers.
    function isFeeTier(uint24 fee) internal pure returns (bool) {
        return fee == 100 || fee == 500 || fee == 3000 || fee == 10_000;
    }

    /// @notice Whether `key` is a well formed v3 hop: marker, no hooks, sorted ERC-20 pair, tier.
    function isValidV3(PoolKey memory key) internal pure returns (bool) {
        address c0 = Currency.unwrap(key.currency0);
        address c1 = Currency.unwrap(key.currency1);
        return key.tickSpacing == TICK_SPACING && address(key.hooks) == address(0)
            && c0 != address(0) && c0 < c1 && isFeeTier(key.fee);
    }

    /// @notice The hop for the v3 pool of `(a, b, fee)` (the order of `a` and `b` does not matter).
    function hop(address a, address b, uint24 fee) internal pure returns (PoolKey memory key) {
        (address c0, address c1) = a < b ? (a, b) : (b, a);
        key = PoolKey(Currency.wrap(c0), Currency.wrap(c1), fee, TICK_SPACING, IHooks(address(0)));
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@fhevm/solidity/=node_modules/@fhevm/solidity/",
    "encrypted-types/=node_modules/encrypted-types/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.