Skip to content
Verified contractPartialMIT

FeeEscrow

Address0xd992f465d55b005e8d2aff9fce977cb78f5652e0
Balance

0.054384 ETH

 

Transactions

33

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 777 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,953,585
Creation transaction
0x38fec68e8e…3a2fe0adc7

src/contracts/escrows/FeeEscrow.sol

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

import {Ownable} from '@solady/auth/Ownable.sol';

import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';

import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';

import {PairedTokenLib} from '@flaunch/libraries/PairedTokenLib.sol';

import {IFeeEscrow} from '@flaunch-interfaces/IFeeEscrow.sol';
import {IIndexerSubscriber} from '@flaunch-interfaces/IIndexerSubscriber.sol';
import {IPairedTokenRegistry} from '@flaunch-interfaces/IPairedTokenRegistry.sol';

/**
 * Escrow contract that receives fees from multiple PositionManagers, allowing each recipient to
 * withdraw them in a single transaction.
 *
 * A single instance escrows EVERY paired token: the token is named per allocation and balances
 * are held per (recipient, token). Deposits are self-securing regardless of the caller — a
 * native allocation must deliver its exact `msg.value`, and an ERC20 allocation is pulled from
 * the caller with the full amount moving or the transfer reverting (every approved paired token
 * is 1:1 by policy; nothing here measures for one that is not) — and balances are booked per
 * token, so one token's books can never be settled out of another token's holdings.
 *
 * That argument covers the DEPOSIT path only: the withdrawal path crosses tokens by
 * construction, because unwrapping a wrapper debits the balance of one asset and delivers a
 * DIFFERENT one. CEI is respected on the ledger — {_withdrawFees} zeroes the balance before
 * paying out — and the 1:1 delivery itself is a registry admission guarantee, not a runtime
 * assertion: {PairedTokenRegistry.approvePairedToken} only admits direct tokens and wrappers
 * that unwrap 1:1, and {PairedTokenLib.payout} quotes the debited amount without measuring
 * what the wrapper actually delivered.
 */
contract FeeEscrow is IFeeEscrow, Ownable {
    /// The paired-token registry used to resolve each token's unwrap policy on withdrawal.
    /// A constructor binding: an unwired (registry-less) escrow state is unconstructible, so no
    /// legacy fallback path exists.
    IPairedTokenRegistry public immutable pairedTokenRegistry;

    /// The {IndexerSubscriber} subscriber
    IIndexerSubscriber public indexer;

    /// Maps a user to the balance available to claim, per escrowed token
    mapping(address _recipient => mapping(address _token => uint _amount)) public balances;

    /// Maps the total fees that a PoolId has accrued, per escrowed token. The token key is
    /// load-bearing: `allocateFees` is permissionless, so a pool-only figure could be inflated
    /// for free with a worthless self-minted token. Keyed per token, junk lands under its own
    /// token and is invisible to any consumer reading the pool's actual paired token.
    mapping(PoolId _poolId => mapping(address _token => uint _amount)) public totalFeesAllocated;

    /**
     * Constructor to initialize the registry binding and the indexer.
     *
     * @param _pairedTokenRegistry The {PairedTokenRegistry} resolving unwrap policies
     * @param _indexer The {IndexerSubscriber} contract address
     */
    constructor(
        address _pairedTokenRegistry,
        address _indexer
    ) {
        if (_pairedTokenRegistry == address(0)) {
            revert RegistryZeroAddress();
        }
        if (_indexer == address(0)) {
            revert IndexerZeroAddress();
        }

        pairedTokenRegistry = IPairedTokenRegistry(_pairedTokenRegistry);
        indexer = IIndexerSubscriber(_indexer);

        _initializeOwner(msg.sender);
    }

    /**
     * Allows a deposit to be made against a user. The amount is stored within the
     * escrow contract to be claimed later.
     *
     * @param _poolId The PoolId that the deposit came from
     * @param _token The token being escrowed (`address(0)` for raw native ETH)
     * @param _recipient The recipient of the transferred token
     * @param _amount The amount of the token to be transferred
     */
    function allocateFees(
        PoolId _poolId,
        address _token,
        address _recipient,
        uint _amount
    ) external payable {
        // If we don't have fees to allocate, exit early. A native caller must not send value on
        // a no-op, or it would be trapped here.
        if (_amount == 0) {
            if (msg.value != 0) revert IncorrectNativeDeposit();
            return;
        }

        // Ensure we aren't trying to allocate fees to a zero address
        if (_recipient == address(0)) {
            revert RecipientZeroAddress();
        }

        // Secure the funds BEFORE any balance is credited. `_token` is caller-supplied, so the
        // pull below can execute arbitrary token code; crediting first would let a reentrant
        // token withdraw against a credit whose backing has not yet arrived.
        if (_token == address(0)) {
            // Native-ETH allocation: the fee arrives as `msg.value` with this call.
            if (msg.value != _amount) revert IncorrectNativeDeposit();
        } else {
            // ERC20 allocation: pull the fee from the caller; reject stray ETH. The recipient's
            // balance is credited with `_amount` below, which matches the holdings because every
            // approved paired token is 1:1 by policy: the pull moves the full amount or reverts
            // inside `safeTransferFrom`. The credited-delta check that used to assert this went
            // with the rest of the non-1:1 handling — a non-1:1 token would now quietly under-back
            // its own (recipient, token) key, and `approvePairedToken` is the gate that keeps such
            // a token out of every value-bearing flow.
            if (msg.value != 0) revert IncorrectNativeDeposit();
            PairedTokenLib.pullFrom(Currency.wrap(_token), msg.sender, _amount, 0);
        }

        // Increase the balance available for the recipient to claim
        balances[_recipient][_token] += _amount;

        // Increase the fee tracking for the PoolId, only if the recipient matches the PoolId
        // that has also been passed in. This will prevent users from being misallocated and
        // external contracts that depend on this figure from being misinformed.
        (address flaunch,,, uint tokenId) = indexer.poolIndex(_poolId);
        if (tokenId != 0 && IERC721(flaunch).ownerOf(tokenId) == _recipient) {
            totalFeesAllocated[_poolId][_token] += _amount;
        }

        emit Deposit(_poolId, _recipient, _token, _amount);
    }

    /**
     * Allows fees to be withdrawn from an escrowed fee position in a single token.
     *
     * @param _token The escrowed token to withdraw (`address(0)` for raw native ETH)
     * @param _recipient The recipient of the holder's withdraw
     * @param _unwrap If we want to unwrap the balance into the escrow token's underlying
     * asset (ETH for flETH, USDC for flUSDC)
     */
    function withdrawFees(
        address _token,
        address _recipient,
        bool _unwrap
    ) public {
        _withdrawFees(_token, _recipient, _unwrap);
    }

    /**
     * Allows fees to be withdrawn across multiple escrowed tokens in a single transaction.
     *
     * @dev Duplicate or zero-balance entries are harmless no-ops: each token's balance is zeroed
     * before its payout, so a repeated entry finds nothing left to claim.
     *
     * @param _tokens The escrowed tokens to withdraw (`address(0)` for raw native ETH)
     * @param _recipient The recipient of the holder's withdraws
     * @param _unwrap If we want to unwrap each balance into its token's underlying asset
     */
    function withdrawFees(
        address[] calldata _tokens,
        address _recipient,
        bool _unwrap
    ) external {
        for (uint i; i < _tokens.length; ++i) {
            _withdrawFees(_tokens[i], _recipient, _unwrap);
        }
    }

    /**
     * Withdraws the sender's full balance of a single escrowed token.
     *
     * @param _token The escrowed token to withdraw
     * @param _recipient The recipient of the withdraw
     * @param _unwrap If the balance should be unwrapped via the registry's policy
     */
    function _withdrawFees(
        address _token,
        address _recipient,
        bool _unwrap
    ) internal {
        // Get the amount of the token that is stored in escrow
        uint amount = balances[msg.sender][_token];

        // If there are no fees to withdraw, exit early
        if (amount == 0) {
            return;
        }

        // Reset our user's balance to prevent reentry
        balances[msg.sender][_token] = 0;

        if (_unwrap) {
            // Unwrap the token to its underlying asset (ETH for flETH, USDC for flUSDC) via the
            // registry's policy. The event carries both the escrow-token KEY (the balance that was
            // zeroed) and the delivered asset: {payoutAsset} mirrors the payout dispatch exactly,
            // so the latter always names what was actually delivered — including a plain or
            // never-registered ERC20 forwarded as-is, which is labelled with the token itself
            // rather than the native-ETH marker.
            IPairedTokenRegistry.PairedToken memory cfg = pairedTokenRegistry.tokenConfig(_token);
            PairedTokenLib.payout(cfg, _token, _recipient, amount);
            emit Withdrawal(msg.sender, _recipient, _token, PairedTokenLib.payoutAsset(cfg, _token), amount);
        }
        // Transfer the token without unwrapping. The library's uniform send handles an ERC20 and
        // raw native ETH (`_token == address(0)`) alike.
        else {
            PairedTokenLib.pay(Currency.wrap(_token), _recipient, amount);
            emit Withdrawal(msg.sender, _recipient, _token, _token, amount);
        }
    }

    /**
     * Allows the owner to update the {IndexerSubscriber}.
     *
     * @param _indexer The new {IndexerSubscriber} contract address
     */
    function setIndexer(
        address _indexer
    ) public onlyOwner {
        if (_indexer == address(0)) {
            revert IndexerZeroAddress();
        }

        indexer = IIndexerSubscriber(_indexer);
    }

    /**
     * Allows the contract to receive ETH: transiently when a native wrapper (e.g. flETH) is
     * unwrapped during a withdraw, and durably for raw native-ETH allocations, which the escrow
     * holds directly.
     */
    receive() external payable {}
}

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

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/solady/src/auth/Ownable.sol

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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

lib/solady/src/utils/SafeTransferLib.sol

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount :=
                mul( // The arguments of `mul` are evaluated from right to left.
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
            mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

lib/v4-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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-hooks-public/lib/v4-periphery/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/contracts/libraries/PairedTokenLib.sol

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

import {SafeTransferLib} from '@solady/utils/SafeTransferLib.sol';

import {Currency, CurrencyLibrary} from '@uniswap/v4-core/src/types/Currency.sol';

import {IPairedTokenRegistry} from '@flaunch-interfaces/IPairedTokenRegistry.sol';
import {IWrappedToken} from '@flaunch-interfaces/IWrappedToken.sol';

/**
 * The standardised movement library for paired tokens: one home for pulling, paying,
 * wrapping, unwrapping, allowances and refunds across every paired-token shape (raw native
 * ETH, native wrappers, ERC20 wrappers and plain ERC20s), so shape-conditional branches do
 * not proliferate across the escrows, hooks and treasury actions. Keeping this logic in an
 * internal library also keeps it off the near-EIP-170-limit hooks.
 *
 * The caller must hold `_amount` of the wrapped token before calling {payout}.
 */
library PairedTokenLib {
    using CurrencyLibrary for Currency;

    /// Thrown when a treasury action is asked to settle more of a native paired leg than the
    /// {MemecoinTreasury} actually forwarded as call value.
    error InsufficientNativeValue();

    /**
     * The calling contract's own balance of `_currency`, excluding native ETH that arrived as
     * `msg.value` in the current call.
     *
     * @dev Treasury actions bracket their work with a before/after balance delta so they forward
     * back only what THIS call moved, never a residual belonging to another pool. A native paired
     * leg breaks that pattern, because `msg.value` is already credited to `address(this).balance`
     * before the function body runs: an unadjusted "before" snapshot would make the unspent ETH
     * look like a decrease, and it would be stranded rather than refunded. Subtracting the
     * forwarded value restores the invariant, so the same `after > before` refund works for both
     * an ERC20 and a native leg.
     *
     * @param _currency The currency to read
     * @param _value The native value forwarded into the current call (`msg.value`)
     *
     * @return balance_ The balance held prior to the forwarded value
     */
    function balanceExcludingValue(
        Currency _currency,
        uint _value
    ) internal view returns (uint balance_) {
        balance_ = _currency.balanceOfSelf();
        if (_currency.isAddressZero()) {
            balance_ -= _value;
        }
    }

    /**
     * Pulls `_amount` of `_currency` into the calling contract from `_payer`.
     *
     * @dev Every paired token is either a direct token or a wrapper that unwraps 1:1, so an ERC20
     * pull either moves `_amount` or reverts inside `safeTransferFrom` — there is no partial
     * outcome to measure. This used to bracket the transfer with a balance snapshot and report the
     * delta, and a `pullFromExact` variant reverted when that delta came up short; both existed
     * only for fee-on-transfer tokens, which the protocol does not admit.
     *
     * A native leg follows push semantics — the value must already have been forwarded as
     * `msg.value` (it cannot be approved or pulled), so all this asserts is that the forwarded
     * value covers the request. That check is about the CALLER's funding, not the token's
     * behaviour, so it stays.
     *
     * @param _currency The currency to pull
     * @param _payer The address to pull an ERC20 leg from
     * @param _amount The amount requested
     * @param _value The native value forwarded into the current call (`msg.value`)
     */
    function pullFrom(
        Currency _currency,
        address _payer,
        uint _amount,
        uint _value
    ) internal {
        if (_amount == 0) {
            return;
        }

        if (_currency.isAddressZero()) {
            if (_value < _amount) {
                revert InsufficientNativeValue();
            }
            return;
        }

        SafeTransferLib.safeTransferFrom(Currency.unwrap(_currency), _payer, address(this), _amount);
    }

    /**
     * Pulls `_amount` of `_currency` into the calling contract from `_payer`, reporting the amount
     * actually credited.
     *
     * @dev For an ARBITRARY token only. An imported memecoin is never screened for transfer fees,
     * so a pool can legitimately exist whose memecoin takes a cut on every transfer, and quoting
     * the requested amount would settle the shortfall out of balances held for OTHER pools.
     *
     * Paired tokens do NOT belong here: they are 1:1 by policy and use {pullFrom}, which does not
     * pay for a measurement that can never differ.
     *
     * @param _currency The currency to pull
     * @param _payer The address to pull from
     * @param _amount The amount requested
     * @param _value The native value forwarded into the current call (`msg.value`)
     *
     * @return credited_ The amount actually credited to the caller
     */
    function pullFromMeasured(
        Currency _currency,
        address _payer,
        uint _amount,
        uint _value
    ) internal returns (uint credited_) {
        if (_amount == 0) {
            return 0;
        }

        if (_currency.isAddressZero()) {
            if (_value < _amount) {
                revert InsufficientNativeValue();
            }
            return _amount;
        }

        uint balanceBefore = _currency.balanceOfSelf();
        SafeTransferLib.safeTransferFrom(Currency.unwrap(_currency), _payer, address(this), _amount);
        credited_ = _currency.balanceOfSelf() - balanceBefore;
    }

    /**
     * Pays `_amount` of the paired token `_token` to `_recipient`, applying the token's unwrap
     * policy from the registry:
     *
     * - native wrapper (flETH): unwrap to ETH and forward raw ETH.
     * - ERC20 wrapper (flUSDC): unwrap to the `underlying` ERC20 (USDC) and forward it.
     * - anything else (plain ERC20, raw native ETH, unregistered token): forward as-is.
     *
     * The unwrap is unconditional policy dispatch: the registry decides what each token unwraps
     * to, and a caller that wants to forward a token untouched uses {pay} instead.
     *
     * @dev Every registerable wrapper wraps 1:1 -- a native wrapper against ETH, and an ERC20
     * wrapper against an underlying whose decimals the registry pins equal to its own -- so the
     * unwrapped amount IS `_amount`. This used to bracket the withdraw with a balance snapshot and
     * forward the measured delta instead, purely to stay safe for a wrapper that was not 1:1. That
     * is not a shape the protocol admits, so the measurement bought nothing and cost two
     * `balanceOf` calls on every unwrapping payout.
     *
     * @param _registry The {PairedTokenRegistry} holding each token's unwrap policy
     * @param _token The wrapped paired token held by the caller
     * @param _recipient The recipient of the payout
     * @param _amount The amount of the wrapped token to pay out
     */
    function payout(
        IPairedTokenRegistry _registry,
        address _token,
        address _recipient,
        uint _amount
    ) internal {
        if (_amount == 0) {
            return;
        }

        payout(_registry.tokenConfig(_token), _token, _recipient, _amount);
    }

    /**
     * {payout} against an already-fetched registry config, for callers that also need
     * {payoutAsset} and would otherwise pay for the same `tokenConfig` call twice.
     *
     * @param cfg The registry config of `_token`
     * @param _token The wrapped paired token held by the caller
     * @param _recipient The recipient of the payout
     * @param _amount The amount of the wrapped token to pay out
     */
    function payout(
        IPairedTokenRegistry.PairedToken memory cfg,
        address _token,
        address _recipient,
        uint _amount
    ) internal {
        if (_amount == 0) {
            return;
        }

        // Native-ETH wrapper (flETH): unwrap and forward the ETH. A registered wrapper unwraps
        // 1:1, so the withdraw delivers exactly `_amount` and there is nothing to measure.
        if (cfg.tokenType == IPairedTokenRegistry.PairedTokenType.NativeWrapper) {
            IWrappedToken(_token).withdraw(_amount);
            CurrencyLibrary.ADDRESS_ZERO.transfer(_recipient, _amount);
            return;
        }

        // ERC20-backed wrapper (flUSDC): unwrap to the underlying token (USDC) and forward it. The
        // registry pins `wrapper.decimals() == underlying.decimals()`, so the unwrap is 1:1 and
        // the amount delivered is exactly `_amount`.
        if (cfg.tokenType == IPairedTokenRegistry.PairedTokenType.Erc20Wrapper && cfg.underlying != address(0)) {
            IWrappedToken(_token).withdraw(_amount);
            Currency.wrap(cfg.underlying).transfer(_recipient, _amount);
            return;
        }

        // Unregistered / non-wrapper token (e.g. a memecoin referral fee), a plain ERC20 or raw
        // native ETH: forward as-is via the uniform currency transfer.
        Currency.wrap(_token).transfer(_recipient, _amount);
    }

    /**
     * The asset a {payout} of `_token` would actually deliver. The single source of truth for
     * every consumer that needs to KNOW the delivered asset (event fields, claim gating)
     * without moving it — mirroring {payout}'s dispatch exactly, so the two can never diverge.
     *
     * @param _registry The {PairedTokenRegistry} holding each token's unwrap policy
     * @param _token The paired token being paid out
     *
     * @return asset_ The asset the recipient would receive (`address(0)` = native ETH)
     */
    function payoutAsset(
        IPairedTokenRegistry _registry,
        address _token
    ) internal view returns (address asset_) {
        return payoutAsset(_registry.tokenConfig(_token), _token);
    }

    /**
     * {payoutAsset} against an already-fetched registry config.
     *
     * @param cfg The registry config of `_token`
     * @param _token The paired token being paid out
     *
     * @return asset_ The asset the recipient would receive (`address(0)` = native ETH)
     */
    function payoutAsset(
        IPairedTokenRegistry.PairedToken memory cfg,
        address _token
    ) internal pure returns (address asset_) {
        if (cfg.tokenType == IPairedTokenRegistry.PairedTokenType.NativeWrapper) {
            return address(0);
        }

        if (cfg.tokenType == IPairedTokenRegistry.PairedTokenType.Erc20Wrapper && cfg.underlying != address(0)) {
            return cfg.underlying;
        }

        return _token;
    }

    /**
     * Whether a paired token of this shape is funded from ETH at launch (settled from
     * `msg.value`, wrapping if needed) rather than pulled from the payer with an allowance.
     * The single source of dispatch truth for the premine funding mode, shared by
     * {FlaunchLibrary} and {FlaunchZap} so they can never disagree.
     *
     * @param _tokenType The paired token's shape
     *
     * @return True for raw native ETH and native wrappers; false for every ERC20 shape
     */
    function isEthFunded(
        IPairedTokenRegistry.PairedTokenType _tokenType
    ) internal pure returns (bool) {
        return _tokenType == IPairedTokenRegistry.PairedTokenType.NativeEth
            || _tokenType == IPairedTokenRegistry.PairedTokenType.NativeWrapper;
    }

    /**
     * Pays `_amount` of `_currency` to `_recipient` with no unwrap — the uniform send for
     * native ETH and any ERC20. Reverts on failure; use {tryPay} for hostile recipients.
     *
     * @param _currency The currency to pay
     * @param _recipient The recipient of the payment
     * @param _amount The amount to pay
     */
    function pay(
        Currency _currency,
        address _recipient,
        uint _amount
    ) internal {
        if (_amount == 0) {
            return;
        }

        _currency.transfer(_recipient, _amount);
    }

    /**
     * Best-effort, gas-capped, non-reverting payment for recipients that may be hostile (a
     * reverting `receive()`, a gas-griefing fallback). The caller decides what to do with a
     * failed payment (escrow it, skip it) — funds are never lost, just not delivered.
     *
     * @param _currency The currency to pay
     * @param _recipient The recipient of the payment
     * @param _amount The amount to pay
     * @param _gasCap The maximum gas forwarded to the recipient / token call
     *
     * @return success_ Whether the payment was delivered
     */
    function tryPay(
        Currency _currency,
        address _recipient,
        uint _amount,
        uint _gasCap
    ) internal returns (bool success_) {
        if (_amount == 0) {
            return true;
        }

        if (_currency.isAddressZero()) {
            assembly ("memory-safe") {
                success_ := call(_gasCap, _recipient, _amount, 0, 0, 0, 0)
            }
            return success_;
        }

        // A codeless token cannot deliver anything; the raw call below would report success
        address token = Currency.unwrap(_currency);
        if (token.code.length == 0) {
            return false;
        }

        (bool ok, bytes memory data) = token.call{gas: _gasCap}(
            abi.encodeWithSignature('transfer(address,uint256)', _recipient, _amount)
        );
        return ok && (data.length == 0 || abi.decode(data, (bool)));
    }

    /**
     * Wraps `_ethValue` of the caller's ETH into `_wrapper`.
     *
     * @dev A registered wrapper wraps 1:1, so the caller is credited exactly `_ethValue`. The
     * balance snapshot this used to take existed only for a fee-charging wrapper.
     *
     * @param _wrapper The native wrapper (e.g. flETH) to deposit into
     * @param _ethValue The ETH value to wrap
     */
    function wrap(
        address _wrapper,
        uint _ethValue
    ) internal {
        IWrappedToken(_wrapper).deposit{value: _ethValue}(0);
    }

    /**
     * Refunds the caller's `_currency` balance above `_balanceBefore` to `_recipient` — the
     * "snapshot / act / refund the delta" bracket used by swaps, premines and treasury
     * actions, expressed once.
     *
     * @param _currency The currency to refund
     * @param _balanceBefore The balance snapshot taken before acting (see {balanceExcludingValue})
     * @param _recipient The recipient of the refund
     *
     * @return refunded_ The amount refunded
     */
    function refundUnspentValue(
        Currency _currency,
        uint _balanceBefore,
        address _recipient
    ) internal returns (uint refunded_) {
        uint balance = _currency.balanceOfSelf();
        if (balance > _balanceBefore) {
            refunded_ = balance - _balanceBefore;
            _currency.transfer(_recipient, refunded_);
        }
    }

    /**
     * Grants `_spender` an allowance of `_amount` over the caller's `_token`, tolerating
     * non-standard ERC20s (USDT-style approval resets). A no-op for native ETH, which has no
     * allowance concept.
     *
     * @param _token The token to approve (`address(0)` = native ETH, no-op)
     * @param _spender The spender to approve
     * @param _amount The allowance to grant
     */
    function ensureAllowance(
        address _token,
        address _spender,
        uint _amount
    ) internal {
        if (_token == address(0)) {
            return;
        }

        SafeTransferLib.safeApproveWithRetry(_token, _spender, _amount);
    }

    /**
     * Clears `_spender`'s allowance over the caller's `_token`. A no-op for native ETH.
     *
     * @param _token The token to revoke (`address(0)` = native ETH, no-op)
     * @param _spender The spender to revoke
     */
    function revokeAllowance(
        address _token,
        address _spender
    ) internal {
        if (_token == address(0)) {
            return;
        }

        SafeTransferLib.safeApprove(_token, _spender, 0);
    }
}

src/interfaces/IFeeEscrow.sol

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

import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';

import {IPairedTokenRegistry} from '@flaunch-interfaces/IPairedTokenRegistry.sol';

interface IFeeEscrow {
    error RecipientZeroAddress();

    /// Thrown when the ETH sent with `allocateFees` does not match the amount for a native-ETH
    /// allocation (or when ETH is sent with an ERC20 allocation / a zero-amount allocation)
    error IncorrectNativeDeposit();

    /// Thrown when the escrow is constructed without a {PairedTokenRegistry}
    error RegistryZeroAddress();

    /// Thrown when the escrow is constructed with, or repointed at, a zero indexer — every
    /// allocation reads `indexer.poolIndex`, so a zero indexer would brick fee distribution
    error IndexerZeroAddress();

    event Deposit(PoolId indexed _poolId, address _payee, address _token, uint _amount);

    /// Emitted once per escrowed token withdrawn. `_token` is the escrow-token KEY (the mirror of
    /// {Deposit._token}; `address(0)` = raw native ETH) — indexers attribute the zeroed balance by
    /// it exactly. `_deliveredAsset` is what was actually transferred: the registry's payout asset
    /// under an unwrap (ETH for flETH, USDC for flUSDC), or `_token` itself on the raw path.
    /// Already-deployed legacy escrows emit the pre-singleton 4-param shape without the key.
    event Withdrawal(address _sender, address _recipient, address _token, address _deliveredAsset, uint _amount);

    function pairedTokenRegistry() external view returns (IPairedTokenRegistry pairedTokenRegistry_);

    function balances(
        address _recipient,
        address _token
    ) external view returns (uint amount_);

    function totalFeesAllocated(
        PoolId _poolId,
        address _token
    ) external view returns (uint amount_);

    function allocateFees(
        PoolId _poolId,
        address _token,
        address _recipient,
        uint _amount
    ) external payable;

    function withdrawFees(
        address _token,
        address _recipient,
        bool _unwrap
    ) external;

    function withdrawFees(
        address[] calldata _tokens,
        address _recipient,
        bool _unwrap
    ) external;

    function setIndexer(
        address _indexer
    ) external;
}

src/interfaces/IIndexerSubscriber.sol

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

import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';

interface IIndexerSubscriber {
    error FlaunchNotVerified(address _flaunch);
    error InvalidTokenId(address _flaunch, uint _tokenId);

    event FlaunchVerified(address indexed _flaunch, bool _verified);
    event PoolIndexed(PoolId indexed _poolId, address indexed _flaunch, address _memecoin, address _memecoinTreasury, uint _tokenId);

    struct Index {
        address flaunch;
        address memecoin;
        address memecoinTreasury;
        uint tokenId;
    }

    struct AddIndexParams {
        address flaunch;
        uint[] tokenIds;
    }

    function subscribe(
        bytes memory _data
    ) external returns (bool);
    function notify(
        PoolId _poolId,
        bytes4 _key,
        bytes calldata _data
    ) external;
    function poolIndex(
        PoolId _poolId
    ) external view returns (address flaunch_, address memecoin_, address memecoinTreasury_, uint tokenId_);
    function addIndex(
        AddIndexParams[] calldata _params
    ) external;
    function setNotifierFlaunch(
        address _notifier,
        address _flaunch
    ) external;
    function addVerifiedFlaunch(
        address _flaunch
    ) external;
    function removeVerifiedFlaunch(
        address _flaunch
    ) external;
    function isVerifiedFlaunch(
        address _flaunch
    ) external view returns (bool verified_);
}

src/interfaces/IPairedTokenRegistry.sol

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

interface IPairedTokenRegistry {
    error PairedTokenZeroAddress();
    error InvalidPairedTokenConfig();

    /// Thrown when a non-native paired token is configured without a price calculator
    error MissingPriceCalculator();

    /// Thrown when a price calculator's own `pairedToken()` binding disagrees with the token it
    /// is being registered for (or the calculator does not expose the getter at all)
    error PriceCalculatorTokenMismatch();

    /// Thrown when a price calculator cannot serve a live quote at registration time
    error PriceCalculatorNotLive();

    /// Thrown when a token's `feeEscrow` has not been pointed back at this registry — i.e. it is
    /// not a current-generation, registry-bound multi-token {FeeEscrow}
    error FeeEscrowRegistryMismatch();

    /// Thrown when a sub-18-decimal paired token is approved without explicit distribution
    /// thresholds (leaving them at 0 would inherit the 18-decimal native-token defaults)
    error MissingDistributionThresholds();

    /// Thrown when an ERC20 wrapper's declared `underlying` disagrees with the wrapper's own
    /// `underlying()` getter
    error PairedTokenUnderlyingMismatch();

    /// Thrown when a token's declared `decimals` disagrees with its own `decimals()` getter
    error PairedTokenDecimalsMismatch();

    /// Emitted when a paired token is approved (or its config is updated)
    event PairedTokenApproved(address indexed _token, PairedToken _config);

    /// Emitted when a paired token is removed from the whitelist
    event PairedTokenUnapproved(address indexed _token);

    /// Emitted when a paired token's price calculator is updated
    event PriceCalculatorUpdated(address indexed _token, address _priceCalculator);

    /**
     * The shape of a paired token, which determines how the protocol moves and settles it.
     *
     * @member Unset The zero value — an unregistered / zero-config token. Deliberately 0 so a
     * `tokenConfig` miss never matches a wrapper branch (e.g. a memecoin referral fee forwarded as-is).
     * @member NativeWrapper An ERC20 that wraps native ETH (flETH, and canonical WETH itself);
     * `withdraw` returns raw ETH. Prices 1:1 with ETH, so the registry gates it to 18 decimals
     * and it may not bind a price calculator — this is the shape WETH registers under.
     * @member Erc20Wrapper An ERC20 that wraps another ERC20 (e.g. flUSDC); `withdraw` returns `underlying`.
     * @member NativeEth Raw native ETH (`address(0)`, the Uniswap v4 native currency); paid/received
     * directly with no wrapper and no underlying.
     * @member Erc20 A plain ERC20 with no wrapper semantics (USDC, DOGE, ...); transferred as-is,
     * never unwrapped, priced through a MANDATORY calculator — which is why WETH does not belong
     * here (a WETH:WETH oracle pool cannot exist; register it as {NativeWrapper} instead).
     * Appended so the existing type values are unchanged.
     */
    enum PairedTokenType {
        Unset,
        NativeWrapper,
        Erc20Wrapper,
        NativeEth,
        Erc20
    }

    /**
     * Per-token configuration for an approved paired token.
     *
     * @member approved Whether the token is whitelisted as a paired token
     * @member tokenType The shape of the token (see {PairedTokenType}); determines wrap/unwrap and
     * native-vs-ERC20 settlement
     * @member decimals The decimals of the paired token, used to scale launch price + thresholds
     * @member underlying The ERC20 unwrapped from the wrapper (USDC for flUSDC); `address(0)` for
     * native wrappers and native ETH
     * @member feeEscrow The {FeeEscrow} that holds this token's escrowed fees. The escrow is
     * multi-token, so every registration normally points at the same singleton instance; the
     * field stays per-token so the hooks' launch-time snapshots keep working across generations
     * @member priceCalculator The {IPairedTokenPriceCalculator} that converts ETH amounts into
     * this token's units for launch pricing. Required for `Erc20` / `Erc20Wrapper` tokens; must
     * be zero for `NativeEth` / `NativeWrapper` tokens (they are 1:1 with ETH by definition, so
     * there is exactly one pricing path per shape)
     * @member minDistribute The minimum fee inventory before a pool distributes, in token units
     * @member bidWallThreshold The accumulated-fee threshold before the BidWall repositions, in token units
     */
    struct PairedToken {
        bool approved;
        PairedTokenType tokenType;
        uint8 decimals;
        address underlying;
        address feeEscrow;
        address priceCalculator;
        uint minDistribute;
        uint bidWallThreshold;
    }

    function isApproved(
        address _token
    ) external view returns (bool);

    function tokenConfig(
        address _token
    ) external view returns (PairedToken memory);

    function approvePairedToken(
        address _token,
        PairedToken calldata _config
    ) external;

    function unapprovePairedToken(
        address _token
    ) external;

    function setPriceCalculator(
        address _token,
        address _priceCalculator
    ) external;
}

src/interfaces/IWrappedToken.sol

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

/**
 * Generalises the flETH deposit / withdraw wrapper interface to any wrapped paired token.
 *
 * For a native-ETH wrapper (flETH) `deposit` is payable and wraps `msg.value`, and `withdraw`
 * returns native ETH to the caller. For an ERC20-backed wrapper (flUSDC) `deposit` pulls the
 * `underlying` ERC20 from the caller and `withdraw` returns that underlying ERC20 to the caller.
 *
 * @dev This supersedes the flETH-specific {IFLETH} interface, which is retained as a flETH alias
 * for native-wrapper specific deploy math.
 */
interface IWrappedToken {
    /**
     * Wraps tokens into the wrapped representation.
     *
     * @param _amount The amount of `underlying` to wrap (ignored by native wrappers, which use
     * `msg.value`)
     */
    function deposit(
        uint _amount
    ) external payable;

    /**
     * Unwraps `_amount` of the wrapped token, returning either native ETH (native wrappers) or
     * the `underlying` ERC20 (ERC20 wrappers) to the caller.
     *
     * @param _amount The amount of the wrapped token to unwrap
     */
    function withdraw(
        uint _amount
    ) external;

    /**
     * The ERC20 token unwrapped from this wrapper, or `address(0)` for a native-ETH wrapper.
     *
     * @return The address of the underlying token
     */
    function underlying() external view returns (address);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 777,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "[\"@uniswap/v4-periphery/=lib/v4-hooks-public/lib/v4-periphery/\", \"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/\", \"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/\", \"@optimism/=lib/optimism/packages/contracts-bedrock/\", \"interfaces/=lib/optimism/packages/contracts-bedrock/interfaces/\", \"@solady/=lib/solady/src/\", \"solady-test/=lib/solady/test/\", \"@uniswap/v3-core/=lib/v3-core/\", \"@uniswap/v4-core/=lib/v4-hooks-public/lib/v4-periphery/lib/v4-core/\", \"@uniswap-periphery/=lib/v4-hooks-public/lib/v4-periphery/src/\", \"@uniswap-hooks/=lib/v4-hooks-public/src/\", \"solmate/=lib/optimism/packages/contracts-bedrock/lib/solmate/\", \"@flaunch/=src/contracts/\", \"@flaunch-interfaces/=src/interfaces/\", \"briefcase/=lib/v4-hooks-public/lib/briefcase/src/protocols/lib-external/solmate/src/\", \"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/\", \"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/\", \"forge-gas-snapshot/=lib/v4-hooks-public/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/\", \"forge-std/=lib/forge-std/src/\", \"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/\", \"kontrol-cheatcodes/=lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/\", \"lib-keccak/=lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/\", \"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/\", \"openzeppelin-contracts-v5/=lib/optimism/packages/contracts-bedrock/lib/openzeppelin-contracts-v5/\", \"openzeppelin-contracts/=lib/openzeppelin-contracts/\", \"optimism/=lib/optimism/\", \"permit2/=lib/v4-hooks-public/lib/v4-periphery/lib/permit2/\", \"safe-contracts/=lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/\", \"solady-v0.0.245/=lib/optimism/packages/contracts-bedrock/lib/solady-v0.0.245/src/\", \"solady/=lib/solady/src/\", \"v3-core/=lib/v3-core/\", \"v4-core/=lib/v4-hooks-public/lib/v4-periphery/lib/v4-core/src/\", \"v4-hooks-public/=lib/v4-hooks-public/\", \"v4-periphery/=lib/v4-hooks-public/lib/v4-periphery/\", \"vulcan/=lib/vulcan/src/\"]/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@optimism/=lib/optimism/packages/contracts-bedrock/",
    "interfaces/=lib/optimism/packages/contracts-bedrock/interfaces/",
    "@solady/=lib/solady/src/",
    "solady-test/=lib/solady/test/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v4-core/=lib/v4-hooks-public/lib/v4-periphery/lib/v4-core/",
    "@uniswap-periphery/=lib/v4-hooks-public/lib/v4-periphery/src/",
    "@uniswap-hooks/=lib/v4-hooks-public/src/",
    "solmate/=lib/optimism/packages/contracts-bedrock/lib/solmate/",
    "@flaunch/=src/contracts/",
    "@flaunch-interfaces/=src/interfaces/",
    "briefcase/=lib/v4-hooks-public/lib/briefcase/src/protocols/lib-external/solmate/src/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-hooks-public/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "kontrol-cheatcodes/=lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
    "lib-keccak/=lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts-v5/=lib/optimism/packages/contracts-bedrock/lib/openzeppelin-contracts-v5/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "optimism/=lib/optimism/",
    "permit2/=lib/v4-hooks-public/lib/v4-periphery/lib/permit2/",
    "safe-contracts/=lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/",
    "solady-v0.0.245/=lib/optimism/packages/contracts-bedrock/lib/solady-v0.0.245/src/",
    "solady/=lib/solady/src/",
    "v3-core/=lib/v3-core/",
    "v4-core/=lib/v4-hooks-public/lib/v4-periphery/lib/v4-core/src/",
    "v4-hooks-public/=lib/v4-hooks-public/",
    "v4-periphery/=lib/v4-hooks-public/lib/v4-periphery/",
    "vulcan/=lib/vulcan/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.