账户
0x51...afdc
0x51...AFDC

0x51...AFDC

$500
此合同的源代码已经过验证!
合同元数据
编译器
0.8.27+commit.40a35a09
语言
Solidity
合同源代码
文件 1 的 67:ActionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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


/**
 * Allows the contract owner to manage approved {ITreasuryAction} contracts.
 */
contract TreasuryActionManager is Ownable {

    event ActionApproved(address indexed _action);
    event ActionUnapproved(address indexed _action);

    // Mapping to store approved action contract addresses
    mapping (address _action => bool _approved) public approvedActions;

    /**
     * Sets the contract owner.
     *
     * @dev This contract should be created in the {PositionManager} constructor call.
     */
    constructor (address _protocolOwner) {
        _initializeOwner(_protocolOwner);
    }

    /**
     * Approves an action contract.
     *
     * @param _action {ITreasuryAction} contract address
     */
    function approveAction(address _action) external onlyOwner {
        approvedActions[_action] = true;
        emit ActionApproved(_action);
    }

    /**
     * Remove an action contract from approval.
     *
     * @param _action {ITreasuryAction} contract address
     */
    function unapproveAction(address _action) external onlyOwner {
        approvedActions[_action] = false;
        emit ActionUnapproved(_action);
    }

    /**
     * Override to return true to make `_initializeOwner` prevent double-initialization.
     *
     * @return bool Set to `true` to prevent owner being reinitialized.
     */
    function _guardInitializeOwner() internal pure override returns (bool) {
        return true;
    }

}
合同源代码
文件 2 的 67: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)
        }
    }
}
合同源代码
文件 3 的 67:BaseHook.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, SafeCallback {
    error NotSelf();
    error InvalidPool();
    error LockFailure();
    error HookNotImplemented();

    constructor(IPoolManager _manager) SafeCallback(_manager) {
        validateHookAddress(this);
    }

    /// @dev Only this address may call this function
    modifier selfOnly() {
        if (msg.sender != address(this)) revert NotSelf();
        _;
    }

    /// @dev Only pools with hooks set to this contract may call this function
    modifier onlyValidPools(IHooks hooks) {
        if (hooks != this) revert InvalidPool();
        _;
    }

    /// @notice Returns a struct of permissions to signal which hook functions are to be implemented
    /// @dev Used at deployment to validate the address correctly represents the expected permissions
    function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);

    /// @notice Validates the deployed hook address agrees with the expected permissions of the hook
    /// @dev this function is virtual so that we can override it during testing,
    /// which allows us to deploy an implementation to any address
    /// and then etch the bytecode into the correct address
    function validateHookAddress(BaseHook _this) internal pure virtual {
        Hooks.validateHookPermissions(_this, getHookPermissions());
    }

    function _unlockCallback(bytes calldata data) internal virtual override returns (bytes memory) {
        (bool success, bytes memory returnData) = address(this).call(data);
        if (success) return returnData;
        if (returnData.length == 0) revert LockFailure();
        // if the call failed, bubble up the reason
        assembly ("memory-safe") {
            revert(add(returnData, 32), mload(returnData))
        }
    }

    /// @inheritdoc IHooks
    function beforeInitialize(address, PoolKey calldata, uint160) external virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterInitialize(address, PoolKey calldata, uint160, int24) external virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
        external
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        bytes calldata
    ) external virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterAddLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) external virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) external virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, bytes calldata)
        external
        virtual
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, BalanceDelta, bytes calldata)
        external
        virtual
        returns (bytes4, int128)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        external
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        external
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }
}
合同源代码
文件 4 的 67: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)
        }
    }
}
合同源代码
文件 5 的 67:BidWall.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {Currency, CurrencyLibrary} from '@uniswap/v4-core/src/types/Currency.sol';
import {Hooks, IHooks} from '@uniswap/v4-core/src/libraries/Hooks.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {LiquidityAmounts} from '@uniswap/v4-core/test/utils/LiquidityAmounts.sol';
import {PoolId, PoolIdLibrary} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {StateLibrary} from '@uniswap/v4-core/src/libraries/StateLibrary.sol';
import {TickMath} from '@uniswap/v4-core/src/libraries/TickMath.sol';

import {CurrencySettler} from '@flaunch/libraries/CurrencySettler.sol';
import {MemecoinFinder} from '@flaunch/types/MemecoinFinder.sol';
import {PositionManager} from '@flaunch/PositionManager.sol';
import {TickFinder} from '@flaunch/types/TickFinder.sol';

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


/**
 * This hook allows us to create a single sided liquidity position (Plunge Protection) that is
 * placed 1 tick below spot price, using the ETH fees accumulated.
 *
 * After each deposit into the BidWall the position is rebalanced to ensure it remains 1 tick
 * below spot. This spot will be determined by the tick value before the triggering swap.
 */
contract BidWall is Ownable {

    using CurrencyLibrary for Currency;
    using CurrencySettler for Currency;
    using Hooks for IHooks;
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using TickFinder for int24;
    using MemecoinFinder for PoolKey;

    error CallerIsNotCreator();
    error NotPositionManager();

    /// Emitted when the BidWall is first initialised with ETH
    event BidWallInitialized(PoolId indexed _poolId, uint _eth, int24 _tickLower, int24 _tickUpper);

    /// Emitted when a BidWall receives a deposit
    event BidWallDeposit(PoolId indexed _poolId, uint _added, uint _pending);

    /// Emitted when the BidWall is repositioned under an updated tick, or with additional ETH
    event BidWallRepositioned(PoolId indexed _poolId, uint _eth, int24 _tickLower, int24 _tickUpper);

    /// Emitted when non-ETH tokens received are transferrer to the memecoin treasury
    event BidWallRewardsTransferred(PoolId indexed _poolId, address _recipient, uint _tokens);

    /// Emitted when the BidWall is closed
    event BidWallClosed(PoolId indexed _poolId, address _recipient, uint _eth);

    /// Emitted when the BidWall is disabled or enabled
    event BidWallDisabledStateUpdated(PoolId indexed _poolId, bool _disabled);

    /// Emitted when the `_swapFeeThreshold` is updated
    event FixedSwapFeeThresholdUpdated(uint _newSwapFeeThreshold);

    /**
     * Stores the BidWall information for a specific pool.
     *
     * @member disabled If the BidWall is disabled for the pool
     * @member initialized If the BidWall has been initialized
     * @member tickLower The current lower tick of the BidWall
     * @member tickUpper The current upper tick of the BidWall
     * @member pendingETHFees The amount of ETH fees waiting to be put into the BidWall until threshold is crossed
     * @member cumulativeSwapFees The total amount of swap fees accumulated for the pool
     */
    struct PoolInfo {
        bool disabled;
        bool initialized;
        int24 tickLower;
        int24 tickUpper;
        uint pendingETHFees;
        uint cumulativeSwapFees;
    }

    /// Our Uniswap V4 {PoolManager} contract
    IPoolManager public immutable poolManager;

    /// Our {PositionManager} address
    PositionManager public immutable positionManager;

    /// The native token used in the Flaunch protocol
    address public immutable nativeToken;

    /// Our fixed swap fee threshold
    uint internal _swapFeeThreshold;

    /// Maps our poolId to the `PoolInfo` struct for bidWall data
    mapping (PoolId _poolId => PoolInfo _poolInfo) public poolInfo;

    /**
     * Set up our PoolManager and native ETH token.
     *
     * @param _nativeToken The ETH token being used in the {PositionManager}
     * @param _poolManager The Uniswap V4 {PoolManager}
     */
    constructor (address _nativeToken, address _poolManager, address _protocolOwner) {
        positionManager = PositionManager(payable(msg.sender));
        nativeToken = _nativeToken;
        poolManager = IPoolManager(_poolManager);

        // Set our initial swapFeeThreshold and emit an update for the amount
        _swapFeeThreshold = 0.1 ether;
        emit FixedSwapFeeThresholdUpdated(0.1 ether);

        _initializeOwner(_protocolOwner);
    }

    /**
     * Helper function that checks if a pool's BidWall is enabled or disabled.
     *
     * @param _poolId The pool ID to check
     *
     * @return bool Set to `true` if the hook is enabled, `false` if it is disabled
     */
    function isBidWallEnabled(PoolId _poolId) public view returns (bool) {
        return !poolInfo[_poolId].disabled;
    }

    /**
     * Attributes swap fees to the BidWall and calculates if it needs to rebalance
     * the current position.
     *
     * @dev The calling contract should have already checked if this hook is active
     * and ready to receive the swap fees.
     *
     * @param _poolKey The PoolKey to modify the BidWall of
     * @param _ethSwapAmount The amount of ETH swap fees added to BidWall
     * @param _currentTick The current tick of the pool
     * @param _nativeIsZero If the native token is `currency0`
     */
    function deposit(
        PoolKey memory _poolKey,
        uint _ethSwapAmount,
        int24 _currentTick,
        bool _nativeIsZero
    ) public onlyPositionManager {
        // If we have no fees to swap, then exit early
        if (_ethSwapAmount == 0) return;

        // Increase our cumulative and pending fees
        PoolId poolId = _poolKey.toId();
        PoolInfo storage _poolInfo = poolInfo[poolId];
        _poolInfo.cumulativeSwapFees += _ethSwapAmount;
        _poolInfo.pendingETHFees += _ethSwapAmount;

        // Send an event to notify that BidWall has received funds
        emit BidWallDeposit(poolId, _ethSwapAmount, _poolInfo.pendingETHFees);

        // If we haven't yet crossed a threshold, then we just increase the amount of
        // pending fees to calculate against next time.
        if (_poolInfo.pendingETHFees < _getSwapFeeThreshold(_poolInfo.cumulativeSwapFees)) {
            return;
        }

        // Reset pending ETH token fees as we will be processing a bidwall initialization
        // or a rebalance.
        uint totalFees = _poolInfo.pendingETHFees;
        _poolInfo.pendingETHFees = 0;

        uint ethWithdrawn;
        uint memecoinWithdrawn;

        // Check if the BidWall has been initialized before, then we have a position
        if (_poolInfo.initialized) {
            // Remove tokens from our current position
            (ethWithdrawn, memecoinWithdrawn) = _removeLiquidity({
                _key: _poolKey,
                _nativeIsZero: _nativeIsZero,
                _tickLower: _poolInfo.tickLower,
                _tickUpper: _poolInfo.tickUpper
            });

            // Send the received ETH to the {PositionManager}, as that will be supplying the ETH
            // tokens to create the new position.
            if (ethWithdrawn != 0) {
                IERC20(nativeToken).transfer(address(positionManager), ethWithdrawn);
            }
        } else {
            // If this is the first time we are adding liquidity, then we can set our
            // pool initialized flag to true.
            _poolInfo.initialized = true;
        }

        /**
         * The `_currentTick` is calculated from the `_beforeSwapTick`, which means that it could be
         * that the actual swap has impacted the tick of the pool. This will affect our liquidity
         * modification in one of two ways:
         *
         *   1. The tick has moved FOR the native token, meaning that we will be creating our position to
         *      give a lower native token value. This is absolutely fine and is expected so as to not give
         *      an overly generous price when the BidWall is triggered.
         *   2. The tick has moved AGAINST the native token, meaning that we will be creating our position
         *      to give a higher native token value. This means that liquidity calculations called within
         *      the `_addETHLiquidity` will actually result in requiring both native _and_ memecoin tokens
         *      to be settled. If this is the case then we instead need to use the `slot0` tick rather than
         *      the beforeSwap tick value provided in `_currentTick`.
         *
         * This is the final, and only, place that `_currentTick` is referenced, so we can safely overwrite
         * the value if required.
         */

        (, int24 slot0Tick,,) = poolManager.getSlot0(poolId);
        if (_nativeIsZero == slot0Tick > _currentTick) {
            _currentTick = slot0Tick;
        }

        // Create our liquidity position; including any tokens withdrawn from our previous position if
        // set, as well as the additional swap fees.
        _addETHLiquidity({
            _key: _poolKey,
            _nativeIsZero: _nativeIsZero,
            _currentTick: _currentTick,
            _ethAmount: ethWithdrawn + totalFees
        });

        // If we have memecoins available, then we transfer those to the treasury
        if (memecoinWithdrawn != 0) {
            // Find our non-ETH token and the {TokenTreasury} attached to it
            IMemecoin memecoin = _poolKey.memecoin(nativeToken);
            address memecoinTreasury = memecoin.treasury();

            // Transfer the tokens to the memecoin treasury
            memecoin.transfer(memecoinTreasury, memecoinWithdrawn);
            emit BidWallRewardsTransferred(poolId, memecoinTreasury, memecoinWithdrawn);
        }

        emit BidWallRepositioned(poolId, ethWithdrawn + totalFees, _poolInfo.tickLower, _poolInfo.tickUpper);
    }

    /**
     * Allows the BidWall to be enabled or disabled for the {PoolKey}.
     *
     * If disabled, future swap fees will be transferred directly to the respective
     * {MemecoinTreasury} address instead of the BidWall.
     *
     * @dev This can only be called by the creator of the memecoin.
     *
     * @param _key The PoolKey that is being updated
     * @param _disable If the BidWall is being disabled (true) or enabled (false)
     */
    function setDisabledState(PoolKey memory _key, bool _disable) external {
        // Ensure that the caller is the pool creator
        if (msg.sender != _key.memecoin(nativeToken).creator()) revert CallerIsNotCreator();

        // We only need to process the following logic if anything is changing
        PoolInfo storage _poolInfo = poolInfo[_key.toId()];
        if (_disable == _poolInfo.disabled) return;

        // If we are disabling our BidWall, then we want to also remove the current liquidity. We
        // need to send this through the {PositionManager} so that it can open a {PoolManager} lock.
        if (_disable) {
            positionManager.closeBidWall(_key);
        }

        // Update our disabled flag
        _poolInfo.disabled = _disable;

        // Emit our event to flag the BidWall disabled state update
        emit BidWallDisabledStateUpdated(_key.toId(), _disable);
    }

    /**
     * Allows the memecoin creator to close the BidWall and distribute any fees held in the BidWall
     * to the treasury address.
     *
     * This call will have been routed in the following way:
     * ```
     * BidWall.disable -> PositionManager.closeBidWall -> PositionManager.unlockCallback -> BidWall.closeBidwall
     * ```
     *
     * @param _key The PoolKey that we are closing the BidWall of
     */
    function closeBidWall(PoolKey memory _key) external onlyPositionManager {
        // Unpack information required for our call
        bool nativeIsZero = nativeToken == Currency.unwrap(_key.currency0);

        PoolId poolId = _key.toId();
        PoolInfo storage _poolInfo = poolInfo[poolId];

        uint ethWithdrawn;
        uint memecoinWithdrawn;

        // If the pool has not yet been initialized, then there will be no liquidity to remove
        if (_poolInfo.initialized) {
            // Remove all liquidity from the BidWall
            (ethWithdrawn, memecoinWithdrawn) = _removeLiquidity({
                _key: _key,
                _nativeIsZero: nativeIsZero,
                _tickLower: _poolInfo.tickLower,
                _tickUpper: _poolInfo.tickUpper
            });

            // Set our pool back to being uninitialized
            _poolInfo.initialized = false;
        }

        // Reset pending ETH fees for the pool. We also reset our `cumulativeSwapFees` as this is
        // used to determine our threshold hits.
        uint pendingETHFees = _poolInfo.pendingETHFees;
        _poolInfo.pendingETHFees = 0;
        _poolInfo.cumulativeSwapFees = 0;

        // Unwrap the non-native token and find the treasury address
        IMemecoin memecoin = _key.memecoin(nativeToken);
        address memecoinTreasury = memecoin.treasury();

        // Pending ETH fees are stored in the {PositionManager}. So if we have a value there, then we
        // will need to transfer this from the {PositionManager}, rather than this contract.
        if (pendingETHFees != 0) {
            IERC20(nativeToken).transferFrom(address(positionManager), memecoinTreasury, pendingETHFees);
        }

        // Transfer ETH withdrawn from the legacy position to the governance contract. We Avoid using
        // safe transfer as this could brick calls if a malicious governance was set by the token.
        if (ethWithdrawn != 0) {
            IERC20(nativeToken).transfer(memecoinTreasury, ethWithdrawn);
        }

        // Transfer the flTokens withdrawn from the legacy position to the governance contract
        if (memecoinWithdrawn != 0) {
            memecoin.transfer(memecoinTreasury, memecoinWithdrawn);
            emit BidWallRewardsTransferred(poolId, memecoinTreasury, memecoinWithdrawn);
        }

        emit BidWallClosed(poolId, memecoinTreasury, ethWithdrawn + pendingETHFees);
    }

    /**
     * Retrieves the current position held by the BidWall.
     *
     * @param _poolId The `PoolId` to check the {BidWall} position of
     *
     * @return amount0_ The {BidWall} token0 position
     * @return amount1_ The {BidWall} token1 position
     * @return pendingEth_ The amount of ETH pending to be depositted into the {BidWall}
     */
    function position(PoolId _poolId) public view returns (uint amount0_, uint amount1_, uint pendingEth_) {
        // Get the BidWall tick range from our PoolInfo
        PoolInfo memory _poolInfo = poolInfo[_poolId];

        // If our pool is not initialized, then we don't have a position to query and we will
        // only have the pending fees to return
        if (!_poolInfo.initialized) {
            return (0, 0, _poolInfo.pendingETHFees);
        }

        // Retrieve the total liquidity of the pool
        (uint128 liquidity,,) = poolManager.getPositionInfo({
            poolId: _poolId,
            owner: address(this),
            tickLower: _poolInfo.tickLower,
            tickUpper: _poolInfo.tickUpper,
            salt: 'bidwall'
        });

        // Get the current slot of the pool and find the amounts against the liquidity
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(_poolId);
        (amount0_, amount1_) = LiquidityAmounts.getAmountsForLiquidity({
            sqrtPriceX96: sqrtPriceX96,
            sqrtPriceAX96: TickMath.getSqrtPriceAtTick(_poolInfo.tickLower),
            sqrtPriceBX96: TickMath.getSqrtPriceAtTick(_poolInfo.tickUpper),
            liquidity: liquidity
        });

        // Map our pending fees to our response
        pendingEth_ = _poolInfo.pendingETHFees;
    }

    /**
     * Allows the threshold for the swap fee to be updated.
     *
     * @param swapFeeThreshold The new threshold to set
     */
    function setSwapFeeThreshold(uint swapFeeThreshold) external onlyOwner {
        _swapFeeThreshold = swapFeeThreshold;
        emit FixedSwapFeeThresholdUpdated(_swapFeeThreshold);
    }

    /**
     * Adds liquidity to our BidWall position. We calculate the tick to be adjacent to the current
     * tick of the pool into a single tick spaced range.
     *
     * @param _key The {PoolKey} that is being modified
     * @param _nativeIsZero If our native token is `currency0`
     * @param _currentTick The current tick for the pool
     * @param _ethAmount The amount of native token we are adding to the BidWall
     */
    function _addETHLiquidity(PoolKey memory _key, bool _nativeIsZero, int24 _currentTick, uint _ethAmount) internal {
        // Determine a base tick just outside of the current tick
        int24 baseTick = _nativeIsZero ? _currentTick + 1 : _currentTick - 1;

        /**
         * Calculate the tick range for the BidWall.
         *
         *                   tick ( lower | upper )
         * When the tick is  6931 (  6960 |  7020 )
         * When the tick is -6932 ( -7020 | -6960 )
         */

        int24 newTickLower;
        int24 newTickUpper;
        uint128 liquidityDelta;

        if (_nativeIsZero) {
            newTickLower = baseTick.validTick(false);
            newTickUpper = newTickLower + TickFinder.TICK_SPACING;
            liquidityDelta = LiquidityAmounts.getLiquidityForAmount0({
                sqrtPriceAX96: TickMath.getSqrtPriceAtTick(newTickLower),
                sqrtPriceBX96: TickMath.getSqrtPriceAtTick(newTickUpper),
                amount0: _ethAmount
            });
        } else {
            newTickUpper = baseTick.validTick(true);
            newTickLower = newTickUpper - TickFinder.TICK_SPACING;
            liquidityDelta = LiquidityAmounts.getLiquidityForAmount1({
                sqrtPriceAX96: TickMath.getSqrtPriceAtTick(newTickLower),
                sqrtPriceBX96: TickMath.getSqrtPriceAtTick(newTickUpper),
                amount1: _ethAmount
            });
        }

        // Modify the liquidity to add our position
        _modifyAndSettleLiquidity({
            _poolKey: _key,
            _tickLower: newTickLower,
            _tickUpper: newTickUpper,
            _liquidityDelta: int128(liquidityDelta),
            _sender: address(positionManager)
        });

        // Update the BidWall position tick range
        PoolInfo storage _poolInfo = poolInfo[_key.toId()];
        _poolInfo.tickLower = newTickLower;
        _poolInfo.tickUpper = newTickUpper;
    }

    /**
     * Removes liquidity from our BidWall position.
     *
     * @param _key The {PoolKey} that is being modified
     * @param _nativeIsZero If our native token is `currency0`
     * @param _tickLower The lower tick of our BidWall position
     * @param _tickUpper The upper tick of our BidWall position
     *
     * @return ethWithdrawn_ The amount of native token withdrawn
     * @return memecoinWithdrawn_ The amount of Memecoin withdrawn
     */
    function _removeLiquidity(
        PoolKey memory _key,
        bool _nativeIsZero,
        int24 _tickLower,
        int24 _tickUpper
    ) internal returns (
        uint ethWithdrawn_,
        uint memecoinWithdrawn_
    ) {
        // Get our existing liquidity for the position
        (uint128 liquidityBefore,,) = poolManager.getPositionInfo({
            poolId: _key.toId(),
            owner: address(this),
            tickLower: _tickLower,
            tickUpper: _tickUpper,
            salt: 'bidwall'
        });

        BalanceDelta delta = _modifyAndSettleLiquidity({
            _poolKey: _key,
            _tickLower: _tickLower,
            _tickUpper: _tickUpper,
            _liquidityDelta: -int128(liquidityBefore),
            _sender: address(this)
        });

        // Set our ETH and Memecoin withdrawn amounts, depending on if the native token is currency0
        (ethWithdrawn_, memecoinWithdrawn_) = _nativeIsZero
            ? (uint128(delta.amount0()), uint128(delta.amount1()))
            : (uint128(delta.amount1()), uint128(delta.amount0()));
    }

    /**
     * This function will only be called by other functions via the PositionManager, which will already
     * hold the Uniswap V4 PoolManager key. It is for this reason we can interact openly with the
     * Uniswap V4 protocol without requiring a separate callback.
     *
     * @param _poolKey The {PoolKey} that is being modified
     * @param _tickLower The lower tick of our BidWall position
     * @param _tickUpper The upper tick of our BidWall position
     * @param _liquidityDelta The liquidity delta modifying the position
     * @param _sender The address that will be sending or receiving tokens
     */
    function _modifyAndSettleLiquidity(
        PoolKey memory _poolKey,
        int24 _tickLower,
        int24 _tickUpper,
        int128 _liquidityDelta,
        address _sender
    ) internal returns (
        BalanceDelta delta_
    ) {
        (delta_, ) = poolManager.modifyLiquidity({
            key: _poolKey,
            params: IPoolManager.ModifyLiquidityParams({
                tickLower: _tickLower,
                tickUpper: _tickUpper,
                liquidityDelta: _liquidityDelta,
                salt: 'bidwall'
            }),
            hookData: ''
        });

        if (delta_.amount0() < 0) {
            _poolKey.currency0.settle(poolManager, _sender, uint128(-delta_.amount0()), false);
        } else if (delta_.amount0() > 0) {
            poolManager.take(_poolKey.currency0, _sender, uint128(delta_.amount0()));
        }

        if (delta_.amount1() < 0) {
            _poolKey.currency1.settle(poolManager, _sender, uint128(-delta_.amount1()), false);
        } else if (delta_.amount1() > 0) {
            poolManager.take(_poolKey.currency1, _sender, uint128(delta_.amount1()));
        }
    }

    /**
     * Defines our swap fee thresholds that must be crossed to provide fees. Each time
     * that we hit a set `cumulativeSwapFees` amount, we release a threshold of fees into
     * the bid wall.
     *
     * For this fixed threshold, this will just return the value set in `setSwapFeeThreshold`.
     *
     * @return uint The swap fee threshold
     */
    function _getSwapFeeThreshold(uint) internal virtual view returns (uint) {
        return _swapFeeThreshold;
    }

    /**
     * Override to return true to make `_initializeOwner` prevent double-initialization.
     *
     * @return bool Set to `true` to prevent owner being reinitialized.
     */
    function _guardInitializeOwner() internal pure override virtual returns (bool) {
        return true;
    }

    /**
     * Ensures that only the immutable {PositionManager} can call the function.
     */
    modifier onlyPositionManager {
        if (msg.sender != address(positionManager)) revert NotPositionManager();
        _;
    }

}
合同源代码
文件 6 的 67:BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}
合同源代码
文件 7 的 67: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)));
    }
}
合同源代码
文件 8 的 67:CurrencyReserves.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

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

library CurrencyReserves {
    using CustomRevert for bytes4;

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

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

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

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

    function getSyncedReserves() internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(RESERVES_OF_SLOT)
        }
    }
}
合同源代码
文件 9 的 67:CurrencySettler.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {IERC20Minimal} from '@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';


/**
 * Library used to interact with PoolManager.sol to settle any open deltas:
 * - To settle a positive delta (a credit to the user), a user may take or mint.
 * - To settle a negative delta (a debt on the user), a user make transfer or burn to pay off a debt.
 *
 * @dev Note that sync() is called before any erc-20 transfer in `settle`.
 */
library CurrencySettler {

    /**
     * Settle (pay) a currency to the PoolManager.
     *
     * @param currency Currency to settle
     * @param manager IPoolManager to settle to
     * @param payer Address of the payer, the token sender
     * @param amount Amount to send
     * @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
     */
    function settle(Currency currency, IPoolManager manager, address payer, uint amount, bool burn) internal {
        // For native currencies or burns, calling sync is not required
        // short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
        if (burn) {
            manager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            manager.settle{value: amount}();
        } else {
            manager.sync(currency);
            if (payer != address(this)) {
                IERC20Minimal(Currency.unwrap(currency)).transferFrom(payer, address(manager), amount);
            } else {
                IERC20Minimal(Currency.unwrap(currency)).transfer(address(manager), amount);
            }
            manager.settle();
        }
    }

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

}
合同源代码
文件 10 的 67: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))
        }
    }
}
合同源代码
文件 11 的 67:EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}
合同源代码
文件 12 的 67:FairLaunch.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {BeforeSwapDelta, toBeforeSwapDelta} from '@uniswap/v4-core/src/types/BeforeSwapDelta.sol';
import {BalanceDelta, toBalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {FullMath} from '@uniswap/v4-core/src/libraries/FullMath.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {LiquidityAmounts} from '@uniswap/v4-core/test/utils/LiquidityAmounts.sol';
import {PoolId, PoolIdLibrary} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {SafeCast} from '@uniswap/v4-core/src/libraries/SafeCast.sol';
import {TickMath} from '@uniswap/v4-core/src/libraries/TickMath.sol';

import {CurrencySettler} from '@flaunch/libraries/CurrencySettler.sol';
import {TickFinder} from '@flaunch/types/TickFinder.sol';


/**
 * Adds functionality to the {PositionManager} that promotes a fair token launch.
 *
 * This creates a time window right after the token is launched that keeps the token at
 * the same price in a single tick position. Fees earned from this are kept within the
 * position and cannot be sold into until the fair launch window has finished.
 *
 * Once the FairLaunch period has ended, the ETH raised and the remaining tokens are
 * both deployed into a Uniswap position to facilitate ongoing transactions and create
 * a price discovery.
 *
 * @dev Based on: https://github.com/fico23/fundraise-hook
 */
contract FairLaunch {

    using CurrencySettler for Currency;
    using PoolIdLibrary for PoolKey;
    using SafeCast for *;
    using TickFinder for int24;

    error CannotModifyLiquidityDuringFairLaunch();
    error CannotSellTokenDuringFairLaunch();
    error NotPositionManager();

    /// Emitted when a Fair Launch position is created
    event FairLaunchCreated(PoolId indexed _poolId, uint _tokens, uint _startsAt, uint _endsAt);

    /// Emitted when a Fair Launch is ended and rebalanced
    event FairLaunchEnded(PoolId indexed _poolId, uint _revenue, uint _supply, uint _endedAt);

    /**
     * Holds FairLaunch information for a Pool.
     *
     * @member startsAt The unix timestamp that the FairLaunch window starts
     * @member endsAt The unix timestamp that the FairLaunch window ends
     * @member initialTick The tick that the FairLaunch position was created at
     * @member revenue The amount of revenue earned by the FairLaunch position
     * @member supply The amount of supply in the FairLaunch
     * @member closed If the FairLaunch has been closed
     */
    struct FairLaunchInfo {
        uint startsAt;
        uint endsAt;
        int24 initialTick;
        uint revenue;
        uint supply;
        bool closed;
    }

    /// Our fair launch window duration
    uint public constant FAIR_LAUNCH_WINDOW = 30 minutes;

    /// Maps a PoolId to a FairLaunchInfo struct
    mapping (PoolId _poolId => FairLaunchInfo _info) internal _fairLaunchInfo;

    /// Our Uniswap V4 {PoolManager} contract address
    IPoolManager public immutable poolManager;

    /// Our Flaunch {PositionManager} address
    address public immutable positionManager;

    /**
     * Stores our native token.
     *
     * @param _poolManager The Uniswap V4 {PoolManager} contract
     */
    constructor (IPoolManager _poolManager) {
        poolManager = _poolManager;

        // Set our {PositionManager} as the caller
        positionManager = msg.sender;
    }

    /**
     * Checks if the {PoolKey} is within the fair launch window.
     *
     * @param _poolId The ID of the PoolKey
     *
     * @return If the {PoolKey} is within the fair launch window
     */
    function inFairLaunchWindow(PoolId _poolId) public view returns (bool) {
        FairLaunchInfo memory info = _fairLaunchInfo[_poolId];
        return block.timestamp >= info.startsAt && block.timestamp < info.endsAt;
    }

    /**
     * Helper function to call the FairLaunchInfo struct for a pool.
     *
     * @param _poolId The ID of the PoolKey
     *
     * @return The FairLaunchInfo for the pool
     */
    function fairLaunchInfo(PoolId _poolId) public view returns (FairLaunchInfo memory) {
        return _fairLaunchInfo[_poolId];
    }

    /**
     * Creates an initial fair launch position.
     *
     * @param _poolId The ID for the pool being initialized
     * @param _initialTokenFairLaunch The amount of tokens to add as single sided fair launch liquidity
     */
    function createPosition(
        PoolId _poolId,
        int24 _initialTick,
        uint _flaunchesAt,
        uint _initialTokenFairLaunch
    ) public virtual onlyPositionManager returns (
        FairLaunchInfo memory
    ) {
        // Determine the time that the fair launch window will close
        uint endsAt = _flaunchesAt + FAIR_LAUNCH_WINDOW;

        // Map these tokens into an pseudo-escrow that we can reference during the sale
        // and activate our pool fair launch window.
        _fairLaunchInfo[_poolId] = FairLaunchInfo({
            startsAt: _flaunchesAt,
            endsAt: endsAt,
            initialTick: _initialTick,
            revenue: 0,
            supply: _initialTokenFairLaunch,
            closed: false
        });

        emit FairLaunchCreated(_poolId, _initialTokenFairLaunch, _flaunchesAt, endsAt);
        return _fairLaunchInfo[_poolId];
    }

    /**
     * Closes the FairLaunch position and recreates the position as a wide range position immediately
     * above the tick for our memecoin. This position is comprised of any unsold Memecoin
     * from the FairLaunch, as well as the remaining supply from mint.
     *
     * @param _poolKey The PoolKey we are closing the FairLaunch position of
     * @param _tokenFees The amount of token fees that need to remain in the {PositionManager}
     * @param _nativeIsZero If our native token is `currency0`
     */
    function closePosition(
        PoolKey memory _poolKey,
        uint _tokenFees,
        bool _nativeIsZero
    ) public onlyPositionManager returns (
        FairLaunchInfo memory
    ) {
        // Reference the pool's FairLaunchInfo, ready to store updated values
        FairLaunchInfo storage info = _fairLaunchInfo[_poolKey.toId()];

        int24 tickLower;
        int24 tickUpper;

        if (_nativeIsZero) {
            // ETH position
            tickLower = (info.initialTick + 1).validTick(false);
            tickUpper = tickLower + TickFinder.TICK_SPACING;
            _createImmutablePosition(_poolKey, tickLower, tickUpper, info.revenue, true);

            // memecoin position
            tickLower = TickFinder.MIN_TICK;
            tickUpper = (info.initialTick - 1).validTick(true);
            _createImmutablePosition(_poolKey, tickLower, tickUpper, _poolKey.currency1.balanceOf(address(positionManager)) - _tokenFees, false);
        } else {
            // ETH position
            tickUpper = (info.initialTick - 1).validTick(true);
            tickLower = tickUpper - TickFinder.TICK_SPACING;
            _createImmutablePosition(_poolKey, tickLower, tickUpper, info.revenue, false);

            // memecoin position
            tickLower = (info.initialTick + 1).validTick(false);
            tickUpper = TickFinder.MAX_TICK;
            _createImmutablePosition(_poolKey, tickLower, tickUpper, _poolKey.currency0.balanceOf(address(positionManager)) - _tokenFees, true);
        }

        // Mark our position as closed
        info.endsAt = block.timestamp;
        info.closed = true;

        // Emit the event with the balance of the currency we hold before we create a position with
        // it. We determine the end time by seeing if it has ended early, or if we are past the point
        // it was meant to end then we backdate it.
        emit FairLaunchEnded(_poolKey.toId(), info.revenue, info.supply, info.endsAt);

        return info;
    }

    /**
     * When we are filling from our Fair Launch position, we will always be buying tokens
     * with ETH. The amount specified that is passed in, however, could be positive or negative.
     *
     * The positive / negative flag will require us to calculate the amount the user will get in
     * a different way. Positive: How much ETH it costs to get amount. Negative: How many tokens
     * I can get for amount.
     *
     * The amount requested **can** exceed the Fair Launch position, but we will additionally
     * have to call `_closeFairLaunchPosition` to facilitate it during this call. This will
     * provide additional liquidity before the swap actually takes place.
     *
     * @dev `zeroForOne` will always be equal to `_nativeIsZero` as it will always be ETH -> Token.
     *
     * @param _poolKey The PoolKey we are filling from
     * @param _amountSpecified The amount specified in the swap
     * @param _nativeIsZero If our native token is `currency0`
     *
     * @return beforeSwapDelta_ The modified swap delta
     */
    function fillFromPosition(
        PoolKey memory _poolKey,
        int _amountSpecified,
        bool _nativeIsZero
    ) public onlyPositionManager returns (
        BeforeSwapDelta beforeSwapDelta_,
        BalanceDelta balanceDelta_,
        FairLaunchInfo memory fairLaunchInfo_
    ) {
        PoolId poolId = _poolKey.toId();
        FairLaunchInfo storage info = _fairLaunchInfo[poolId];

        // No tokens, no fun.
        if (_amountSpecified == 0) {
            return (beforeSwapDelta_, balanceDelta_, info);
        }

        uint ethIn;
        uint tokensOut;

        // If we have a negative amount specified, then we have an ETH amount passed in and want
        // to buy as many tokens as we can for that price.
        if (_amountSpecified < 0) {
            ethIn = uint(-_amountSpecified);
            tokensOut = _getQuoteAtTick(
                info.initialTick,
                ethIn,
                Currency.unwrap(_nativeIsZero ? _poolKey.currency0 : _poolKey.currency1),
                Currency.unwrap(_nativeIsZero ? _poolKey.currency1 : _poolKey.currency0)
            );
        }
        // Otherwise, if we have a positive amount specified, then we know the number of tokens that
        // are being purchased and need to calculate the amount of ETH required.
        else {
            tokensOut = uint(_amountSpecified);
            ethIn = _getQuoteAtTick(
                info.initialTick,
                tokensOut,
                Currency.unwrap(!_nativeIsZero ? _poolKey.currency0 : _poolKey.currency1),
                Currency.unwrap(!_nativeIsZero ? _poolKey.currency1 : _poolKey.currency0)
            );
        }

        // If the user has requested more tokens than are available in the fair launch, then we
        // need to strip back the amount that we can fulfill.
        if (tokensOut > info.supply) {
            // Calculate the percentage of tokensOut relative to the threshold and reduce the `ethIn`
            // value by the same amount. There may be some slight accuracy loss, but it's all good.
            uint percentage = info.supply * 1e18 / tokensOut;
            ethIn = (ethIn * percentage) / 1e18;

            // Update our `tokensOut` to the supply limit
            tokensOut = info.supply;
        }

        // Get our BeforeSwapDelta response ready
        beforeSwapDelta_ = (_amountSpecified < 0)
            ? toBeforeSwapDelta(ethIn.toInt128(), -tokensOut.toInt128())
            : toBeforeSwapDelta(-tokensOut.toInt128(), ethIn.toInt128());

        // Define our BalanceDelta
        balanceDelta_ = toBalanceDelta(
            _nativeIsZero ? ethIn.toInt128() : -tokensOut.toInt128(),
            _nativeIsZero ? -tokensOut.toInt128() : ethIn.toInt128()
        );

        info.revenue += ethIn;
        info.supply -= tokensOut;

        return (beforeSwapDelta_, balanceDelta_, info);
    }

    /**
     * Allows calls from the {PositionManager} to modify the amount of revenue stored against a pool's
     * FairLaunch position. This is required to correctly attribute fees taken.
     *
     * @param _poolId The ID of the PoolKey
     * @param _revenue The revenue amount to add or subtract
     */
    function modifyRevenue(PoolId _poolId, int _revenue) public onlyPositionManager {
        if (_revenue < 0) {
            _fairLaunchInfo[_poolId].revenue -= uint(-_revenue);
        } else if (_revenue > 0) {
            _fairLaunchInfo[_poolId].revenue += uint(_revenue);
        }
    }

    /**
     * Creates an immutable, single-sided position when the FairLaunch window is closed.
     *
     * @param _poolKey The PoolKey to create a position against
     * @param _tickLower The lower tick of the position
     * @param _tickUpper The upper tick of the position
     * @param _tokens The number of tokens to put into the position
     * @param _tokenIsZero True if the position is created `currency0`; false is `currency1`
     */
    function _createImmutablePosition(
        PoolKey memory _poolKey,
        int24 _tickLower,
        int24 _tickUpper,
        uint _tokens,
        bool _tokenIsZero
    ) internal {
        // Calculate the liquidity delta based on the tick range and token amount
        uint128 liquidityDelta = _tokenIsZero ? LiquidityAmounts.getLiquidityForAmount0({
            sqrtPriceAX96: TickMath.getSqrtPriceAtTick(_tickLower),
            sqrtPriceBX96: TickMath.getSqrtPriceAtTick(_tickUpper),
            amount0: _tokens
        }) : LiquidityAmounts.getLiquidityForAmount1({
            sqrtPriceAX96: TickMath.getSqrtPriceAtTick(_tickLower),
            sqrtPriceBX96: TickMath.getSqrtPriceAtTick(_tickUpper),
            amount1: _tokens
        });

        // If we have no liquidity, then exit before creating the position which would revert
        if (liquidityDelta == 0) return;

        // Create our single-sided position
        (BalanceDelta delta,) = poolManager.modifyLiquidity({
            key: _poolKey,
            params: IPoolManager.ModifyLiquidityParams({
                tickLower: _tickLower,
                tickUpper: _tickUpper,
                liquidityDelta: liquidityDelta.toInt128(),
                salt: ''
            }),
            hookData: ''
        });

        // Settle the tokens that are required to fill the position
        if (delta.amount0() < 0) {
            _poolKey.currency0.settle(poolManager, address(positionManager), uint(-int(delta.amount0())), false);
        }

        if (delta.amount1() < 0) {
            _poolKey.currency1.settle(poolManager, address(positionManager), uint(-int(delta.amount1())), false);
        }
    }

    /**
     * Given a tick and a token amount, calculates the amount of token received in exchange.
     *
     * @dev Forked from the `Uniswap/v3-periphery` {OracleLibrary} contract.
     *
     * @param _tick Tick value used to calculate the quote
     * @param _baseAmount Amount of token to be converted
     * @param _baseToken Address of an ERC20 token contract used as the baseAmount denomination
     * @param _quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
     *
     * @return quoteAmount_ Amount of quoteToken received for baseAmount of baseToken
     */
    function _getQuoteAtTick(
        int24 _tick,
        uint _baseAmount,
        address _baseToken,
        address _quoteToken
    ) internal pure returns (
        uint quoteAmount_
    ) {
        uint160 sqrtPriceX96 = TickMath.getSqrtPriceAtTick(_tick);

        // Calculate `quoteAmount` with better precision if it doesn't overflow when multiplied
        // by itself.
        if (sqrtPriceX96 <= type(uint128).max) {
            uint ratioX192 = uint(sqrtPriceX96) * sqrtPriceX96;
            quoteAmount_ = _baseToken < _quoteToken
                ? FullMath.mulDiv(ratioX192, _baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, _baseAmount, ratioX192);
        } else {
            uint ratioX128 = FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, 1 << 64);
            quoteAmount_ = _baseToken < _quoteToken
                ? FullMath.mulDiv(ratioX128, _baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, _baseAmount, ratioX128);
        }
    }

    /**
     * Ensures that only the immutable {PositionManager} can call the function.
     */
    modifier onlyPositionManager {
        if (msg.sender != positionManager) revert NotPositionManager();
        _;
    }

}
合同源代码
文件 13 的 67:FeeDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {PoolId, PoolIdLibrary} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';

import {FeeExemptions} from '@flaunch/hooks/FeeExemptions.sol';
import {MemecoinFinder} from '@flaunch/types/MemecoinFinder.sol';
import {ReferralEscrow} from '@flaunch/referrals/ReferralEscrow.sol';

import {IFeeCalculator} from '@flaunch-interfaces/IFeeCalculator.sol';
import {IFLETH} from '@flaunch-interfaces/IFLETH.sol';
import {IMemecoin} from '@flaunch-interfaces/IMemecoin.sol';


/**
 * This hook will allow our pools to have a range of fee distribution approaches. This will
 * fallback onto a global fee distribution if there is not a specific.
 */
abstract contract FeeDistributor is Ownable {

    using MemecoinFinder for PoolKey;
    using PoolIdLibrary for PoolKey;

    error CallerNotCreator(address _caller);
    error RecipientZeroAddress();
    error ProtocolFeeInvalid();
    error ReferrerFeeInvalid();
    error SwapFeeInvalid();

    /// Emitted when our `FeeDistribution` struct is modified
    event FeeDistributionUpdated(FeeDistribution _feeDistribution);

    /// Emitted when our `FeeDistribution` struct is modified for a pool
    event PoolFeeDistributionUpdated(PoolId indexed _poolId, FeeDistribution _feeDistribution);

    /// Emitted when fees are added to a payee
    event Deposit(PoolId indexed _poolId, address _payee, address _token, uint _amount);

    /// Emitted when fees are withdrawn to a payee
    event Withdrawal(address _sender, address _recipient, address _token, uint _amount);

    /// Emitted when our {FeeCalculator} contract is updated
    event FeeCalculatorUpdated(address _feeCalculator);

    /// Emitted when our FairLaunch {FeeCalculator} contract is updated
    event FairLaunchFeeCalculatorUpdated(address _feeCalculator);

    /// Emitted when a pool's creator fee allocation is updated
    event CreatorFeeAllocationUpdated(PoolId indexed _poolId, uint24 _allocation);

    /// Emitted when a referrer fee has been paid out
    event ReferrerFeePaid(PoolId indexed _poolId, address _recipient, address _token, uint _amount);

    /// Emitted when the {ReferralEscrow} contract is updated
    event ReferralEscrowUpdated(address _referralEscrow);

    /**
     * Stores the percentages of fee distribution.
     *
     * @dev This works in a waterfall approach, with a percentage taking a share before
     * passing the potential allocation on to the next. This means that the percentages
     * listed don't need to equal 100%:
     *
     * `Fee priority: swapfee -> referrer -> protocol -> creator -> bidwall`
     *
     * @member swapFee The amount of the transaction taken as fee
     * @member referrer The percentage that the referrer will receive
     * @member protocol The percentage that the protocol will receive
     * @member active If a FeeDistribution struct has been set for the mapping
     */
    struct FeeDistribution {
        uint24 swapFee;
        uint24 referrer;
        uint24 protocol;
        bool active;
    }

    /// Helpful constant to define 100% to 2dp
    uint internal constant ONE_HUNDRED_PERCENT = 100_00;

    /// The maximum value of a protocol fee allocation
    uint24 public constant MAX_PROTOCOL_ALLOCATION = 10_00;

    /// Maps the creators share of the fee distribution that can be set by the creator
    /// to reduce fees from hitting the bidwall.
    mapping (PoolId _poolId => uint24 _creatorFee) internal creatorFee;

    /// Maps a user to an ETH equivalent token balance available in escrow
    mapping (address _recipient => uint _amount) public balances;

    /// Maps individual pools to custom `FeeDistribution`s. These will overwrite the
    /// global `feeDistribution`.
    mapping (PoolId _poolId => FeeDistribution _feeDistribution) internal poolFeeDistribution;

    /// Maps our IERC20 token addresses to their registered PoolKey
    mapping (address _memecoin => PoolKey _poolKey) internal _poolKeys;

    /// The global FeeDistribution that will be applied to all pools
    FeeDistribution internal feeDistribution;

    /// The {ReferralEscrow} contract that will be used
    ReferralEscrow public referralEscrow;

    /// The {IFeeCalculator} used to calculate swap fees
    IFeeCalculator public feeCalculator;
    IFeeCalculator public fairLaunchFeeCalculator;

    /// Our internal native token
    address public immutable nativeToken;

    /// The address of the $FLAY token's governance
    address public immutable flayGovernance;

    /**
     * Set up our initial FeeDistribution data.
     *
     * @param _nativeToken Our internal native token
     * @param _feeDistribution The initial FeeDistribution value
     * @param _protocolOwner The initial EOA owner of the contract
     */
    constructor (address _nativeToken, FeeDistribution memory _feeDistribution, address _protocolOwner, address _flayGovernance) {
        nativeToken = _nativeToken;

        // Set our initial fee distribution
        _validateFeeDistribution(_feeDistribution);
        feeDistribution = _feeDistribution;
        emit FeeDistributionUpdated(_feeDistribution);

        // Set our $FLAY token governance address
        flayGovernance = _flayGovernance;

        // Grant ownership permissions to the caller
        if (owner() == address(0)) {
            _initializeOwner(_protocolOwner);
        }
    }

    /**
     * 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 _recipient The recipient of the transferred token
     * @param _amount The amount of the token to be transferred
     */
    function _allocateFees(PoolId _poolId, address _recipient, uint _amount) internal {
        // If we don't have fees to allocate, exit early
        if (_amount == 0) return;

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

        balances[_recipient] += _amount;
        emit Deposit(_poolId, _recipient, nativeToken, _amount);
    }

    /**
     * Allows fees to be withdrawn from escrowed fee positions.
     *
     * @param _recipient The recipient of the holder's withdraw
     * @param _unwrap If we want to unwrap the balance from flETH into ETH
     */
    function withdrawFees(address _recipient, bool _unwrap) public {
        // Get the amount of token that is stored in escrow
        uint amount = balances[msg.sender];

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

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

        // Convert the flETH balance held into native ETH
        if (_unwrap) {
            // Handle a withdraw of the withdrawn ETH
            IFLETH(nativeToken).withdraw(amount);
            (bool _sent,) = payable(_recipient).call{value: amount}('');
            require(_sent, 'ETH Transfer Failed');
            emit Withdrawal(msg.sender, _recipient, address(0), amount);
        }
        // Transfer flETH token without unwrapping
        else {
            SafeTransferLib.safeTransfer(nativeToken, _recipient, amount);
            emit Withdrawal(msg.sender, _recipient, nativeToken, amount);
        }
    }

    /**
     * Captures fees following a swap.
     *
     * @param _poolManager The Uniswap V4 {PoolManager}
     * @param _key The key for the pool being swapped against
     * @param _params The swap parameters called in the swap
     * @param _feeCalculator The fee calculator to use for calculations
     * @param _swapFeeCurrency The currency that the fee will be paid in
     * @param _swapAmount The amount of the swap to take fees from
     * @param _feeExemption The optional fee exemption that can overwrite
     *
     * @return swapFee_ The amount of fees taken for the swap
     */
    function _captureSwapFees(
        IPoolManager _poolManager,
        PoolKey calldata _key,
        IPoolManager.SwapParams memory _params,
        IFeeCalculator _feeCalculator,
        Currency _swapFeeCurrency,
        uint _swapAmount,
        FeeExemptions.FeeExemption memory _feeExemption
    ) internal returns (
        uint swapFee_
    ) {
        // If we have an empty swapAmount then we can exit early
        if (_swapAmount == 0) {
            return swapFee_;
        }

        // Get our base swapFee from the FeeCalculator. If we don't have a feeCalculator
        // set, then we need to just use our base rate.
        uint24 baseSwapFee = getPoolFeeDistribution(_key.toId()).swapFee;

        // Check if we have a {FeeCalculator} attached to calculate the fee
        if (address(_feeCalculator) != address(0)) {
            baseSwapFee = _feeCalculator.determineSwapFee(_key, _params, baseSwapFee);
        }

        // If we have a swap fee override, then we want to use that value, only if it is
        // less than the traditionally calculated base swap fee.
        if (_feeExemption.enabled && _feeExemption.flatFee < baseSwapFee) {
            baseSwapFee = _feeExemption.flatFee;
        }

        // If we have an empty swapFee, then we don't need to process further
        if (baseSwapFee == 0) {
            return swapFee_;
        }

        // Determine our fee amount
        swapFee_ = _swapAmount * baseSwapFee / ONE_HUNDRED_PERCENT;

        // Take our swap fees from the {PoolManager}
        _poolManager.take(_swapFeeCurrency, address(this), swapFee_);
    }

    /**
     * Checks if a referrer has been set in the hookData and transfers them their share of
     * the fee directly. This call is made when a swap is taking place and returns the new
     * fee amount after the referrer fee has been removed from it.
     *
     * @param _key The pool key to distribute referrer fees for
     * @param _swapFeeCurrency The currency of the swap fee
     * @param _swapFee The total value of the swap fee
     * @param _hookData Hook data that may contain an encoded referrer address
     *
     * @return referrerFee_ The amount of `swapFeeCurrency` token given to referrer
     */
    function _distributeReferrerFees(
        PoolKey calldata _key,
        Currency _swapFeeCurrency,
        uint _swapFee,
        bytes calldata _hookData
    ) internal returns (uint referrerFee_) {
        // If we have no hook data, then this is a low-gas exit point
        if (_hookData.length == 0) {
            return referrerFee_;
        }

        // Check if we have a specific pool FeeDistribution that overwrites the global value
        PoolId poolId = _key.toId();
        uint24 referrerShare = getPoolFeeDistribution(poolId).referrer;

        // If we have no referrer fee set, then we can exit without paying a fee
        if (referrerShare == 0) {
            return referrerFee_;
        }

        // Decode our referrer address
        (address referrer) = abi.decode(_hookData, (address));

        // If we have a zero address referrer, then we can exit early
        if (referrer == address(0)) {
            return referrerFee_;
        }

        // If we have a referrer then instantly cut them _x%_ of the swap result
        referrerFee_ = _swapFee * feeDistribution.referrer / ONE_HUNDRED_PERCENT;

        // If we don't have referral escrow, send direct to user. We use an unsafe transfer so that
        // invalid addresses don't prevent the process.
        if (address(referralEscrow) == address(0)) {
            _swapFeeCurrency.transfer(referrer, referrerFee_);
            emit ReferrerFeePaid(poolId, referrer, Currency.unwrap(_swapFeeCurrency), referrerFee_);
        }
        // Transfer referrer fees to the escrow contract that they can claim or swap for later
        else {
            _swapFeeCurrency.transfer(address(referralEscrow), referrerFee_);
            referralEscrow.assignTokens(poolId, referrer, Currency.unwrap(_swapFeeCurrency), referrerFee_);
        }
    }

    /**
     * Taking an amount, show the split that each of the different recipients will receive.
     *
     * @dev Fee priority: swapfee -> referrer -> || protocol -> creator -> bidwall ||
     *
     * @param _poolId The PoolId that is having the fee split calculated
     * @param _amount The amount of token being passed in
     *
     * @return bidWall_ The amount that the PBW will receive
     * @return creator_ The amount that the token creator will receive
     * @return protocol_ The amount that the protocol will receive
     */
    function feeSplit(PoolId _poolId, uint _amount) public view returns (uint bidWall_, uint creator_, uint protocol_) {
        // Check if we have a pool overwrite for the FeeDistribution
        FeeDistribution memory _poolFeeDistribution = getPoolFeeDistribution(_poolId);

        // Take the protocol share
        if (_poolFeeDistribution.protocol != 0) {
            protocol_ = _amount * _poolFeeDistribution.protocol / ONE_HUNDRED_PERCENT;
            _amount -= protocol_;
        }

        // The creator is now given their share
        uint24 _creatorFee = creatorFee[_poolId];
        if (_creatorFee != 0) {
            creator_ = _amount * _creatorFee / ONE_HUNDRED_PERCENT;
            _amount -= creator_;
        }

        // The bidwall will receive the remaining allocation
        bidWall_ = _amount;
    }

    /**
     * Updates the {ReferralEscrow} contract that will store referrer fees.
     *
     * @param _referralEscrow The new {ReferralEscrow} contract address
     */
    function setReferralEscrow(address payable _referralEscrow) public onlyOwner {
        // Update our {ReferralEscrow} address
        referralEscrow = ReferralEscrow(_referralEscrow);
        emit ReferralEscrowUpdated(_referralEscrow);
    }

    /**
     * Allows the governing contract to make global changes to the fees.
     *
     * @param _feeDistribution The new FeeDistribution value
     */
    function setFeeDistribution(FeeDistribution memory _feeDistribution) public onlyOwner {
        _validateFeeDistribution(_feeDistribution);

        // Update our FeeDistribution struct
        feeDistribution = _feeDistribution;
        emit FeeDistributionUpdated(_feeDistribution);
    }

    /**
     * Allows the $FLAY token governance to set the global protocol fee.
     *
     * @param _protocol New protocol fee
     */
    function setProtocolFeeDistribution(uint24 _protocol) public {
        // Check that the caller is the $FLAY governance
        if (msg.sender != flayGovernance) {
            revert Unauthorized();
        }

        // Validate the range that the protocol fee can be
        if (_protocol > MAX_PROTOCOL_ALLOCATION) {
            revert ProtocolFeeInvalid();
        }

        // Update only the protocol fee in our `FeeDistribution`
        feeDistribution.protocol = _protocol;
        emit FeeDistributionUpdated(feeDistribution);
    }

    /**
     * Allows the governing contract to make pool specific changes to the fees.
     *
     * @param _poolId The PoolId being updated
     * @param _feeDistribution The new FeeDistribution value
     */
    function setPoolFeeDistribution(PoolId _poolId, FeeDistribution memory _feeDistribution) public onlyOwner {
        _validateFeeDistribution(_feeDistribution);

        // Update our FeeDistribution struct
        poolFeeDistribution[_poolId] = _feeDistribution;
        emit PoolFeeDistributionUpdated(_poolId, _feeDistribution);
    }

    /**
     * Internally validates FeeDistribution structs to ensure they are valid.
     *
     * @dev If the struct is not valid, then the call will be reverted.
     *
     * @param _feeDistribution The FeeDistribution to be validated
     */
    function _validateFeeDistribution(FeeDistribution memory _feeDistribution) internal pure {
        // Ensure our swap fee is below 100%
        if (_feeDistribution.swapFee > ONE_HUNDRED_PERCENT) {
            revert SwapFeeInvalid();
        }

        // Ensure our referrer fee is below 100%
        if (_feeDistribution.referrer > ONE_HUNDRED_PERCENT) {
            revert ReferrerFeeInvalid();
        }

        // Ensure our protocol fee is below 10%
        if (_feeDistribution.protocol > MAX_PROTOCOL_ALLOCATION) {
            revert ProtocolFeeInvalid();
        }
    }

    /**
     * Allows an owner to update the {IFeeCalculator} used to determine the swap fee.
     *
     * @param _feeCalculator The new {IFeeCalculator} to use
     */
    function setFeeCalculator(IFeeCalculator _feeCalculator) public onlyOwner {
        feeCalculator = _feeCalculator;
        emit FeeCalculatorUpdated(address(_feeCalculator));
    }

    /**
     * Allows an owner to update the {IFeeCalculator} used during FairLaunch to determine the
     * swap fee.
     *
     * @param _feeCalculator The new {IFeeCalculator} to use
     */
    function setFairLaunchFeeCalculator(IFeeCalculator _feeCalculator) public onlyOwner {
        fairLaunchFeeCalculator = _feeCalculator;
        emit FairLaunchFeeCalculatorUpdated(address(_feeCalculator));
    }

    /**
     * Gets the distribution for a pool by checking to see if a pool has it's own FeeDistribution. If
     * it does then this is used, but if it isn't then it will fallback on the global FeeDistribution.
     *
     * @param _poolId The PoolId being updated
     *
     * @return feeDistribution_ The FeeDistribution applied to the pool
     */
    function getPoolFeeDistribution(PoolId _poolId) public view returns (FeeDistribution memory feeDistribution_) {
        feeDistribution_ = (poolFeeDistribution[_poolId].active) ? poolFeeDistribution[_poolId] : feeDistribution;
    }

    /**
     * Gets the {IFeeCalculator} contract that should be used based on which are set, and if the
     * pool is currently in FairLaunch or not.
     *
     * @dev This could return a zero address if no fee calculators have been set
     *
     * @param _isFairLaunch If the pool is currently in FairLaunch
     *
     * @return IFeeCalculator The IFeeCalculator to use
     */
    function getFeeCalculator(bool _isFairLaunch) public view returns (IFeeCalculator) {
        if (_isFairLaunch && address(fairLaunchFeeCalculator) != address(0)) {
            return fairLaunchFeeCalculator;
        }

        return feeCalculator;
    }

    /**
     * Allows the contract to receive ETH when withdrawn from the flETH token.
     */
    receive () external payable {}

}
合同源代码
文件 14 的 67:FeeExemptions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {LPFeeLibrary} from '@uniswap/v4-core/src/libraries/LPFeeLibrary.sol';


/**
 * This contract will allow for specific addresses to have reduced or nullified fees for all
 * swaps transactions within the pool. These will be allocated to partners that need a more
 * consistent underlying price to ensure their protocol can operate using Flaunch pools.
 */
contract FeeExemptions is Ownable {

    using LPFeeLibrary for uint24;

    error FeeExemptionInvalid(uint24 _invalidFee, uint24 _maxFee);
    error NoBeneficiaryExemption(address _beneficiary);

    /// Emitted when a beneficiary exemption is set or updated
    event BeneficiaryFeeSet(address _beneficiary, uint24 _flatFee);

    /// Emitted when a beneficiary exemption is removed
    event BeneficiaryFeeRemoved(address _beneficiary);

    /**
     * Defines the fee exemption that a beneficiary will receive if enabled.
     *
     * @member flatFee The flat fee value that the `_beneficiary` will receive
     * @member enabled If the exemption is enabled
     */
    struct FeeExemption {
        uint24 flatFee;
        bool enabled;
    }

    /// Stores a mapping of beneficiaries and that flat fee exemptions
    mapping (address _beneficiary => FeeExemption _exemption) internal _feeExemption;

    /**
     * Registers the caller as the contract owner.
     *
     * @param _protocolOwner The initial EOA owner of the contract
     */
    constructor (address _protocolOwner) {
        // Grant ownership permissions to the caller
        _initializeOwner(_protocolOwner);
    }

    /**
     * Gets the `FeeExemption` data struct for a beneficiary address.
     *
     * @param _beneficiary The address of the beneficiary
     *
     * @return The FeeExemption struct for the beneficiary
     */
    function feeExemption(address _beneficiary) public view returns (FeeExemption memory) {
        return _feeExemption[_beneficiary];
    }

    /**
     * Set our beneficiary's flat fee rate across all pools. If a beneficiary is set, then
     * the fee processed during a swap will be overwritten if this fee exemption value is
     * lower than the otherwise determined fee.
     *
     * @param _beneficiary The swap `sender` that will receive the exemption
     * @param _flatFee The flat fee value that the `_beneficiary` will receive
     */
    function setFeeExemption(address _beneficiary, uint24 _flatFee) public onlyOwner {
        // Ensure that our custom fee conforms to Uniswap V4 requirements
        if (!_flatFee.isValid()) revert FeeExemptionInvalid(_flatFee, LPFeeLibrary.MAX_LP_FEE);

        _feeExemption[_beneficiary] = FeeExemption(_flatFee, true);
        emit BeneficiaryFeeSet(_beneficiary, _flatFee);
    }

    /**
     * Removes a beneficiary fee exemption.
     *
     * @dev If the `beneficiary` does not already have an exemption, this call will revert.
     *
     * @param _beneficiary The address to remove the fee exemption from
     */
    function removeFeeExemption(address _beneficiary) public onlyOwner {
        // Check that a beneficiary is currently enabled
        if (!_feeExemption[_beneficiary].enabled) revert NoBeneficiaryExemption(_beneficiary);

        delete _feeExemption[_beneficiary];
        emit BeneficiaryFeeRemoved(_beneficiary);
    }

    /**
     * Override to return true to make `_initializeOwner` prevent double-initialization.
     *
     * @return bool Set to `true` to prevent owner being reinitialized.
     */
    function _guardInitializeOwner() internal pure override returns (bool) {
        return true;
    }

}
合同源代码
文件 15 的 67:FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
合同源代码
文件 16 的 67:FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}
合同源代码
文件 17 的 67:FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}
合同源代码
文件 18 的 67:Hooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}
合同源代码
文件 19 的 67:IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
合同源代码
文件 20 的 67: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);
}
合同源代码
文件 21 的 67:IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
合同源代码
文件 22 的 67:IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}
合同源代码
文件 23 的 67:IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
合同源代码
文件 24 的 67:IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
合同源代码
文件 25 的 67:IFLETH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;


interface IFLETH {

    function deposit(uint _amount) external payable;

    function withdraw(uint _amount) external;

    function allowance(address _owner, address _spender) external returns (uint);

    function approve(address _spender, uint _amount) external returns (bool);

}
合同源代码
文件 26 的 67:IFeeCalculator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

interface IFeeCalculator {

    function determineSwapFee(PoolKey memory _poolKey, IPoolManager.SwapParams memory _params, uint24 _baseFee) external view returns (uint24 swapFee_);

    function trackSwap(address _sender, PoolKey calldata _poolKey, IPoolManager.SwapParams calldata _params, BalanceDelta _delta, bytes calldata _hookData) external;

    function setFlaunchParams(PoolId _poolId, bytes calldata _params) external;

}
合同源代码
文件 27 的 67:IFlaunch.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {PositionManager} from '@flaunch/PositionManager.sol';


interface IFlaunch {

    function flaunch(PositionManager.FlaunchParams calldata) external returns (address memecoin_, address payable memecoinTreasury_, uint tokenId_);

}
合同源代码
文件 28 的 67:IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4, BeforeSwapDelta, uint24);

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

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

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}
合同源代码
文件 29 的 67:IImmutableState.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

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

/// @title Interface for ImmutableState
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}
合同源代码
文件 30 的 67:IInitialPrice.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;


interface IInitialPrice {

    function getFlaunchingFee(address _sender, bytes calldata _initialPriceParams) external view returns (uint);

    function getMarketCap(bytes calldata _initialPriceParams) external view returns (uint);

    function getSqrtPriceX96(address _sender, bool _flipped, bytes calldata _initialPriceParams) external view returns (uint160);

}
合同源代码
文件 31 的 67:IMemecoin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {IERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';


interface IMemecoin is IERC20Upgradeable {

    function initialize(string calldata name_, string calldata symbol_, string calldata tokenUri_) external;

    function mint(address _to, uint _amount) external;

    function burn(uint value) external;

    function burnFrom(address account, uint value) external;

    function setMetadata(string calldata name_, string calldata symbol_) external;

    function name() external view returns (string memory);

    function symbol() external view returns (string memory);

    function tokenURI() external view returns (string memory);

    function clock() external view returns (uint48);

    function creator() external view returns (address);

    function treasury() external view returns (address payable);

}
合同源代码
文件 32 的 67:IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

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

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

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

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

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

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

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

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

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

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

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
合同源代码
文件 33 的 67:IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}
合同源代码
文件 34 的 67:ISubscriber.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;

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


/**
 * Interface that a Subscriber contract should implement to receive updates from the Flaunch
 * {PositionManager}.
 */
interface ISubscriber {

    function subscribe(bytes memory data) external returns (bool);

    function unsubscribe() external;

    function notify(PoolId _poolId, bytes4 _key, bytes calldata _data) external;

}
合同源代码
文件 35 的 67:ITreasuryAction.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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


interface ITreasuryAction {

    event ActionExecuted(PoolKey _poolKey, int _token0, int _token1);

    function execute(PoolKey memory _poolKey, bytes memory _data) external;

}
合同源代码
文件 36 的 67:IUnlockCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
    /// @param data The data that was passed to the call to unlock
    /// @return Any data that you want to be returned from the unlock call
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}
合同源代码
文件 37 的 67:ImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

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

/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
    /// @inheritdoc IImmutableState
    IPoolManager public immutable poolManager;

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
    }
}
合同源代码
文件 38 的 67:Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Initializable mixin for the upgradeable contracts.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Initializable.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/proxy/utils/Initializable.sol)
abstract contract Initializable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

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

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

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

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

    /// @dev `keccak256(bytes("Initialized(uint64)"))`.
    bytes32 private constant _INTIALIZED_EVENT_SIGNATURE =
        0xc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2;

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

    /// @dev The default initializable slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_INITIALIZABLE_SLOT")))))`.
    ///
    /// Bits Layout:
    /// - [0]     `initializing`
    /// - [1..64] `initializedVersion`
    bytes32 private constant _INITIALIZABLE_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffbf601132;

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

    /// @dev Override to return a custom storage slot if required.
    function _initializableSlot() internal pure virtual returns (bytes32) {
        return _INITIALIZABLE_SLOT;
    }

    /// @dev Guards an initializer function so that it can be invoked at most once.
    ///
    /// You can guard a function with `onlyInitializing` such that it can be called
    /// through a function guarded with `initializer`.
    ///
    /// This is similar to `reinitializer(1)`, except that in the context of a constructor,
    /// an `initializer` guarded function can be invoked multiple times.
    /// This can be useful during testing and is not expected to be used in production.
    ///
    /// Emits an {Initialized} event.
    modifier initializer() virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            let i := sload(s)
            // Set `initializing` to 1, `initializedVersion` to 1.
            sstore(s, 3)
            // If `!(initializing == 0 && initializedVersion == 0)`.
            if i {
                // If `!(address(this).code.length == 0 && initializedVersion == 1)`.
                if iszero(lt(extcodesize(address()), eq(shr(1, i), 1))) {
                    mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
                    revert(0x1c, 0x04)
                }
                s := shl(shl(255, i), s) // Skip initializing if `initializing == 1`.
            }
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            if s {
                // Set `initializing` to 0, `initializedVersion` to 1.
                sstore(s, 2)
                // Emit the {Initialized} event.
                mstore(0x20, 1)
                log1(0x20, 0x20, _INTIALIZED_EVENT_SIGNATURE)
            }
        }
    }

    /// @dev Guards an reinitialzer function so that it can be invoked at most once.
    ///
    /// You can guard a function with `onlyInitializing` such that it can be called
    /// through a function guarded with `reinitializer`.
    ///
    /// Emits an {Initialized} event.
    modifier reinitializer(uint64 version) virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            version := and(version, 0xffffffffffffffff) // Clean upper bits.
            let i := sload(s)
            // If `initializing == 1 || initializedVersion >= version`.
            if iszero(lt(and(i, 1), lt(shr(1, i), version))) {
                mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
                revert(0x1c, 0x04)
            }
            // Set `initializing` to 1, `initializedVersion` to `version`.
            sstore(s, or(1, shl(1, version)))
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            // Set `initializing` to 0, `initializedVersion` to `version`.
            sstore(s, shl(1, version))
            // Emit the {Initialized} event.
            mstore(0x20, version)
            log1(0x20, 0x20, _INTIALIZED_EVENT_SIGNATURE)
        }
    }

    /// @dev Guards a function such that it can only be called in the scope
    /// of a function guarded with `initializer` or `reinitializer`.
    modifier onlyInitializing() virtual {
        _checkInitializing();
        _;
    }

    /// @dev Reverts if the contract is not initializing.
    function _checkInitializing() internal view virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(and(1, sload(s))) {
                mstore(0x00, 0xd7e6bcf8) // `NotInitializing()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Locks any future initializations by setting the initialized version to `2**64 - 1`.
    ///
    /// Calling this in the constructor will prevent the contract from being initialized
    /// or reinitialized. It is recommended to use this to lock implementation contracts
    /// that are designed to be called through proxies.
    ///
    /// Emits an {Initialized} event the first time it is successfully called.
    function _disableInitializers() internal virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            let i := sload(s)
            if and(i, 1) {
                mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
                revert(0x1c, 0x04)
            }
            let uint64max := shr(192, s) // Computed to save bytecode.
            if iszero(eq(shr(1, i), uint64max)) {
                // Set `initializing` to 0, `initializedVersion` to `2**64 - 1`.
                sstore(s, shl(1, uint64max))
                // Emit the {Initialized} event.
                mstore(0x20, uint64max)
                log1(0x20, 0x20, _INTIALIZED_EVENT_SIGNATURE)
            }
        }
    }

    /// @dev Returns the highest version that has been initialized.
    function _getInitializedVersion() internal view virtual returns (uint64 version) {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            version := shr(1, sload(s))
        }
    }

    /// @dev Returns whether the contract is currently initializing.
    function _isInitializing() internal view virtual returns (bool result) {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            result := and(1, sload(s))
        }
    }
}
合同源代码
文件 39 的 67:InternalSwapPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {Currency, CurrencyLibrary} from '@uniswap/v4-core/src/types/Currency.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {PoolId, PoolIdLibrary} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {StateLibrary} from '@uniswap/v4-core/src/libraries/StateLibrary.sol';
import {SwapMath} from '@uniswap/v4-core/src/libraries/SwapMath.sol';
import {TickMath} from '@uniswap/v4-core/src/libraries/TickMath.sol';

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


/**
 * This frontruns Uniswap to sell undesired token amounts from our fees into desired tokens
 * ahead of our fee distribution. This acts as a partial orderbook to remove impact against
 * our pool.
 */
abstract contract InternalSwapPool {

    using CurrencyLibrary for Currency;
    using CurrencySettler for Currency;
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;

    /// Emitted when a pool has been allocated fees on either side of the position
    event PoolFeesReceived(PoolId indexed _poolId, uint _amount0, uint _amount1);

    /// Emitted when a pool fees have been distributed to stakers
    event PoolFeesDistributed(PoolId indexed _poolId, uint _donateAmount, uint _creatorAmount, uint _bidWallAmount, uint _governanceAmount, uint _protocolAmount);

    /// Emitted when pool fees have been internally swapped
    event PoolFeesSwapped(PoolId indexed _poolId, bool zeroForOne, uint _amount0, uint _amount1);

    /**
     * Contains amounts for both the currency0 and currency1 values of a UV4 Pool.
     */
    struct ClaimableFees {
        uint amount0;
        uint amount1;
    }

    /// Maps the amount of claimable tokens that are available to be `distributed`
    /// for a `PoolId`.
    mapping (PoolId _poolId => ClaimableFees _fees) internal _poolFees;

    /**
     * Provides the {ClaimableFees} for a pool key.
     *
     * @param _poolKey The PoolKey to check
     *
     * @return The {ClaimableFees} for the PoolKey
     */
    function poolFees(PoolKey memory _poolKey) public view returns (ClaimableFees memory) {
        return _poolFees[_poolKey.toId()];
    }

    /**
     * Allows for fees to be deposited against a pool to be distributed.
     *
     * @dev Our `amount0` must always refer to the amount of the native token provided. The
     * `amount1` will always be the underlying {Memecoin}. The internal logic of
     * this function will rearrange them to match the `PoolKey` if needed.
     *
     * @param _poolKey The PoolKey to deposit against
     * @param _amount0 The amount of eth equivalent to deposit
     * @param _amount1 The amount of underlying token to deposit
     */
    function _depositFees(PoolKey memory _poolKey, uint _amount0, uint _amount1) internal {
        PoolId _poolId = _poolKey.toId();

        _poolFees[_poolId].amount0 += _amount0;
        _poolFees[_poolId].amount1 += _amount1;

        emit PoolFeesReceived(_poolId, _amount0, _amount1);
    }

    /**
     * Check if we have any token1 fee tokens that we can use to fill the swap before it hits
     * the Uniswap pool. This prevents the pool from being affected and reduced gas costs.
     *
     * This frontruns UniSwap to sell undesired token amounts from our fees into desired tokens
     * ahead of our fee distribution. This acts as a partial orderbook to remove impact against
     * our pool.
     *
     * @param _poolManager The Uniswap V4 {PoolManager} contract
     * @param _key The PoolKey that is being swapped against
     * @param _params The swap parameters
     * @param _nativeIsZero If our native token is `currency0`
     *
     * @return ethIn_ The ETH taken for the swap
     * @return tokenOut_ The tokens given for the swap
     */
    function _internalSwap(
        IPoolManager _poolManager,
        PoolKey calldata _key,
        IPoolManager.SwapParams memory _params,
        bool _nativeIsZero
    ) internal returns (
        uint ethIn_,
        uint tokenOut_
    ) {
        PoolId poolId = _key.toId();

        // Load our PoolFees as storage as we will manipulate them later if we trigger
        ClaimableFees storage pendingPoolFees = _poolFees[poolId];
        if (pendingPoolFees.amount1 == 0) {
            return (ethIn_, tokenOut_);
        }

        // We only want to process our internal swap if we are buying non-ETH tokens with ETH. This
        // will allow us to correctly calculate the amount of token to replace.
        if (_nativeIsZero != _params.zeroForOne) {
            return (ethIn_, tokenOut_);
        }

        // Get the current price for our pool
        (uint160 sqrtPriceX96,,,) = _poolManager.getSlot0(poolId);

        // Since we have a positive amountSpecified, we can determine the maximum
        // amount that we can transact from our pool fees.
        if (_params.amountSpecified >= 0) {
            // Take the max value of either the pool fees or the amount specified to swap for
            uint amountSpecified = (uint(_params.amountSpecified) > pendingPoolFees.amount1)
                ? pendingPoolFees.amount1
                : uint(_params.amountSpecified);

            // Capture the amount of desired token required at the current pool state to
            // purchase the amount of token speicified, capped by the pool fees available.
            (, ethIn_, tokenOut_, ) = SwapMath.computeSwapStep({
                sqrtPriceCurrentX96: sqrtPriceX96,
                sqrtPriceTargetX96: _params.sqrtPriceLimitX96,
                liquidity: _poolManager.getLiquidity(poolId),
                amountRemaining: int(amountSpecified),
                feePips: 0
            });
        }
        // As we have a negative amountSpecified, this means that we are spending any amount
        // of token to get a specific amount of undesired token.
        else {
            // To calculate the amount of tokens that we can receive, we first pass in the amount
            // of ETH that we are requesting to spend. We need to invert the `sqrtPriceTargetX96`
            // as our swap step computation is essentially calculating the opposite direction.
            (, tokenOut_, ethIn_, ) = SwapMath.computeSwapStep({
                sqrtPriceCurrentX96: sqrtPriceX96,
                sqrtPriceTargetX96: _params.zeroForOne ? TickMath.MAX_SQRT_PRICE - 1 : TickMath.MIN_SQRT_PRICE + 1,
                liquidity: _poolManager.getLiquidity(poolId),
                amountRemaining: int(-_params.amountSpecified),
                feePips: 0
            });

            // If we cannot fulfill the full amount of the internal orderbook, then we want to
            // calculate the percentage of which we can utilize.
            if (tokenOut_ > pendingPoolFees.amount1) {
                ethIn_ = (pendingPoolFees.amount1 * ethIn_) / tokenOut_;
                tokenOut_ = pendingPoolFees.amount1;
            }
        }

        // If nothing has happened, we can exit
        if (ethIn_ == 0 && tokenOut_ == 0) {
            return (ethIn_, tokenOut_);
        }

        // Reduce the amount of fees that have been extracted from the pool and converted
        // into ETH fees.
        pendingPoolFees.amount0 += ethIn_;
        pendingPoolFees.amount1 -= tokenOut_;

        // Take the required ETH tokens from the {PoolManager} to settle the currency change. The
        // `tokensOut_` are settled externally to this call.
        _poolManager.take(!_nativeIsZero ? _key.currency1 : _key.currency0, address(this), ethIn_);
        (!_nativeIsZero ? _key.currency0 : _key.currency1).settle(_poolManager, address(this), tokenOut_, false);

        // Capture the swap cost that we captured from our drip
        emit PoolFeesSwapped(poolId, _params.zeroForOne, ethIn_, tokenOut_);
    }

}
合同源代码
文件 40 的 67:LPFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

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

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

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

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

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

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

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

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

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}
合同源代码
文件 41 的 67:LiquidityAmounts.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        }
    }
}
合同源代码
文件 42 的 67:LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}
合同源代码
文件 43 的 67:Lock.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

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

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

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

    function isUnlocked() internal view returns (bool unlocked) {
        assembly ("memory-safe") {
            unlocked := tload(IS_UNLOCKED_SLOT)
        }
    }
}
合同源代码
文件 44 的 67:MemecoinFinder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

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


/**
 * A helper library that finds the memecoin contract and it's associated treasury and
 * creator for a given {PoolKey}.
 */
library MemecoinFinder {

    /**
     * Finds the {IMemecoin} attached to a `PoolKey` by assuming it is not the `_nativeToken`.
     *
     * @param _key The `PoolKey` that is being discovered
     * @param _nativeToken The native token used by Flaunch
     *
     * @return The {IMemecoin} contract from the `PoolKey`
     */
    function memecoin(PoolKey memory _key, address _nativeToken) internal pure returns (IMemecoin) {
        return IMemecoin(
            Currency.unwrap(
                Currency.wrap(_nativeToken) == _key.currency0 ? _key.currency1 : _key.currency0
            )
        );
    }

}
合同源代码
文件 45 的 67:MemecoinTreasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

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

import {MemecoinFinder} from '@flaunch/types/MemecoinFinder.sol';
import {PositionManager} from '@flaunch/PositionManager.sol';
import {TreasuryActionManager} from '@flaunch/treasury/ActionManager.sol';

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


/**
 * Allows approved actions to be executed by the `PoolCreator` for their specific pool, using
 * tokens in their {MemecoinTreasury}.
 */
contract MemecoinTreasury is Initializable, ReentrancyGuard {

    using MemecoinFinder for PoolKey;
    using PoolIdLibrary for PoolKey;

    error ActionNotApproved();
    error Unauthorized();

    event ActionExecuted(address indexed _action, PoolKey _poolKey, bytes _data);

    /// The native token used by the Flaunch {PositionManager}
    address public nativeToken;

    /// The {TreasuryActionManager} contract that stores approved actions
    TreasuryActionManager public actionManager;

    /// The {PositionManager} that fees will be claimed from
    PositionManager public positionManager;

    /// The `PoolKey` that is attached to this {MemecoinTreasury}
    PoolKey public poolKey;

    /**
     * Sets the Flaunch {PositionManager} and native token, and initializes with the `PoolKey`.
     *
     * @param _actionManager The {TreasuryActionManager} contract address
     * @param _nativeToken The native token address used by Flaunch
     * @param _poolKey The pool that is being actioned against
     */
    function initialize(address payable _positionManager, address _actionManager, address _nativeToken, PoolKey memory _poolKey) public initializer {
        actionManager = TreasuryActionManager(_actionManager);
        nativeToken = _nativeToken;
        poolKey = _poolKey;
        positionManager = PositionManager(_positionManager);
    }

    /**
     * Executes an approved {ITreasuryAction}.
     *
     * @dev Only to `PoolCreator` can make this call, otherwise reverted with `Unauthorized`
     *
     * @param _action The {ITreasuryAction} address to execute
     * @param _data Additional data that the {ITreasuryAction} may require
     */
    function executeAction(address _action, bytes memory _data) public nonReentrant {
        // Ensure the action is approved
        if (!actionManager.approvedActions(_action)) revert ActionNotApproved();

        // Make sure the caller is the owner of the corresponding ERC721
        address poolCreator = poolKey.memecoin(nativeToken).creator();
        if (poolCreator != msg.sender) revert Unauthorized();

        IERC20 token0 = IERC20(Currency.unwrap(poolKey.currency0));
        IERC20 token1 = IERC20(Currency.unwrap(poolKey.currency1));

        // Approve all tokens to be used before execution
        token0.approve(_action, type(uint).max);
        token1.approve(_action, type(uint).max);

        // Claim fees before executing, keeping as fleth to ensure full treasury balances
        claimFees();

        // Call the execute function on the action contract
        ITreasuryAction(_action).execute(poolKey, _data);
        emit ActionExecuted(_action, poolKey, _data);

        // Unapprove all tokens after execution
        token0.approve(_action, 0);
        token1.approve(_action, 0);
    }

    /**
     * Claims any pending fees allocated to the {MemecoinTreasury}. We do not unwrap the flETH
     * in our claim call to ensure that we keep two persisted tokens as per the {PoolKey}.
     *
     * @dev This call does not require protection and can be called by anyone
     */
    function claimFees() public {
        positionManager.withdrawFees(address(this), false);
    }

    /**
     * Allows the contract to receive ETH when withdrawn from the flETH token.
     */
    receive () external payable {}

}
合同源代码
文件 46 的 67:NonzeroDeltaCount.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

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

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

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

    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
    function decrement() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := sub(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }
}
合同源代码
文件 47 的 67:Notifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';

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

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


/**
 * Notifier is used to opt in to sending updates to external contracts about position modifications
 * against a managed pool.
 */
contract Notifier is Ownable {

    using EnumerableSet for EnumerableSet.AddressSet;

    error SubscriptionReverted();

    event Subscription(address _subscriber);
    event Unsubscription(address _subscriber);

    /// Store a list of subscribed contracts
    EnumerableSet.AddressSet internal subscribers;

    /// Store the {PositionManager} that created this contract
    address internal _positionManager;

    /**
     * Registers the caller as the contract owner.
     *
     * @param _protocolOwner The initial EOA owner of the contract
     */
    constructor (address _protocolOwner) {
        _positionManager = msg.sender;

        // Grant ownership permissions to the caller
        _initializeOwner(_protocolOwner);
    }

    /**
     * Subscribes a contract to receive updates regarding pool modifications.
     *
     * @param _subscriber The address of the contract being subscribed
     * @param _data Any data passed to subscription call
     */
    function subscribe(address _subscriber, bytes calldata _data) public onlyOwner {
        // Add the subscriber to our array, which returns true if address is not already
        // present in our EnumerableSet.
        if (subscribers.add(_subscriber)) {
            // Check if we receive a success response. If not, we cannot subscribe the address
            if (!ISubscriber(_subscriber).subscribe(_data)) {
                revert SubscriptionReverted();
            }

            emit Subscription(_subscriber);
        }
    }

    /**
     * Removes a subscriber based on the index they were stored at.
     *
     * @param _subscriber The address of the subscriber to unsubscribe
     */
    function unsubscribe(address _subscriber) public onlyOwner {
        // If we have referenced an empty index, prevent futher processing
        if (!subscribers.contains(_subscriber)) {
            return;
        }

        // Delete our subscriber by the index
        subscribers.remove(_subscriber);

        // Unsubscribe our subscriber, catching the revert in case the contract has become corrupted
        try ISubscriber(_subscriber).unsubscribe() {} catch {}
        emit Unsubscription(_subscriber);
    }

    /**
     * Send our pool modification notification to all subscribers.
     *
     * @param _poolId The PoolId that was modified
     */
    function notifySubscribers(PoolId _poolId, bytes4 _key, bytes calldata _data) public {
        // Ensure that the {PositionManager} sent this notification
        require(msg.sender == _positionManager);

        // Iterate over all subscribers to pass on data
        uint subscribersLength = subscribers.length();
        for (uint i; i < subscribersLength; ++i) {
            ISubscriber(subscribers.at(i)).notify(_poolId, _key, _data);
        }
    }

}
合同源代码
文件 48 的 67: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();
        _;
    }
}
合同源代码
文件 49 的 67:ParseBytes.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

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

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}
合同源代码
文件 50 的 67: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)
        }
    }
}
合同源代码
文件 51 的 67: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;
}
合同源代码
文件 52 的 67:PoolSwap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {Hooks, IHooks} from '@uniswap/v4-core/src/libraries/Hooks.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {IUnlockCallback} from '@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {TransientStateLibrary} from '@uniswap/v4-core/src/libraries/TransientStateLibrary.sol';

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


/**
 * Handles swaps against Uniswap V4 pools.
 *
 * @dev Copied from the `v4-core` `PoolSwapTest.sol` contract and simplified to suit Flaunch
 * requirements.
 */
contract PoolSwap is IUnlockCallback {

    using CurrencySettler for Currency;
    using Hooks for IHooks;
    using TransientStateLibrary for IPoolManager;

    /**
     * Stores information to be passed back when unlocking the callback.
     *
     * @member sender The sender of the swap
     * @member key The poolKey being swapped against
     * @member params Swap parameters
     * @member referrer An optional referrer
     */
    struct CallbackData {
        address sender;
        PoolKey key;
        IPoolManager.SwapParams params;
        address referrer;
    }

    /// The Uniswap V4 {PoolManager} contract
    IPoolManager public immutable manager;

    /**
     * Register our Uniswap V4 {PoolManager}.
     *
     * @param _manager The Uniswap V4 {PoolManager}
     */
    constructor (IPoolManager _manager) {
        manager = _manager;
    }

    /**
     * Actions a swap using the SwapParams provided against the PoolKey without a referrer.
     *
     * @param _key The PoolKey to swap against
     * @param _params The parameters for the swap
     *
     * @return The BalanceDelta of the swap
     */
    function swap(PoolKey memory _key, IPoolManager.SwapParams memory _params) public payable returns (BalanceDelta) {
        return swap(_key, _params, address(0));
    }

    /**
     * Actions a swap using the SwapParams provided against the PoolKey with a referrer.
     *
     * @param _key The PoolKey to swap against
     * @param _params The parameters for the swap
     * @param _referrer The referrer of the swap
     *
     * @return delta_ The BalanceDelta of the swap
     */
    function swap(PoolKey memory _key, IPoolManager.SwapParams memory _params, address _referrer) public payable returns (BalanceDelta delta_) {
        delta_ = abi.decode(
            manager.unlock(abi.encode(CallbackData(msg.sender, _key, _params, _referrer))),
            (BalanceDelta)
        );
    }

    /**
     * Performs the swap call using information from the CallbackData.
     */
    function unlockCallback(bytes calldata rawData) external returns (bytes memory) {
        // Ensure that the {PoolManager} has sent the message
        require(msg.sender == address(manager));

        // Decode our CallbackData
        CallbackData memory data = abi.decode(rawData, (CallbackData));

        int deltaBefore0 = manager.currencyDelta(address(this), data.key.currency0);
        int deltaBefore1 = manager.currencyDelta(address(this), data.key.currency1);

        require(deltaBefore0 == 0, 'deltaBefore0 is not equal to 0');
        require(deltaBefore1 == 0, 'deltaBefore1 is not equal to 0');

        // Action the swap, converting the referrer to bytes so that we exit earlier in our
        // subsequent hook calls.
        BalanceDelta delta = manager.swap({
            key: data.key,
            params: data.params,
            hookData: data.referrer == address(0) ? bytes('') : abi.encode(data.referrer)
        });

        int deltaAfter0 = manager.currencyDelta(address(this), data.key.currency0);
        int deltaAfter1 = manager.currencyDelta(address(this), data.key.currency1);

        // Sense checking of the request for safety
        if (data.params.zeroForOne) {
            if (data.params.amountSpecified < 0) {
                // exact input, 0 for 1
                require(
                    deltaAfter0 >= data.params.amountSpecified,
                    'deltaAfter0 is not greater than or equal to data.params.amountSpecified'
                );
                require(delta.amount0() == deltaAfter0, 'delta.amount0() is not equal to deltaAfter0');
                require(deltaAfter1 >= 0, 'deltaAfter1 is not greater than or equal to 0');
            } else {
                // exact output, 0 for 1
                require(deltaAfter0 <= 0, 'deltaAfter0 is not less than or equal to zero');
                require(delta.amount1() == deltaAfter1, 'delta.amount1() is not equal to deltaAfter1');
                require(
                    deltaAfter1 <= data.params.amountSpecified,
                    'deltaAfter1 is not less than or equal to data.params.amountSpecified'
                );
            }
        } else {
            if (data.params.amountSpecified < 0) {
                // exact input, 1 for 0
                require(
                    deltaAfter1 >= data.params.amountSpecified,
                    'deltaAfter1 is not greater than or equal to data.params.amountSpecified'
                );
                require(delta.amount1() == deltaAfter1, 'delta.amount1() is not equal to deltaAfter1');
                require(deltaAfter0 >= 0, 'deltaAfter0 is not greater than or equal to 0');
            } else {
                // exact output, 1 for 0
                require(deltaAfter1 <= 0, 'deltaAfter1 is not less than or equal to 0');
                require(delta.amount0() == deltaAfter0, 'delta.amount0() is not equal to deltaAfter0');
                require(
                    deltaAfter0 <= data.params.amountSpecified,
                    'deltaAfter0 is not less than or equal to data.params.amountSpecified'
                );
            }
        }

        if (deltaAfter0 < 0) {
            data.key.currency0.settle(manager, data.sender, uint(-deltaAfter0), false);
        }
        if (deltaAfter1 < 0) {
            data.key.currency1.settle(manager, data.sender, uint(-deltaAfter1), false);
        }
        if (deltaAfter0 > 0) {
            data.key.currency0.take(manager, data.sender, uint(deltaAfter0), false);
        }
        if (deltaAfter1 > 0) {
            data.key.currency1.take(manager, data.sender, uint(deltaAfter1), false);
        }

        return abi.encode(delta);
    }

}
合同源代码
文件 53 的 67:Position.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}
合同源代码
文件 54 的 67:PositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from '@uniswap/v4-core/src/types/BeforeSwapDelta.sol';
import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {Hooks, IHooks} from '@uniswap/v4-core/src/libraries/Hooks.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {PoolId, PoolIdLibrary} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {SafeCast} from '@uniswap/v4-core/src/libraries/SafeCast.sol';
import {StateLibrary} from '@uniswap/v4-core/src/libraries/StateLibrary.sol';

import {BaseHook} from '@uniswap-periphery/base/hooks/BaseHook.sol';

import {BidWall} from '@flaunch/bidwall/BidWall.sol';
import {CurrencySettler} from '@flaunch/libraries/CurrencySettler.sol';
import {FairLaunch} from '@flaunch/hooks/FairLaunch.sol';
import {FeeDistributor} from '@flaunch/hooks/FeeDistributor.sol';
import {FeeExemptions} from '@flaunch/hooks/FeeExemptions.sol';
import {InternalSwapPool} from '@flaunch/hooks/InternalSwapPool.sol';
import {MemecoinFinder} from '@flaunch/types/MemecoinFinder.sol';
import {MemecoinTreasury} from '@flaunch/treasury/MemecoinTreasury.sol';
import {Notifier} from '@flaunch/hooks/Notifier.sol';
import {StoreKeys} from '@flaunch/types/StoreKeys.sol';
import {TreasuryActionManager} from '@flaunch/treasury/ActionManager.sol';

import {IFeeCalculator} from '@flaunch-interfaces/IFeeCalculator.sol';
import {IFlaunch} from '@flaunch-interfaces/IFlaunch.sol';
import {IInitialPrice} from '@flaunch-interfaces/IInitialPrice.sol';
import {IMemecoin} from '@flaunch-interfaces/IMemecoin.sol';


/**
 * The PositionManager is a Uniswap V4 hook that controls the user journey from token creation,
 * to fair launch, to ongoing swaps.
 *
 * The creator of the pool will receive an ERC721 representation of the token. The holder of
 * this token will be the recipient of any creator fees generated by the token in the pool.
 *
 * Hook interactions have aimed to be abstracted into inherited contracts to simplify both
 * functionality and readability. Specific use of each of these contracts has been denoted
 * within comments using square brackets where possible.
 */
contract PositionManager is BaseHook, FeeDistributor, InternalSwapPool, StoreKeys {

    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using CurrencySettler for Currency;
    using PoolIdLibrary for PoolKey;
    using SafeCast for uint;
    using StateLibrary for IPoolManager;
    using MemecoinFinder for PoolKey;

    error CallerIsNotBidWall();
    error CannotBeInitializedDirectly();
    error InsufficientFlaunchFee(uint _paid, uint _required);
    error TokenNotFlaunched(uint _flaunchesAt);
    error UnknownPool(PoolId _poolId);

    /// Emitted when a Flaunch pool is created
    event PoolCreated(PoolId indexed _poolId, address _memecoin, address _memecoinTreasury, uint _tokenId, bool _currencyFlipped, uint _flaunchFee, FlaunchParams _params);

    /// Emitted when a Flaunch pool is scheduled
    event PoolScheduled(PoolId indexed _poolId, uint _flaunchesAt);

    /// Emitted when a pool swap occurs
    event PoolSwap(PoolId indexed poolId, int flAmount0, int flAmount1, int flFee0, int flFee1, int ispAmount0, int ispAmount1, int ispFee0, int ispFee1, int uniAmount0, int uniAmount1, int uniFee0, int uniFee1);

    /// Emitted after any transaction to share pool state
    event PoolStateUpdated(PoolId indexed _poolId, uint160 _sqrtPriceX96, int24 _tick, uint24 _protocolFee, uint24 _swapFee, uint128 _liquidity);

    /// Emitted when a user successfully premines their token
    event PoolPremine(PoolId indexed _poolId, int _premineAmount);

    /// Emitted when the `IInitialPrice` contract has been updated
    event InitialPriceUpdated(address _initialPrice);

    /**
     * Defines our constructor parameters.
     *
     * @member nativeToken The native ETH equivalent token used by protocol
     * @member poolManager The Uniswap V4 {PoolManager} contract
     * @member feeDistribution The default fee distribution configuration
     * @member initialPrice Set initial price calculator address
     * @member protocolOwner The EOA that will be the initial owner
     * @member protocolFeeRecipient The recipient EOA of all
     * @member flayGovernance The $FLAY token governance address
     * @member feeExemptions The default global FeeExemption values
     */
    struct ConstructorParams {
        address nativeToken;
        IPoolManager poolManager;
        FeeDistribution feeDistribution;
        IInitialPrice initialPrice;
        address protocolOwner;
        address protocolFeeRecipient;
        address flayGovernance;
        FeeExemptions feeExemptions;
    }

    /**
     * If the creator requests a premine amount of tokens, then these will be cast
     * to this structure.
     *
     * @member amountSpecified The amount of tokens requested to buy as creator
     * @member blockNumber The block that the premine is created and allocated
     */
    struct PoolPremineInfo {
        int amountSpecified;
        uint blockNumber;
    }

    /**
     * Parameters required when flaunching a new token.
     *
     * @member name Name of the token
     * @member symbol Symbol of the token
     * @member tokenUri The generated ERC721 token URI
     * @member initialTokenFairLaunch The amount of tokens to add as single sided fair launch liquidity
     * @member premineAmount The amount of tokens that the creator will buy themselves
     * @member creator The address that will receive the ERC721 ownership and premined ERC20 tokens
     * @member creatorFeeAllocation The percentage of fees the creators wants to take from the BidWall
     * @member flaunchAt The timestamp at which the token will launch
     * @member initialPriceParams The encoded parameters for the Initial Price logic
     * @member feeCalculatorParams The encoded parameters for the fee calculator
     */
    struct FlaunchParams {
        string name;
        string symbol;
        string tokenUri;
        uint initialTokenFairLaunch;
        uint premineAmount;
        address creator;
        uint24 creatorFeeAllocation;
        uint flaunchAt;
        bytes initialPriceParams;
        bytes feeCalculatorParams;
    }

    /// The minimum amount before a distribution is triggered
    uint public constant MIN_DISTRIBUTE_THRESHOLD = 0.001 ether;

    /// The contract that will be used for flaunching tokens
    IFlaunch public flaunchContract;

    /// Our starting token sqrtPriceX96
    IInitialPrice public initialPrice;

    /// Internal storage to allow the `beforeSwap` tick value to be used in `afterSwap`
    int24 internal _beforeSwapTick;

    /// Store the address that will collect protocol fees
    address internal protocolFeeRecipient;

    /// Store the contract that will manage our Bidwall interactions
    BidWall public bidWall;

    /// The contract that handles the FairLaunch flow
    FairLaunch public fairLaunch;

    /// The contract that handles the token Treasury actions
    TreasuryActionManager public actionManager;

    /// Store the contract that will manage fee exemptions
    FeeExemptions public feeExemptions;

    /// Store our {Notifier} contract
    Notifier public notifier;

    /// Store the block timestamp when a poolId is set to launch
    mapping (PoolId _poolId => uint _flaunchTime) public flaunchesAt;

    /// Store the premine information for a pool
    mapping (PoolId _poolId => PoolPremineInfo _premineInfo) public premineInfo;

    /**
     * Initializes our {BaseHook} contract and initializes all implemented hooks.
     */
    constructor (ConstructorParams memory params)
        BaseHook(params.poolManager)
        FeeDistributor(params.nativeToken, params.feeDistribution, params.protocolOwner, params.flayGovernance)
    {
        // Set our contract references
        initialPrice = params.initialPrice;

        // Set our protocol fee recipient
        protocolFeeRecipient = params.protocolFeeRecipient;

        // Register our FeeExemption contract
        feeExemptions = params.feeExemptions;

        // Deploy our BidWall contract and transfer ownership to the protocol owner
        bidWall = new BidWall(params.nativeToken, address(params.poolManager), params.protocolOwner);

        // Deploy our FairLaunch logic
        fairLaunch = new FairLaunch(params.poolManager);

        // Deploy our ActionManager
        actionManager = new TreasuryActionManager(params.protocolOwner);

        // Deploy our notifier
        notifier = new Notifier(params.protocolOwner);

        // Approve the BidWall to manage native token from the PositionManager
        IERC20(params.nativeToken).approve(address(bidWall), type(uint).max);
        IERC20(params.nativeToken).approve(address(fairLaunch), type(uint).max);
    }

    /**
     * Creates a new ERC20 memecoin token creating and an ERC721 that signifies ownership of the
     * flaunched collection. The token is then initialized into a UV4 pool.
     *
     * The FairLaunch period will start in this call, as soon as the pool is initialized.
     *
     * @return memecoin_ The created ERC20 token address
     */
    function flaunch(FlaunchParams calldata _params) external payable returns (address memecoin_) {
        uint tokenId;
        address payable memecoinTreasury;

        // Flaunch our token
        (memecoin_, memecoinTreasury, tokenId) = flaunchContract.flaunch(_params);

        // Check if our pool currency is flipped
        bool currencyFlipped = nativeToken >= memecoin_;

        // Create our Uniswap pool and store the pool key for lookups
        PoolKey memory _poolKey = PoolKey({
            currency0: Currency.wrap(!currencyFlipped ? nativeToken : memecoin_),
            currency1: Currency.wrap(currencyFlipped ? nativeToken : memecoin_),
            fee: 0,
            tickSpacing: 60,
            hooks: IHooks(address(this))
        });

        // Initialize the {MemecoinTreasury} with `PoolKey`
        MemecoinTreasury(memecoinTreasury).initialize(payable(address(this)), address(actionManager), nativeToken, _poolKey);

        // Set the PoolKey to storage
        _poolKeys[memecoin_] = _poolKey;
        PoolId poolId = _poolKey.toId();

        // If we have a non-zero creator fee allocation, then we need to update our creator's
        // fee allocation.
        if (_params.creatorFeeAllocation != 0) {
            creatorFee[poolId] = _params.creatorFeeAllocation;
        }

        {
            // Check if we have a fair launch calculator assigned. If we do, then we want to register
            // any custom parameters that have been passed.
            IFeeCalculator fairLaunchCalculator = getFeeCalculator(true);
            if (address(fairLaunchCalculator) != address(0)) {
                fairLaunchCalculator.setFlaunchParams(poolId, _params.feeCalculatorParams);
            }
        }

        // Initialize our memecoin with the sqrtPriceX96
        int24 initialTick = poolManager.initialize(
            _poolKey,
            initialPrice.getSqrtPriceX96(msg.sender, currencyFlipped, _params.initialPriceParams)
        );

        // Check if we have an initial flaunching fee, check that enough ETH has been sent
        uint flaunchFee = getFlaunchingFee(_params.initialPriceParams);

        emit PoolCreated({
            _poolId: poolId,
            _memecoin: memecoin_,
            _memecoinTreasury: memecoinTreasury,
            _tokenId: tokenId,
            _currencyFlipped: currencyFlipped,
            _flaunchFee: flaunchFee,
            _params: _params
        });

        /**
         * [PREMINE] If the creator has requested tokens from their initial fair launch
         * allocation, which they can purchase in the same transaction.
         */

        if (_params.premineAmount != 0) {
            premineInfo[poolId] = PoolPremineInfo({
                amountSpecified: _params.premineAmount.toInt256(),
                blockNumber: block.number
            });
        }

        /**
         * [FL] At token creation, x% of token supply is put into a one-sided position.
         */

        if (_params.initialTokenFairLaunch != 0) {
            fairLaunch.createPosition(
                poolId,
                initialTick,
                _params.flaunchAt > block.timestamp ? _params.flaunchAt : block.timestamp,
                _params.initialTokenFairLaunch
            );

            // We don't currently require any token approval to create a fair launch position, but
            // when the position closes, the {FairLaunch} contract will supply the {PoolManager}
            // with tokens from this contract.
            IMemecoin(memecoin_).approve(address(fairLaunch), type(uint).max);
        }

        /**
         * [SCHEDULE] If we have a timestamp in the future, then we set our schedule mapping.
         */

        if (_params.flaunchAt > block.timestamp) {
            flaunchesAt[poolId] = _params.flaunchAt;
            emit PoolScheduled(poolId, _params.flaunchAt);
        } else {
            // If the `flaunchAt` timestamp has already passed, then use the current timestamp
            flaunchesAt[poolId] = block.timestamp;
        }

        // Refund any additional ETH
        if (flaunchFee != 0) {
            // Check if we have insufficient value provided
            if (msg.value < flaunchFee) {
                revert InsufficientFlaunchFee(msg.value, flaunchFee);
            }

            // Pay the flaunching fee to our fee recipient
            SafeTransferLib.safeTransferETH(protocolFeeRecipient, flaunchFee);
        }

        // Refund any ETH that was not required
        if (msg.value > flaunchFee) {
            SafeTransferLib.safeTransferETH(msg.sender, msg.value - flaunchFee);
        }

        // After our contract is initialized, we mark our pool as initialized and emit
        // our state update to notify the UX of current prices, etc. This will include
        // optional liquidity modifications from the Fair Launch logic.
        _emitPoolStateUpdate(poolId, IHooks.afterInitialize.selector, abi.encode(tokenId, _params));
    }

    /**
     * Returns the PoolKey mapped to the token address. If none is set then a zero value
     * will be returned for the fields.
     *
     * @dev The easiest way to check for an empty response is `tickSpacing = 0`
     *
     * @param _token The address of the ERC20 token
     *
     * @return The corresponding {PoolKey} for the token
     */
    function poolKey(address _token) external view returns (PoolKey memory) {
        return _poolKeys[_token];
    }

    /**
     * Defines the Uniswap V4 hooks that are used by our implementation. This will determine
     * the address that our contract **must** be deployed to for Uniswap V4. This address suffix
     * is shown in the dev comments for this function call.
     *
     * @dev 1011 1111 0111 00 == 2FDC
     */
    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true, // Prevent initialize
            afterInitialize: false,
            beforeAddLiquidity: true, // [FairLaunch], [InternalSwapPool]
            afterAddLiquidity: true, // [EventTracking]
            beforeRemoveLiquidity: true, // FairLaunch], [InternalSwapPool]
            afterRemoveLiquidity: true, // [EventTracking]
            beforeSwap: true, // FairLaunch], [InternalSwapPool]
            afterSwap: true, // [FeeDistributor], [InternalSwapPool], [BidWall], [EventTracking]
            beforeDonate: false,
            afterDonate: true, // [EventTracking]
            beforeSwapReturnDelta: true, // [InternalSwapPool]
            afterSwapReturnDelta: true, // [FeeDistributor]
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    /**
     * The hook called before the state of a pool is initialized. Prevents external contracts
     * from initializing pools using our contract as a hook.
     *
     * @dev As we call `poolManager.initialize` from the IHooks contract itself, we bypass this
     * hook call as therefore bypass the prevention.
     */
    function beforeInitialize(address, PoolKey calldata, uint160) external view override onlyPoolManager returns (bytes4) {
        revert CannotBeInitializedDirectly();
    }

    /**
     * [FL] Handles swaps during the FairLaunch and closure of the position when it expires
     * [ISP] Checks if we can process an internal swap ahead of the Uniswap swap.
     * [FD] Captures fees from the internal swap pool
     *
     * @param _sender The address calling the swap
     * @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 selector_ 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 swapFee_ The percentage fee applied to our swap
     */
    function beforeSwap(
        address _sender,
        PoolKey calldata _key,
        IPoolManager.SwapParams memory _params,
        bytes calldata _hookData
    ) public override onlyPoolManager returns (
        bytes4 selector_,
        BeforeSwapDelta beforeSwapDelta_,
        uint24
    ) {
        /**
         * [SCHEDULE][PREMINE] Check if the token is scheduled to be flaunched and only
         * allow a swap to take place if there is a premine call available.
         */

        {
            PoolId poolId = _key.toId();

            // If set, get the timestamp that the pool is scheduled to flaunch
            uint _flaunchesAt = flaunchesAt[poolId];
            if (_flaunchesAt != 0) {
                // If we have a schedule set for the token, then we need to make an additional
                // check to see if a premine is set, and if it's valid.
                PoolPremineInfo storage _premineInfo = premineInfo[poolId];

                // The validity of a premine ensures that we are in the same block and that the
                // amount specified is the same. We cannot check that the caller is the same as
                // the `_sender` is obfuscated to be the swap contract.
                if (_premineInfo.blockNumber == block.number && _params.amountSpecified == _premineInfo.amountSpecified) {
                    emit PoolPremine(poolId, _premineInfo.amountSpecified);
                    _premineInfo.blockNumber = 0;
                } else {
                    // If the timestamp has not yet passed, then we revert
                    if (_flaunchesAt > block.timestamp) {
                        revert TokenNotFlaunched(_flaunchesAt);
                    }

                    // Remove the schedule timestamp to prevent future checks
                    delete flaunchesAt[poolId];
                }
            }
        }

        // Check if our fair launch period hasn't ended and already been processed
        FairLaunch.FairLaunchInfo memory fairLaunchInfo = fairLaunch.fairLaunchInfo(_key.toId());
        if (!fairLaunchInfo.closed) {
            PoolId poolId = _key.toId();
            bool nativeIsZero = nativeToken == Currency.unwrap(_key.currency0);

            /**
             * [FL] If the FairLaunch window has ended, but our position is still open, then we
             * need to close the position.
             */

            if (!fairLaunch.inFairLaunchWindow(poolId)) {
                fairLaunch.closePosition({
                    _poolKey: _key,
                    _tokenFees: _poolFees[poolId].amount1,
                    _nativeIsZero: nativeIsZero
                });
            }
            else {

                /**
                 * [FL] If we are still in the FairLaunch window, then we need to prevent any swaps that
                 * are specified to sell the {Memecoin}.
                 */

                if (nativeIsZero != _params.zeroForOne) {
                    revert FairLaunch.CannotSellTokenDuringFairLaunch();
                }

                /**
                 * [FL] We attempt to fill the swap request from our FairLaunch position. If the
                 * swap parameters surpass the FairLaunch position, or the window has closed since
                 * the last swap, then this call will also close the position and create our new
                 * range.
                 */

                // Try to fill from FL at specific tick
                BalanceDelta fairLaunchFillDelta;
                (beforeSwapDelta_, fairLaunchFillDelta, fairLaunchInfo) = fairLaunch.fillFromPosition(_key, _params.amountSpecified, nativeIsZero);

                // Give the tokens to Uniswap V4 so that it can play good-cop and give them to the user
                _settleDelta(_key, fairLaunchFillDelta);

                /**
                 * [FD] We need to determine the amount of fees generated by our fair launch swap to
                 * capture, rather than sending the full amount to the end user.
                 */

                // We need to capture fees from our internal swap at this point
                uint swapFee = _captureAndDepositFees(_key, _params, _sender, beforeSwapDelta_.getUnspecifiedDelta(), _hookData);

                // Increment our swap
                _captureDelta(_params, TS_FL_AMOUNT0, TS_FL_AMOUNT1, beforeSwapDelta_);
                _captureDeltaSwapFee(_params, TS_FL_FEE0, TS_FL_FEE1, swapFee);

                // Increase the delta being sent back
                beforeSwapDelta_ = toBeforeSwapDelta(
                    beforeSwapDelta_.getSpecifiedDelta(),
                    beforeSwapDelta_.getUnspecifiedDelta() + swapFee.toInt128()
                );

                // A FairLaunch transaction will always facilitate purchasing Memecoin with
                // Native Token. This means that if the `amountSpecified` not negative, then we will
                // have captured the fee in Native Token and as such we need to reduce the amount of
                // revenue that we record.
                if (_params.amountSpecified >= 0 && swapFee != 0) {
                    fairLaunch.modifyRevenue(poolId, -swapFee.toInt128());
                }

                // If we have run out of tokens, then we can close the pool
                if (fairLaunchInfo.supply == 0) {
                    fairLaunch.closePosition({
                        _poolKey: _key,
                        _tokenFees: _poolFees[poolId].amount1,
                        _nativeIsZero: nativeIsZero
                    });
                }
            }
        }

        /**
         * [ISP] We want to see if we have any token1 fee tokens that we can use to fill the swap
         * before it hits the Uniswap pool. This prevents the pool from being affected and reduced
         * gas costs. This also allows us to benefit from the Uniswap routing infrastructure.
         *
         * This frontruns Uniswap to sell undesired token amounts from our fees into desired tokens
         * ahead of our fee distribution. This acts as a partial orderbook to remove impact against
         * our pool.
         */

        (uint tokenIn, uint tokenOut) = _internalSwap(poolManager, _key, _params, nativeToken == Currency.unwrap(_key.currency0));
        if (tokenIn + tokenOut != 0) {
            // Update our hook delta to reduce the upcoming swap amount to show that we have
            // already spent some of the ETH and received some of the underlying ERC20.
            BeforeSwapDelta internalBeforeSwapDelta = _params.amountSpecified >= 0
                ? toBeforeSwapDelta(-tokenOut.toInt128(), tokenIn.toInt128())
                : toBeforeSwapDelta(tokenIn.toInt128(), -tokenOut.toInt128());

            /**
             * [FD] We need to determine the amount of fees generated by our internal swap to capture,
             * rather than sending the full amount to the end user.
             */

            // We need to capture fees from our internal swap at this point
            uint swapFee = _captureAndDepositFees(_key, _params, _sender, internalBeforeSwapDelta.getUnspecifiedDelta(), _hookData);

            // Increment our swap
            _captureDelta(_params, TS_ISP_AMOUNT0, TS_ISP_AMOUNT1, internalBeforeSwapDelta);
            _captureDeltaSwapFee(_params, TS_ISP_FEE0, TS_ISP_FEE1, swapFee);

            // Increase the delta being sent back
            beforeSwapDelta_ = toBeforeSwapDelta(
                beforeSwapDelta_.getSpecifiedDelta() + internalBeforeSwapDelta.getSpecifiedDelta(),
                beforeSwapDelta_.getUnspecifiedDelta() + internalBeforeSwapDelta.getUnspecifiedDelta() + swapFee.toInt128()
            );
        }

        // Capture the beforeSwap tick value before actioning our Uniswap swap
        (, _beforeSwapTick,,) = poolManager.getSlot0(_key.toId());

        // Set our return selector
        selector_ = IHooks.beforeSwap.selector;
    }

    /**
     * [FD] Captures fees from the swap to either distribute or send to ISP
     * [ISP] Once a swap has been made, we distribute fees to our LPs and emit our price update event.
     * [FD] Tracks the swap for future fee calculations
     * [FL][BW] If Fair Launch ended then we may have an ETH to deposit into the BidWall
     *
     * @param _sender The sender (or swap contract) making the 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 selector_ The function selector for the hook
     * @return hookDeltaUnspecified_ The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
     */
    function afterSwap(
        address _sender,
        PoolKey calldata _key,
        IPoolManager.SwapParams calldata _params,
        BalanceDelta _delta,
        bytes calldata _hookData
    ) public override onlyPoolManager returns (
        bytes4 selector_,
        int128 hookDeltaUnspecified_
    ) {
        /**
         * [FD] We need to determine the amount of fees generated by our Uniswap swap to capture,
         * rather than sending the full amount to the end user.
         */

        // Determine the currency that we will be taking our fee from
        (int128 amount0, int128 amount1) = (_delta.amount0(), _delta.amount1());
        int128 swapAmount = _params.amountSpecified < 0 == _params.zeroForOne ? amount1 : amount0;

        // Capture the swap fees and dispatch the referrer's share if set
        uint swapFee = _captureAndDepositFees(_key, _params, _sender, swapAmount, _hookData);

        // Increment our swap
        assembly {
            tstore(TS_UNI_AMOUNT0, amount0)
            tstore(TS_UNI_AMOUNT1, amount1)
        }

        _captureDeltaSwapFee(_params, TS_UNI_FEE0, TS_UNI_FEE1, swapFee);

        /**
         * [ISP] Distribute any fees that have been converted by the swap.
         */

        _distributeFees(_key);

        /**
         * [FD] If we have a feeCalculator, then we want to track the swap data for any
         * dynamic calculations.
         */

        PoolId poolId = _key.toId();

        {
            IFeeCalculator _feeCalculator = getFeeCalculator(fairLaunch.inFairLaunchWindow(poolId));
            if (address(_feeCalculator) != address(0)) {
                _feeCalculator.trackSwap(_sender, _key, _params, _delta, _hookData);
            }
        }

        // Set our return selector
        hookDeltaUnspecified_ = swapFee.toInt128();

        selector_ = IHooks.afterSwap.selector;

        // Emit our compiled swap data
        _emitSwapUpdate(poolId);

        // Emit our pool state update to listeners
        _emitPoolStateUpdate(poolId, selector_, abi.encode(_sender, _params, _delta));
    }

    /**
     * [FL] Prevent liquidity modification during FairLaunch period
     * [FD] Before a liquidity position is modified, we distribute fees before they can
     * come in to take a share of fees that they have not earned.
     *
     * @param _key The key for the pool
     *
     * @return selector_ The function selector for the hook
     */
    function beforeAddLiquidity(
        address _sender,
        PoolKey calldata _key,
        IPoolManager.ModifyLiquidityParams calldata,
        bytes calldata
    ) public view override onlyPoolManager returns (
        bytes4 selector_
    ) {
        // [FL] If in fair launch window, we need to prevent liquidity being added
        _canModifyLiquidity(_key.toId(), _sender);

        selector_ = IHooks.beforeAddLiquidity.selector;
    }

    /**
     * Once a liquidity has been added, we emit our price update event.
     *
     * @param _sender The initial msg.sender for the add liquidity call
     * @param _key The key for the pool
     * @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
     *
     * @return selector_ The function selector for the hook
     * @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
     */
    function afterAddLiquidity(
        address _sender,
        PoolKey calldata _key,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta _delta,
        BalanceDelta _feesAccrued,
        bytes calldata
    ) external override onlyPoolManager returns (
        bytes4 selector_,
        BalanceDelta
    ) {
        selector_ = IHooks.afterAddLiquidity.selector;

        // Emit our pool state update to listeners
        _emitPoolStateUpdate(_key.toId(), selector_, abi.encode(_sender, _delta, _feesAccrued));
    }

    /**
     * [FL] Prevent liquidity modification during FairLaunch period
     * [FD] Before liquidity is removed, we distribute fees.
     *
     * @param _key The key for the pool
     *
     * @return selector_ The function selector for the hook
     */
    function beforeRemoveLiquidity(
        address _sender,
        PoolKey calldata _key,
        IPoolManager.ModifyLiquidityParams calldata,
        bytes calldata
    ) public view override onlyPoolManager returns (
        bytes4 selector_
    ) {
        // [FL] If in fair launch window, we need to prevent liquidity being removed
        _canModifyLiquidity(_key.toId(), _sender);

        // Set our return selector
        selector_ = IHooks.beforeRemoveLiquidity.selector;
    }

    /**
     * Once liquidity has been removed, we emit our price update event.
     *
     * @param _sender The initial msg.sender for the remove liquidity call
     * @param _key The key for the pool
     * @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
     *
     * @return selector_ The function selector for the hook
     */
    function afterRemoveLiquidity(
        address _sender,
        PoolKey calldata _key,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta _delta,
        BalanceDelta _feesAccrued,
        bytes calldata
    ) public override onlyPoolManager returns (bytes4 selector_, BalanceDelta) {
        selector_ = IHooks.afterRemoveLiquidity.selector;

        // Emit our pool state update to listeners
        _emitPoolStateUpdate(_key.toId(), selector_, abi.encode(_sender, _delta, _feesAccrued));
    }

    /**
     * The hook called after donate, emitting our price update event.
     *
     * @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
     *
     * @return selector_ The function selector for the hook
     */
    function afterDonate(address _sender, PoolKey calldata _key, uint _amount0, uint _amount1, bytes calldata) external override onlyPoolManager returns (bytes4 selector_) {
        selector_ = IHooks.afterDonate.selector;

        // Emit our pool state update to listeners
        _emitPoolStateUpdate(_key.toId(), selector_, abi.encode(_sender, _amount0, _amount1));
    }

    /**
     * Gets the ETH fee that must be paid to flaunch a token.
     *
     * @return The ETH value of the fee
     */
    function getFlaunchingFee(bytes calldata _initialPriceParams) public view returns (uint) {
        return initialPrice.getFlaunchingFee(msg.sender, _initialPriceParams);
    }

    /**
     * Gets the ETH market cap for a new token that will be flaunched.
     *
     * @return The ETH market cap value
     */
    function getFlaunchingMarketCap(bytes calldata _initialPriceParams) public view returns (uint) {
        return initialPrice.getMarketCap(_initialPriceParams);
    }

    /**
     * Allows the contract used to flaunch a new token to be updated.
     *
     * @param _flaunchContract The new {IFlaunch} contract address
     */
    function setFlaunch(address _flaunchContract) public onlyOwner {
        flaunchContract = IFlaunch(_flaunchContract);
    }

    /**
     * Updates the `IInitialPrice` contract address that is used during `flaunch` to calculate
     * the initial tick / sqrtPriceX96 value.
     *
     * @param _initialPrice The contract address for the `IInitialPrice` contract
     */
    function setInitialPrice(address _initialPrice) public onlyOwner {
        initialPrice = IInitialPrice(_initialPrice);
        emit InitialPriceUpdated(_initialPrice);
    }

    /**
     * Calls for the BidWall to be closed, as this requires callback from the {PoolManager}.
     */
    function closeBidWall(PoolKey memory _key) public {
        // Ensure that the call is made by the BidWall which validates logic
        if (msg.sender != address(bidWall)) revert CallerIsNotBidWall();

        // Ensure that the PoolKey that is being closed is valid and recognised on the protocol,
        // otherwise we could processing issues and false positives in upcoming steps. We need to
        // ensure that the PoolKey is recognised (by checking the hooks address is not zero) and
        // that the PoolId matches when encoded.
        PoolKey memory storedKey = _poolKeys[address(_key.memecoin(nativeToken))];
        if (storedKey.hooks == IHooks(address(0)) || PoolId.unwrap(storedKey.toId()) != PoolId.unwrap(_key.toId())) {
            revert UnknownPool(_key.toId());
        }

        // Action our BidWall closure via the {PoolManager} unlock
        poolManager.unlock(abi.encode(_key));
    }

    /**
     * This function should only be called by the `closeBidWall` function to unlock the {PoolManager}
     * interactions for the `{BidWall}.closeBidWall` function.
     *
     * @param _data The encoded {PoolKey} for the `closeBidWall` request
     *
     * @return bytes Empty data; nothing will be returned
     */
    function _unlockCallback(bytes calldata _data) internal override returns (bytes memory) {
        bidWall.closeBidWall(abi.decode(_data, (PoolKey)));
    }

    /**
     * Capture the fees from our swap. This could either be from an internal swap (`beforeSwap`)
     * or from the actual Uniswap swap (`afterSwap`).
     *
     * @dev This is only used due to too many variables in the `beforeSwap` function
     *
     * @param _key The {PoolKey} that the swap was made against
     * @param _params The swap parameters called in the swap
     * @param _sender The sender of the swap call
     * @param _delta The balance change from the swap
     * @param _hookData Additional bytes data passed in the swap
     *
     * @return swapFee_ The fee taken from the swap
     */
    function _captureAndDepositFees(
        PoolKey calldata _key,
        IPoolManager.SwapParams memory _params,
        address _sender,
        int128 _delta,
        bytes calldata _hookData
    ) internal returns (uint swapFee_) {
        // Determine the swap fee currency based on swap parameters
        Currency swapFeeCurrency = _params.amountSpecified < 0 == _params.zeroForOne ? _key.currency1 : _key.currency0;

        // Capture our swap fees amount
        swapFee_ = _captureSwapFees({
            _poolManager: poolManager,
            _key: _key,
            _params: _params,
            _feeCalculator: getFeeCalculator(fairLaunch.inFairLaunchWindow(_key.toId())),
            _swapFeeCurrency: swapFeeCurrency,
            _swapAmount: uint128(_delta < 0 ? -_delta : _delta),
            _feeExemption: feeExemptions.feeExemption(_sender)
        });

        // If we have no swap fees, then we have nothing to process
        if (swapFee_ == 0) {
            return swapFee_;
        }

        // Check if we have a referrer set and send them the currency directly
        uint referrerFee = _distributeReferrerFees({
            _key: _key,
            _swapFeeCurrency: swapFeeCurrency,
            _swapFee: swapFee_,
            _hookData: _hookData
        });

        // Deposit the remaining fees against our pool to be either distributed to
        // others, or placed into the Internal Swap Pool to be converted into an ETH
        // equivalent token. We don't reduce the amount by referrer fees as we still
        // need to claim this from the PoolManager.
        _depositFees(
            _key,
            Currency.unwrap(swapFeeCurrency) == nativeToken ? swapFee_ - referrerFee : 0,
            Currency.unwrap(swapFeeCurrency) == nativeToken ? 0 : swapFee_ - referrerFee
        );
    }

    /**
     * We want to be able to distribute fees across our {FeeDistribution} recipients
     * when we reach a set threshold. This will only ever distribute the ETH equivalent
     * token, as the non-ETH token will be converted via the {InternalSwapPool} hook logic.
     *
     * @dev There referrer has already received their share, so they do not need to be
     * taken into account at this point.
     *
     * @param _poolKey The PoolKey reference that will have fees distributed
     */
    function _distributeFees(PoolKey memory _poolKey) internal {
        PoolId poolId = _poolKey.toId();

        // Get the amount of the native token available to distribute
        uint distributeAmount = _poolFees[poolId].amount0;

        // Ensure that the collection has sufficient fees available
        if (distributeAmount < MIN_DISTRIBUTE_THRESHOLD) return;

        // Reduce our available fees for the pool
        _poolFees[poolId].amount0 = 0;

        // Find the distribution amount across our different users. The amount that treasury
        // receives will be determined by variables throughout the distribution flow, such as
        // the BidWall being disabled, etc.
        (uint bidWallFee, uint creatorFee, uint protocolFee) = feeSplit(poolId, distributeAmount);
        uint treasuryFee;

        // Load our memecoin so that we can query the creator and treasury
        IMemecoin memecoin = _poolKey.memecoin(nativeToken);

        // Check if our creator has been burned, as this changes fee allocation in a number of places
        address poolCreator = memecoin.creator();
        bool poolCreatorBurned = poolCreator == address(0);

        if (creatorFee != 0) {
            // Ensure that the pool creator has not burned their ownership and send them the fees
            if (!poolCreatorBurned) {
                _allocateFees(poolId, poolCreator, creatorFee);
            }
            // If the pool creator has burned their ownership, then we instead send fees directly
            // to the BidWall.
            else {
                bidWallFee += creatorFee;
                creatorFee = 0;
            }
        }

        if (bidWallFee != 0) {
            // Check if we have an active BidWall for the pool. If we don't have an active BidWall, then
            // we will need to instead allocate this to the protocol. If we are still in the FairLaunch
            // window the this will just carry over into the FairLaunch created position, so we already
            // have this value attributed.
            if (bidWall.isBidWallEnabled(poolId) && !fairLaunch.inFairLaunchWindow(poolId)) {
                // Otherwise, we can deposit directly into the BidWall as we have permission to modify
                // liquidity outside of the window.
                bidWall.deposit(_poolKey, bidWallFee, _beforeSwapTick, nativeToken == Currency.unwrap(_poolKey.currency0));
            } else {
                // If we cannot import into BidWall, then treasury will be allocated the fees
                treasuryFee += bidWallFee;
                bidWallFee = 0;
            }
        }

        if (treasuryFee != 0) {
            // Ensure that the pool creator has not burned their ownership and send treasury the fees
            if (!poolCreatorBurned) {
                _allocateFees(poolId, memecoin.treasury(), treasuryFee);
            } else {
                // If we cannot allocate to treasury, then protocol receives the fees
                protocolFee += treasuryFee;
                treasuryFee = 0;
            }
        }

        // Finally we allocate our protocol fees
        if (protocolFee != 0) {
            _allocateFees(poolId, protocolFeeRecipient, protocolFee);
        }

        emit PoolFeesDistributed(poolId, distributeAmount, creatorFee, bidWallFee, treasuryFee, protocolFee);
    }

    /**
     * Using the `tstore` values that we have generated along the way, we emit an event that shows
     * the breakdown of fees earned at each swap point.
     *
     * @param _poolId The PoolId that is being emitted
     */
    function _emitSwapUpdate(PoolId _poolId) internal {
        emit PoolSwap(
            _poolId,
            _tload(TS_FL_AMOUNT0), _tload(TS_FL_AMOUNT1), _tload(TS_FL_FEE0), _tload(TS_FL_FEE1),
            _tload(TS_ISP_AMOUNT0), _tload(TS_ISP_AMOUNT1), _tload(TS_ISP_FEE0), _tload(TS_ISP_FEE1),
            _tload(TS_UNI_AMOUNT0), _tload(TS_UNI_AMOUNT1), _tload(TS_UNI_FEE0), _tload(TS_UNI_FEE1)
        );

        // @dev We flush the tstore values at this point as although they are only set
        // explicitly and not modified, both the FL and ISP could be bypassed but the tstore
        // data would remain.

        assembly {
            tstore(TS_FL_AMOUNT0, 0)
            tstore(TS_FL_AMOUNT1, 0)
            tstore(TS_FL_FEE0, 0)
            tstore(TS_FL_FEE1, 0)
            tstore(TS_ISP_AMOUNT0, 0)
            tstore(TS_ISP_AMOUNT1, 0)
            tstore(TS_ISP_FEE0, 0)
            tstore(TS_ISP_FEE1, 0)
            tstore(TS_UNI_AMOUNT0, 0)
            tstore(TS_UNI_AMOUNT1, 0)
            tstore(TS_UNI_FEE0, 0)
            tstore(TS_UNI_FEE1, 0)
        }
    }

    /**
     * Emits an event that provides pool state updates and passes the data to subscribers.
     *
     * @param _poolId The PoolId that has been updated
     * @param _key The selector being sent to notification subscribers
     * @param _data The data being sent to notification subscribers
     */
    function _emitPoolStateUpdate(PoolId _poolId, bytes4 _key, bytes memory _data) internal {
        // Notify our subscribed contracts
        notifier.notifySubscribers(_poolId, _key, _data);

        // Emit our event
        (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 swapFee) = poolManager.getSlot0(_poolId);
        emit PoolStateUpdated(_poolId, sqrtPriceX96, tick, protocolFee, swapFee, poolManager.getLiquidity(_poolId));
    }

    /**
     * Settles tokens against the PoolManager based on the BalanceDelta passed.
     *
     * @dev This is required to be separated due to Stack Too Deep errors
     *
     * @param _poolKey The pool key to settle against
     * @param _delta The BalanceDelta showing token amounts to settle
     */
    function _settleDelta(PoolKey memory _poolKey, BalanceDelta _delta) internal {
        if (_delta.amount0() < 0) {
            _poolKey.currency0.settle(poolManager, address(this), uint(-int(_delta.amount0())), false);
        } else if (_delta.amount0() > 0) {
            poolManager.take(_poolKey.currency0, address(this), uint(int(_delta.amount0())));
        }

        if (_delta.amount1() < 0) {
            _poolKey.currency1.settle(poolManager, address(this), uint(-int(_delta.amount1())), false);
        } else if (_delta.amount1() > 0) {
            poolManager.take(_poolKey.currency1, address(this), uint(int(_delta.amount1())));
        }
    }

    /**
     * We need to be able to set the (un)specified token to amount0 / amount1 for the expected
     * event emit format.
     *
     * @param _params The `SwapParams` used to capture the delta
     * @param _key_amount0 The tstore key for the token0 amount
     * @param _key_amount1 The tstore key for the token1 amount
     * @param _delta The `BeforeSwapDelta` that is being captured
     */
    function _captureDelta(
        IPoolManager.SwapParams memory _params,
        bytes32 _key_amount0,
        bytes32 _key_amount1,
        BeforeSwapDelta _delta
    ) internal {
        (int token0, int token1) = _params.amountSpecified < 0 == _params.zeroForOne
            ? (-_delta.getSpecifiedDelta(), -_delta.getUnspecifiedDelta())
            : (-_delta.getUnspecifiedDelta(), -_delta.getSpecifiedDelta());

        // Store our amounts
        assembly {
            tstore(_key_amount0, token0)
            tstore(_key_amount1, token1)
        }
    }

    /**
     * Maps our swap fee to the expected event emit format.
     *
     * @param _params The `SwapParams` used to capture the delta
     * @param _key_fee0 The tstore key for the token0 fee amount
     * @param _key_fee1 The tstore key for the token1 fee amount
     * @param _delta The `uint` that is being captured for the fee
     */
    function _captureDeltaSwapFee(
        IPoolManager.SwapParams memory _params,
        bytes32 _key_fee0,
        bytes32 _key_fee1,
        uint _delta
    ) internal {
        // The delta provided needs to be made negative
        int delta = -int(_delta);

        if (_params.amountSpecified < 0 == _params.zeroForOne) {
            assembly {
                tstore(_key_fee0, 0)
                tstore(_key_fee1, delta)
            }
        } else {
            assembly {
                tstore(_key_fee0, delta)
                tstore(_key_fee1, 0)
            }
        }
    }

    /**
     * If in fair launch window, we need to prevent liquidity being added. We can, however, modify
     * liquidity if we are making the call from the BidWall or FairLaunch contracts.
     *
     * @param _poolId The PoolId having the liquidity modified
     * @param _sender The address that is trying to modify liquidity
     */
    function _canModifyLiquidity(PoolId _poolId, address _sender) internal view {
        // Check our valid addresses
        if (_sender == address(bidWall) || _sender == address(fairLaunch)) {
            return;
        }

        // Check if we have exited the FairLaunch window
        if (!fairLaunch.inFairLaunchWindow(_poolId)) {
            return;
        }

        // All other scenarios will result in revert
        revert FairLaunch.CannotModifyLiquidityDuringFairLaunch();
    }

    /**
     * Helper function to allow for tstore-d variables to be called individually. This saves us
     * defining an additional variable before our `tload` calls inside the function.
     *
     * @param _key The `tstore` key to load
     *
     * @return value_ The `int` value in the tstore
     */
    function _tload(bytes32 _key) internal view returns (int value_) {
        assembly { value_ := tload(_key) }
    }

    /**
     * Override to return true to make `_initializeOwner` prevent double-initialization.
     *
     * @return bool Set to `true` to prevent owner being reinitialized.
     */
    function _guardInitializeOwner() internal pure override returns (bool) {
        return true;
    }

}
合同源代码
文件 55 的 67:ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unauthorized reentrant call.
    error Reentrancy();

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

    /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
    /// 9 bytes is large enough to avoid collisions with lower slots,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      REENTRANCY GUARD                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
            sstore(_REENTRANCY_GUARD_SLOT, address())
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            sstore(_REENTRANCY_GUARD_SLOT, codesize())
        }
    }

    /// @dev Guards a view function from read-only reentrancy.
    modifier nonReadReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
        }
        _;
    }
}
合同源代码
文件 56 的 67:ReferralEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {Currency} from '@uniswap/v4-core/src/types/Currency.sol';
import {IHooks} from '@uniswap/v4-core/src/libraries/Hooks.sol';
import {IPoolManager} from '@uniswap/v4-core/src/interfaces/IPoolManager.sol';
import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';

import {PoolSwap} from '@flaunch/zaps/PoolSwap.sol';

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


/**
 * When a user referrers someone that then actions a swap, their address is passed in the `hookData`. This
 * user will then receive a referral fee of the unspecified token amount. This amount will be moved to this
 * escrow contract to be claimed at a later time.
 */
contract ReferralEscrow is Ownable {

    error MismatchedTokensAndLimits();

    /// Event emitted when tokens are assigned to a user
    event TokensAssigned(PoolId indexed _poolId, address indexed _user, address indexed _token, uint _amount);

    /// Event emitted when a user claims tokens for a specific token address
    event TokensClaimed(address indexed _user, address _recipient, address indexed _token, uint _amount);

    /// Event emitted when a user has swapped their claimed tokens to ETH
    event TokensSwapped(address indexed _user, address indexed _token, uint _tokenIn, uint _ethOut);

    /// PoolSwap contract for performing swaps
    PoolSwap public poolSwap;

    /// The native token used by the Flaunch protocol
    address public immutable nativeToken;

    /// The Flaunch {PositionManager} address
    address public immutable positionManager;

    /// Mapping to track token allocations by user and token
    mapping (address _user => mapping (address _token => uint _amount)) public allocations;

    /**
     * Constructor to initialize the PoolSwap contract address.
     *
     * @param _nativeToken The native token used by the Flaunch protocol
     * @param _positionManager The Flaunch {PositionManager} address
     */
    constructor (address _nativeToken, address _positionManager) {
        nativeToken = _nativeToken;
        positionManager = _positionManager;

        _initializeOwner(msg.sender);
    }

    /**
     * Function to update the PoolSwap contract address (only owner can call this).
     *
     * @param _poolSwap The new address that will handle pool swaps
     */
    function setPoolSwap(address _poolSwap) external onlyOwner {
        poolSwap = PoolSwap(_poolSwap);
    }

    /**
     * Function to assign tokens to a user with a PoolId included in the event.
     *
     * @dev Only the {PositionManager} contract can make this call.
     *
     * @param _poolId The PoolId that generated referral fees
     * @param _user The user that received the referral fees
     * @param _token The token that the fees are paid in
     * @param _amount The amount of fees granted to the user
     */
    function assignTokens(PoolId _poolId, address _user, address _token, uint _amount) external {
        // Ensure that the caller is the {PositionManager}
        if (msg.sender != positionManager) revert Unauthorized();

        // If no amount is passed, then we have nothing to process
        if (_amount == 0) return;

        allocations[_user][_token] += _amount;
        emit TokensAssigned(_poolId, _user, _token, _amount);
    }

    /**
     * Function for a user to claim tokens across multiple token addresses.
     *
     * @param _tokens The tokens to be claimed by the caller
     */
    function claimTokens(address[] calldata _tokens, address payable _recipient) external {
        address token;
        uint amount;
        for (uint i; i < _tokens.length; ++i) {
            token = _tokens[i];
            amount = allocations[msg.sender][token];

            // If there is nothing to claim, skip next steps
            if (amount == 0) continue;

            // Update allocation before transferring to prevent reentrancy attacks
            allocations[msg.sender][token] = 0;

            // If we are claiming the native token, then we can unwrap the flETH to ETH
            if (token == nativeToken) {
                // Withdraw the FLETH and transfer the ETH to the caller
                IFLETH(nativeToken).withdraw(amount);
                (bool _sent,) = _recipient.call{value: amount}('');
                require(_sent, 'ETH Transfer Failed');
            }
            // Otherwise, just transfer the token directly to the user
            else {
                IERC20(token).transfer(_recipient, amount);
            }

            emit TokensClaimed(msg.sender, _recipient, token, amount);
        }
    }

    /**
     * Function for a user to claim and swap tokens across multiple token addresses.
     *
     * @param _tokens The tokens that are being claimed and swapped
     * @param _sqrtPriceX96Limits The respective token's sqrtPriceX96 limit
     */
    function claimAndSwap(address[] calldata _tokens, uint160[] calldata _sqrtPriceX96Limits, address payable _recipient) external {
        // Ensure that we have a limit for each token
        uint tokensLength = _tokens.length;
        if (tokensLength > _sqrtPriceX96Limits.length) revert MismatchedTokensAndLimits();

        address token;
        uint amount;
        uint amountOut;
        uint totalAmountOut;
        for (uint i; i < tokensLength; ++i) {
            token = _tokens[i];
            amount = allocations[msg.sender][token];

            // If no tokens are available, skip the claim
            if (amount == 0) continue;

            // Update allocation before transferring to prevent reentrancy attacks
            allocations[msg.sender][token] = 0;

            // If we are including the native token, then we can just bypass the swap as we will
            // just unwrap it later
            if (token == nativeToken) {
                amountOut = amount;
            } else {
                // Provide the swap contract with sufficient allocation for the swap
                IERC20(token).approve(address(poolSwap), amount);

                // Perform the swap using PoolSwap contract with corresponding sqrtPriceX96Limit
                bool flipped = token < nativeToken;
                BalanceDelta delta = poolSwap.swap({
                    _key: PoolKey({
                        currency0: Currency.wrap(flipped ? token : nativeToken),
                        currency1: Currency.wrap(flipped ? nativeToken : token),
                        fee: 0,
                        hooks: IHooks(positionManager),
                        tickSpacing: 60
                    }),
                    _params: IPoolManager.SwapParams({
                        zeroForOne: flipped,
                        amountSpecified: -int(amount),
                        sqrtPriceLimitX96: _sqrtPriceX96Limits[i]
                    })
                });

                // Get the amount of tokens received from the swap
                amountOut = uint128(flipped ? delta.amount1() : delta.amount0());
            }

            totalAmountOut += amountOut;

            emit TokensClaimed(msg.sender, _recipient, token, amount);
            emit TokensSwapped(msg.sender, token, amount, amountOut);
        }

        // Withdraw the FLETH and transfer the ETH to the caller
        IFLETH(nativeToken).withdraw(totalAmountOut);
        (bool _sent,) = _recipient.call{value: totalAmountOut}('');
        require(_sent, 'ETH Transfer Failed');
    }

    /**
     * Override to return true to make `_initializeOwner` prevent double-initialization.
     *
     * @return bool Set to `true` to prevent owner being reinitialized.
     */
    function _guardInitializeOwner() internal pure override returns (bool) {
        return true;
    }

    /**
     * Allows the contract to receive ETH from the flETH withdrawal.
     */
    receive() external payable {}

}
合同源代码
文件 57 的 67:SafeCallback.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {ImmutableState} from "./ImmutableState.sol";

/// @title Safe Callback
/// @notice A contract that only allows the Uniswap v4 PoolManager to call the unlockCallback
abstract contract SafeCallback is ImmutableState, IUnlockCallback {
    /// @notice Thrown when calling unlockCallback where the caller is not PoolManager
    error NotPoolManager();

    constructor(IPoolManager _poolManager) ImmutableState(_poolManager) {}

    /// @notice Only allow calls from the PoolManager contract
    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    /// @inheritdoc IUnlockCallback
    /// @dev We force the onlyPoolManager modifier by exposing a virtual function after the onlyPoolManager check.
    function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
        return _unlockCallback(data);
    }

    /// @dev to be implemented by the child contract, to safely guarantee the logic is only executed by the PoolManager
    function _unlockCallback(bytes calldata data) internal virtual returns (bytes memory);
}
合同源代码
文件 58 的 67: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));
    }
}
合同源代码
文件 59 的 67: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 Permit2 operation has failed.
    error Permit2Failed();

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

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         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 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 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), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `1` 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)
            }
        }
    }
}
合同源代码
文件 60 的 67:SqrtPriceMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using SafeCast for uint256;

    error InvalidPriceOrLiquidity();
    error InvalidPrice();
    error NotEnoughLiquidity();
    error PriceOverflow();

    /// @notice Gets the next sqrt price given a delta of currency0
    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
    /// price less in order to not send too much output.
    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
    /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency0 to add or remove from virtual reserves
    /// @param add Whether to add or remove the amount of currency0
    /// @return The price after adding or removing amount, depending on add
    function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
        if (amount == 0) return sqrtPX96;
        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;

        if (add) {
            unchecked {
                uint256 product = amount * sqrtPX96;
                if (product / amount == sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    if (denominator >= numerator1) {
                        // always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                    }
                }
            }
            // denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
        } else {
            unchecked {
                uint256 product = amount * sqrtPX96;
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
                assembly ("memory-safe") {
                    if iszero(
                        and(
                            eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                            gt(numerator1, product)
                        )
                    ) {
                        mstore(0, 0xf5c787f1) // selector for PriceOverflow()
                        revert(0x1c, 0x04)
                    }
                }
                uint256 denominator = numerator1 - product;
                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
            }
        }
    }

    /// @notice Gets the next sqrt price given a delta of currency1
    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
    /// price less in order to not send too much output.
    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
    /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency1 to add, or remove, from virtual reserves
    /// @param add Whether to add, or remove, the amount of currency1
    /// @return The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        // in both cases, avoid a mulDiv for most inputs
        if (add) {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? (amount << FixedPoint96.RESOLUTION) / liquidity
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
            );

            return (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
            );

            // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
            assembly ("memory-safe") {
                if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
                    mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
                    revert(0x1c, 0x04)
                }
            }
            // always fits 160 bits
            unchecked {
                return uint160(sqrtPX96 - quotient);
            }
        }
    }

    /// @notice Gets the next sqrt price given an input amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of currency0, or currency1, is being swapped in
    /// @param zeroForOne Whether the amount in is currency0 or currency1
    /// @return uint160 The price after adding the input amount to currency0 or currency1
    function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we don't pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
            : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of currency0, or currency1, is being swapped out
    /// @param zeroForOne Whether the amount out is currency1 or currency0
    /// @return uint160 The price after removing the output amount of currency0 or currency1
    function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
            : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256)
    {
        unchecked {
            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

            // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
            assembly ("memory-safe") {
                if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
                    mstore(0, 0x00bfc921) // selector for InvalidPrice()
                    revert(0x1c, 0x04)
                }
            }

            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
            uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;

            return roundUp
                ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
                : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
        }
    }

    /// @notice Equivalent to: `a >= b ? a - b : b - a`
    function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
        assembly ("memory-safe") {
            let diff :=
                sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
            // mask = 0 if a >= b else -1 (all 1s)
            let mask := sar(255, diff)
            // if a >= b, res = a - b = 0 ^ (a - b)
            // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
            // either way, res = mask ^ (a - b + mask)
            res := xor(mask, add(mask, diff))
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256 amount1)
    {
        uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity = uint256(liquidity);

        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
        assembly ("memory-safe") {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
        }
    }

    /// @notice Helper that gets signed currency0 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }

    /// @notice Helper that gets signed currency1 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }
}
合同源代码
文件 61 的 67:StateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

    // feeGrowthGlobal1X128 offset in Pool.State = 2

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

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

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

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

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

        bytes32 data = manager.extsload(stateSlot);

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

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

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

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

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

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

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

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}
合同源代码
文件 62 的 67:StoreKeys.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;


/**
 * Defines a range of `tstore` storage locations that will be used for swap event storage.
 */
abstract contract StoreKeys {

    bytes32 internal constant TS_FL_AMOUNT0 = 0x17cab649bf7619b4535991407dcf8f717035632cf45997a05c0f90b7baafa479;
    bytes32 internal constant TS_FL_AMOUNT1 = 0x170e502bdc7039c895af9c291daf6592705d439a7873ee28dbc514d2f1aa51b3;
    bytes32 internal constant TS_FL_FEE0 = 0xaac705f00f1df487f4863cf5b7baa49be15a9dc73d477f33ca4d694d45cac7fe;
    bytes32 internal constant TS_FL_FEE1 = 0x2153348e08952a9737a728deab496289242e3884d90dd8e5fc8362f809e84314;

    bytes32 internal constant TS_ISP_AMOUNT0 = 0x859fad1dd1a8a0c97fb9e594529061ff17256ed2fd92004dfd6d47a8324651c4;
    bytes32 internal constant TS_ISP_AMOUNT1 = 0xee887e5283585aea7d61ae82ec91b0d9dbc7a52caa1fbc4f511651d06967058d;
    bytes32 internal constant TS_ISP_FEE0 = 0x1a426dc34b0367779dd37e66c4b193647bd2fd094d26b263dccbe93433d0a25b;
    bytes32 internal constant TS_ISP_FEE1 = 0xb5692db6de7b607ce10bbcb6a38fb443823969b63ffea1591751f25f9fe7059a;

    bytes32 internal constant TS_UNI_AMOUNT0 = 0x0f457c8132f52d9098267126b744d1c04e04ccc48dce7c5b4396b38879d8b08a;
    bytes32 internal constant TS_UNI_AMOUNT1 = 0xf5955824691119aec0d1c983542055bfb83b16d3bc8d04e6cd271bbd244e894a;
    bytes32 internal constant TS_UNI_FEE0 = 0x84457b11f2602289c00904214483ea820055ea325cc54ad9b512e76c6541dfb4;
    bytes32 internal constant TS_UNI_FEE1 = 0x6bc3f16992c8e44a3018b72b6d7aec54e64e1cdec74e64c5154c782ffe8aff2d;

}
合同源代码
文件 63 的 67:SwapMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {FullMath} from "./FullMath.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";

/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
    /// @notice the swap fee is represented in hundredths of a bip, so the max is 100%
    /// @dev the swap fee is the total fee on a swap, including both LP and Protocol fee
    uint256 internal constant MAX_SWAP_FEE = 1e6;

    /// @notice Computes the sqrt price target for the next swap step
    /// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0
    /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value
    /// after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @return sqrtPriceTargetX96 The price target for the next swap step
    function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96)
        internal
        pure
        returns (uint160 sqrtPriceTargetX96)
    {
        assembly ("memory-safe") {
            // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
            // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
            // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
            // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
            // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceNextX96 := and(sqrtPriceNextX96, 0xffffffffffffffffffffffffffffffffffffffff)
            sqrtPriceLimitX96 := and(sqrtPriceLimitX96, 0xffffffffffffffffffffffffffffffffffffffff)
            let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), and(zeroForOne, 0x1))
            let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
        }
    }

    /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
    /// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount.
    /// @param sqrtPriceCurrentX96 The current sqrt price of the pool
    /// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap
    /// @return feeAmount The amount of input that will be taken as a fee
    /// @dev feePips must be no larger than MAX_SWAP_FEE for this function. We ensure that before setting a fee using LPFeeLibrary.isValid.
    function computeSwapStep(
        uint160 sqrtPriceCurrentX96,
        uint160 sqrtPriceTargetX96,
        uint128 liquidity,
        int256 amountRemaining,
        uint24 feePips
    ) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) {
        unchecked {
            uint256 _feePips = feePips; // upcast once and cache
            bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96;
            bool exactIn = amountRemaining < 0;

            if (exactIn) {
                uint256 amountRemainingLessFee =
                    FullMath.mulDiv(uint256(-amountRemaining), MAX_SWAP_FEE - _feePips, MAX_SWAP_FEE);
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true);
                if (amountRemainingLessFee >= amountIn) {
                    // `amountIn` is capped by the target price
                    sqrtPriceNextX96 = sqrtPriceTargetX96;
                    feeAmount = _feePips == MAX_SWAP_FEE
                        ? amountIn // amountIn is always 0 here, as amountRemainingLessFee == 0 and amountRemainingLessFee >= amountIn
                        : FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips);
                } else {
                    // exhaust the remaining amount
                    amountIn = amountRemainingLessFee;
                    sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                        sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne
                    );
                    // we didn't reach the target, so take the remainder of the maximum input as fee
                    feeAmount = uint256(-amountRemaining) - amountIn;
                }
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false);
            } else {
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false);
                if (uint256(amountRemaining) >= amountOut) {
                    // `amountOut` is capped by the target price
                    sqrtPriceNextX96 = sqrtPriceTargetX96;
                } else {
                    // cap the output amount to not exceed the remaining output amount
                    amountOut = uint256(amountRemaining);
                    sqrtPriceNextX96 =
                        SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne);
                }
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true);
                // `feePips` cannot be `MAX_SWAP_FEE` for exact out
                feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips);
            }
        }
    }
}
合同源代码
文件 64 的 67:TickFinder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;


/**
 * A helper library that finds the next valid tick for the specified tick spacing, starting
 * from a single tick. This will allow us to round up or down to find it and also supports
 * negative rounding.
 *
 * This is beneficial as it allows us to create positions directly next to the current tick.
 *
 * @dev This is used by `using TickFinder for int24;`
 */
library TickFinder {

    /// The valid tick spacing value for the pool
    int24 internal constant TICK_SPACING = 60;

    /// Set our min/max tick range that is valid for the tick spacing
    int24 internal constant MIN_TICK = -887220;
    int24 internal constant MAX_TICK = 887220;

    /**
     * Helper function to find the nearest valid tick, rounding up or down.
     *
     * @param _tick The tick that we want to find a valid value for
     * @param _roundDown If we want to round down (true) or up (false)
     *
     * return tick_ The valid tick
     */
    function validTick(int24 _tick, bool _roundDown) internal pure returns (int24 tick_) {
        // If we have a malformed tick, then we need to bring it back within range
        if (_tick < MIN_TICK) _tick = MIN_TICK;
        else if (_tick > MAX_TICK) _tick = MAX_TICK;

        // If the tick is already valid, exit early
        if (_tick % TICK_SPACING == 0) {
            return _tick;
        }

        tick_ = _tick / TICK_SPACING * TICK_SPACING;
        if (_tick < 0) {
            tick_ -= TICK_SPACING;
        }

        // If we are rounding up, then we can just add a `TICK_SPACING` to the lower tick
        if (!_roundDown) {
            return tick_ + TICK_SPACING;
        }
    }

}
合同源代码
文件 65 的 67:TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            uint256 price = uint256(sqrtPriceX96) << 32;

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

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

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

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

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

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

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

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}
合同源代码
文件 66 的 67:TransientStateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

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

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

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

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

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

    /// @notice Returns whether the contract is unlocked or not
    function isUnlocked(IPoolManager manager) internal view returns (bool) {
        return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
    }
}
合同源代码
文件 67 的 67:UnsafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    /// @notice Returns ceil(x / y)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param x The dividend
    /// @param y The divisor
    /// @return z The quotient, ceil(x / y)
    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly ("memory-safe") {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }

    /// @notice Calculates floor(a×b÷denominator)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result, floor(a×b÷denominator)
    function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            result := div(mul(a, b), denominator)
        }
    }
}
设置
{
  "compilationTarget": {
    "src/contracts/PositionManager.sol": "PositionManager"
  },
  "evmVersion": "cancun",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "enabled": true,
    "runs": 0
  },
  "remappings": [
    ":@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    ":@flaunch-interfaces/=src/interfaces/",
    ":@flaunch/=src/contracts/",
    ":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":@optimism/=lib/optimism/packages/contracts-bedrock/src/",
    ":@solady/=lib/solady/src/",
    ":@uniswap-periphery/=lib/v4-periphery/src/",
    ":@uniswap/v3-core/=lib/v3-core/",
    ":@uniswap/v4-core/=lib/v4-core/",
    ":automate/=lib/optimism/packages/contracts-bedrock/lib/automate/contracts/",
    ":ds-test/=lib/vulcan/lib/forge-std/lib/ds-test/src/",
    ":erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    ":forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
    ":forge-std/=lib/forge-std/src/",
    ":halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    ":hardhat/=lib/v4-core/node_modules/hardhat/",
    ":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/",
    ":openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":optimism/=lib/optimism/",
    ":permit2/=lib/v4-periphery/lib/permit2/",
    ":prb-test/=lib/optimism/packages/contracts-bedrock/lib/automate/lib/prb-test/src/",
    ":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/",
    ":solmate/=lib/v4-core/lib/solmate/",
    ":v3-core/=lib/v3-core/",
    ":v4-core/=lib/v4-core/src/",
    ":v4-periphery/=lib/v4-periphery/",
    ":vulcan/=lib/vulcan/src/"
  ]
}
ABI
[{"inputs":[{"components":[{"internalType":"address","name":"nativeToken","type":"address"},{"internalType":"contract IPoolManager","name":"poolManager","type":"address"},{"components":[{"internalType":"uint24","name":"swapFee","type":"uint24"},{"internalType":"uint24","name":"referrer","type":"uint24"},{"internalType":"uint24","name":"protocol","type":"uint24"},{"internalType":"bool","name":"active","type":"bool"}],"internalType":"struct FeeDistributor.FeeDistribution","name":"feeDistribution","type":"tuple"},{"internalType":"contract IInitialPrice","name":"initialPrice","type":"address"},{"internalType":"address","name":"protocolOwner","type":"address"},{"internalType":"address","name":"protocolFeeRecipient","type":"address"},{"internalType":"address","name":"flayGovernance","type":"address"},{"internalType":"contract FeeExemptions","name":"feeExemptions","type":"address"}],"internalType":"struct PositionManager.ConstructorParams","name":"params","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"CallerIsNotBidWall","type":"error"},{"inputs":[{"internalType":"address","name":"_caller","type":"address"}],"name":"CallerNotCreator","type":"error"},{"inputs":[],"name":"CannotBeInitializedDirectly","type":"error"},{"inputs":[],"name":"CannotModifyLiquidityDuringFairLaunch","type":"error"},{"inputs":[],"name":"CannotSellTokenDuringFairLaunch","type":"error"},{"inputs":[],"name":"HookNotImplemented","type":"error"},{"inputs":[{"internalType":"uint256","name":"_paid","type":"uint256"},{"internalType":"uint256","name":"_required","type":"uint256"}],"name":"InsufficientFlaunchFee","type":"error"},{"inputs":[],"name":"InvalidPool","type":"error"},{"inputs":[],"name":"LockFailure","type":"error"},{"inputs":[],"name":"NewOwnerIsZeroAddress","type":"error"},{"inputs":[],"name":"NoHandoverRequest","type":"error"},{"inputs":[],"name":"NotPoolManager","type":"error"},{"inputs":[],"name":"NotSelf","type":"error"},{"inputs":[],"name":"ProtocolFeeInvalid","type":"error"},{"inputs":[],"name":"RecipientZeroAddress","type":"error"},{"inputs":[],"name":"ReferrerFeeInvalid","type":"error"},{"inputs":[],"name":"SwapFeeInvalid","type":"error"},{"inputs":[{"internalType":"uint256","name":"_flaunchesAt","type":"uint256"}],"name":"TokenNotFlaunched","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"}],"name":"UnknownPool","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"uint24","name":"_allocation","type":"uint24"}],"name":"CreatorFeeAllocationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"_payee","type":"address"},{"indexed":false,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_feeCalculator","type":"address"}],"name":"FairLaunchFeeCalculatorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_feeCalculator","type":"address"}],"name":"FeeCalculatorUpdated","type":"event"},{"anonymous":false,"inputs":[{"components":[{"internalType":"uint24","name":"swapFee","type":"uint24"},{"internalType":"uint24","name":"referrer","type":"uint24"},{"internalType":"uint24","name":"protocol","type":"uint24"},{"internalType":"bool","name":"active","type":"bool"}],"indexed":false,"internalType":"struct FeeDistributor.FeeDistribution","name":"_feeDistribution","type":"tuple"}],"name":"FeeDistributionUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_initialPrice","type":"address"}],"name":"InitialPriceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"_memecoin","type":"address"},{"indexed":false,"internalType":"address","name":"_memecoinTreasury","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tokenId","type":"uint256"},{"indexed":false,"internalType":"bool","name":"_currencyFlipped","type":"bool"},{"indexed":false,"internalType":"uint256","name":"_flaunchFee","type":"uint256"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"tokenUri","type":"string"},{"internalType":"uint256","name":"initialTokenFairLaunch","type":"uint256"},{"internalType":"uint256","name":"premineAmount","type":"uint256"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"uint24","name":"creatorFeeAllocation","type":"uint24"},{"internalType":"uint256","name":"flaunchAt","type":"uint256"},{"internalType":"bytes","name":"initialPriceParams","type":"bytes"},{"internalType":"bytes","name":"feeCalculatorParams","type":"bytes"}],"indexed":false,"internalType":"struct PositionManager.FlaunchParams","name":"_params","type":"tuple"}],"name":"PoolCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"components":[{"internalType":"uint24","name":"swapFee","type":"uint24"},{"internalType":"uint24","name":"referrer","type":"uint24"},{"internalType":"uint24","name":"protocol","type":"uint24"},{"internalType":"bool","name":"active","type":"bool"}],"indexed":false,"internalType":"struct FeeDistributor.FeeDistribution","name":"_feeDistribution","type":"tuple"}],"name":"PoolFeeDistributionUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"_donateAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_creatorAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_bidWallAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_governanceAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_protocolAmount","type":"uint256"}],"name":"PoolFeesDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"_amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_amount1","type":"uint256"}],"name":"PoolFeesReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"zeroForOne","type":"bool"},{"indexed":false,"internalType":"uint256","name":"_amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_amount1","type":"uint256"}],"name":"PoolFeesSwapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"int256","name":"_premineAmount","type":"int256"}],"name":"PoolPremine","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"_flaunchesAt","type":"uint256"}],"name":"PoolScheduled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"uint160","name":"_sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"int24","name":"_tick","type":"int24"},{"indexed":false,"internalType":"uint24","name":"_protocolFee","type":"uint24"},{"indexed":false,"internalType":"uint24","name":"_swapFee","type":"uint24"},{"indexed":false,"internalType":"uint128","name":"_liquidity","type":"uint128"}],"name":"PoolStateUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"int256","name":"flAmount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"flAmount1","type":"int256"},{"indexed":false,"internalType":"int256","name":"flFee0","type":"int256"},{"indexed":false,"internalType":"int256","name":"flFee1","type":"int256"},{"indexed":false,"internalType":"int256","name":"ispAmount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"ispAmount1","type":"int256"},{"indexed":false,"internalType":"int256","name":"ispFee0","type":"int256"},{"indexed":false,"internalType":"int256","name":"ispFee1","type":"int256"},{"indexed":false,"internalType":"int256","name":"uniAmount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"uniAmount1","type":"int256"},{"indexed":false,"internalType":"int256","name":"uniFee0","type":"int256"},{"indexed":false,"internalType":"int256","name":"uniFee1","type":"int256"}],"name":"PoolSwap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_referralEscrow","type":"address"}],"name":"ReferralEscrowUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"_recipient","type":"address"},{"indexed":false,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"ReferrerFeePaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_sender","type":"address"},{"indexed":false,"internalType":"address","name":"_recipient","type":"address"},{"indexed":false,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"Withdrawal","type":"event"},{"inputs":[],"name":"MAX_PROTOCOL_ALLOCATION","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_DISTRIBUTE_THRESHOLD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"actionManager","outputs":[{"internalType":"contract TreasuryActionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"","type":"tuple"},{"internalType":"BalanceDelta","name":"_delta","type":"int256"},{"internalType":"BalanceDelta","name":"_feesAccrued","type":"int256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"afterAddLiquidity","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"},{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"internalType":"uint256","name":"_amount0","type":"uint256"},{"internalType":"uint256","name":"_amount1","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"afterDonate","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"","type":"tuple"},{"internalType":"uint160","name":"","type":"uint160"},{"internalType":"int24","name":"","type":"int24"}],"name":"afterInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"","type":"tuple"},{"internalType":"BalanceDelta","name":"_delta","type":"int256"},{"internalType":"BalanceDelta","name":"_feesAccrued","type":"int256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"afterRemoveLiquidity","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"},{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"_params","type":"tuple"},{"internalType":"BalanceDelta","name":"_delta","type":"int256"},{"internalType":"bytes","name":"_hookData","type":"bytes"}],"name":"afterSwap","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"},{"internalType":"int128","name":"hookDeltaUnspecified_","type":"int128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"}],"name":"balances","outputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"","type":"tuple"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"beforeAddLiquidity","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"","type":"tuple"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"beforeDonate","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"","type":"tuple"},{"internalType":"uint160","name":"","type":"uint160"}],"name":"beforeInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"","type":"tuple"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"beforeRemoveLiquidity","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"_params","type":"tuple"},{"internalType":"bytes","name":"_hookData","type":"bytes"}],"name":"beforeSwap","outputs":[{"internalType":"bytes4","name":"selector_","type":"bytes4"},{"internalType":"BeforeSwapDelta","name":"beforeSwapDelta_","type":"int256"},{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"bidWall","outputs":[{"internalType":"contract BidWall","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cancelOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_key","type":"tuple"}],"name":"closeBidWall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"completeOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"fairLaunch","outputs":[{"internalType":"contract FairLaunch","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fairLaunchFeeCalculator","outputs":[{"internalType":"contract IFeeCalculator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeCalculator","outputs":[{"internalType":"contract IFeeCalculator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeExemptions","outputs":[{"internalType":"contract FeeExemptions","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"feeSplit","outputs":[{"internalType":"uint256","name":"bidWall_","type":"uint256"},{"internalType":"uint256","name":"creator_","type":"uint256"},{"internalType":"uint256","name":"protocol_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"tokenUri","type":"string"},{"internalType":"uint256","name":"initialTokenFairLaunch","type":"uint256"},{"internalType":"uint256","name":"premineAmount","type":"uint256"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"uint24","name":"creatorFeeAllocation","type":"uint24"},{"internalType":"uint256","name":"flaunchAt","type":"uint256"},{"internalType":"bytes","name":"initialPriceParams","type":"bytes"},{"internalType":"bytes","name":"feeCalculatorParams","type":"bytes"}],"internalType":"struct PositionManager.FlaunchParams","name":"_params","type":"tuple"}],"name":"flaunch","outputs":[{"internalType":"address","name":"memecoin_","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"flaunchContract","outputs":[{"internalType":"contract IFlaunch","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"}],"name":"flaunchesAt","outputs":[{"internalType":"uint256","name":"_flaunchTime","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"flayGovernance","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_isFairLaunch","type":"bool"}],"name":"getFeeCalculator","outputs":[{"internalType":"contract IFeeCalculator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_initialPriceParams","type":"bytes"}],"name":"getFlaunchingFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_initialPriceParams","type":"bytes"}],"name":"getFlaunchingMarketCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHookPermissions","outputs":[{"components":[{"internalType":"bool","name":"beforeInitialize","type":"bool"},{"internalType":"bool","name":"afterInitialize","type":"bool"},{"internalType":"bool","name":"beforeAddLiquidity","type":"bool"},{"internalType":"bool","name":"afterAddLiquidity","type":"bool"},{"internalType":"bool","name":"beforeRemoveLiquidity","type":"bool"},{"internalType":"bool","name":"afterRemoveLiquidity","type":"bool"},{"internalType":"bool","name":"beforeSwap","type":"bool"},{"internalType":"bool","name":"afterSwap","type":"bool"},{"internalType":"bool","name":"beforeDonate","type":"bool"},{"internalType":"bool","name":"afterDonate","type":"bool"},{"internalType":"bool","name":"beforeSwapReturnDelta","type":"bool"},{"internalType":"bool","name":"afterSwapReturnDelta","type":"bool"},{"internalType":"bool","name":"afterAddLiquidityReturnDelta","type":"bool"},{"internalType":"bool","name":"afterRemoveLiquidityReturnDelta","type":"bool"}],"internalType":"struct Hooks.Permissions","name":"","type":"tuple"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"}],"name":"getPoolFeeDistribution","outputs":[{"components":[{"internalType":"uint24","name":"swapFee","type":"uint24"},{"internalType":"uint24","name":"referrer","type":"uint24"},{"internalType":"uint24","name":"protocol","type":"uint24"},{"internalType":"bool","name":"active","type":"bool"}],"internalType":"struct FeeDistributor.FeeDistribution","name":"feeDistribution_","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialPrice","outputs":[{"internalType":"contract IInitialPrice","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nativeToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"notifier","outputs":[{"internalType":"contract Notifier","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"ownershipHandoverExpiresAt","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_poolKey","type":"tuple"}],"name":"poolFees","outputs":[{"components":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"internalType":"struct InternalSwapPool.ClaimableFees","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"poolKey","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"}],"name":"premineInfo","outputs":[{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint256","name":"blockNumber","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referralEscrow","outputs":[{"internalType":"contract ReferralEscrow","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"requestOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IFeeCalculator","name":"_feeCalculator","type":"address"}],"name":"setFairLaunchFeeCalculator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IFeeCalculator","name":"_feeCalculator","type":"address"}],"name":"setFeeCalculator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint24","name":"swapFee","type":"uint24"},{"internalType":"uint24","name":"referrer","type":"uint24"},{"internalType":"uint24","name":"protocol","type":"uint24"},{"internalType":"bool","name":"active","type":"bool"}],"internalType":"struct FeeDistributor.FeeDistribution","name":"_feeDistribution","type":"tuple"}],"name":"setFeeDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_flaunchContract","type":"address"}],"name":"setFlaunch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_initialPrice","type":"address"}],"name":"setInitialPrice","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"_poolId","type":"bytes32"},{"components":[{"internalType":"uint24","name":"swapFee","type":"uint24"},{"internalType":"uint24","name":"referrer","type":"uint24"},{"internalType":"uint24","name":"protocol","type":"uint24"},{"internalType":"bool","name":"active","type":"bool"}],"internalType":"struct FeeDistributor.FeeDistribution","name":"_feeDistribution","type":"tuple"}],"name":"setPoolFeeDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint24","name":"_protocol","type":"uint24"}],"name":"setProtocolFeeDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_referralEscrow","type":"address"}],"name":"setReferralEscrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"bool","name":"_unwrap","type":"bool"}],"name":"withdrawFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]