Base Sepolia Testnet

Contract

0x3345E557c5C0b474bE1eb4693264008B8562Aa9c
Source Code Source Code
Transaction Hash
Method
Block
From
To
Amount
Approve Migrator370122312026-01-30 17:05:5014 days ago1769792750IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00144
Transfer Ownersh...370119872026-01-30 16:57:4214 days ago1769792262IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00144
Approve Migrator368414922026-01-26 18:14:3218 days ago1769451272IN
0x3345E557...B8562Aa9c
0 ETH0.000000070.00144
Approve Migrator352003882025-12-19 18:31:0456 days ago1766169064IN
0x3345E557...B8562Aa9c
0 ETH0.000000060.00144
Approve Migrator351986042025-12-19 17:31:3656 days ago1766165496IN
0x3345E557...B8562Aa9c
0 ETH0.000000020.00117
Approve Migrator351985992025-12-19 17:31:2656 days ago1766165486IN
0x3345E557...B8562Aa9c
0 ETH0.000000020.00117
Approve Migrator351985542025-12-19 17:29:5656 days ago1766165396IN
0x3345E557...B8562Aa9c
0 ETH0.000000020.00117134
Approve Migrator351985482025-12-19 17:29:4456 days ago1766165384IN
0x3345E557...B8562Aa9c
0 ETH0.000000020.00117
Distribute Fees335614982025-11-11 20:01:2494 days ago1762891284IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00097005
Release Fees283707322025-07-14 16:15:52214 days ago1752509752IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00094095
Distribute Fees283707272025-07-14 16:15:42214 days ago1752509742IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00094095
Distribute Fees283706862025-07-14 16:14:20214 days ago1752509660IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00097005
Distribute Fees282499542025-07-11 21:09:56217 days ago1752268196IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00097005
Release Fees282499102025-07-11 21:08:28217 days ago1752268108IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00097005
Distribute Fees282497502025-07-11 21:03:08217 days ago1752267788IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00097005
Release Fees282497412025-07-11 21:02:50217 days ago1752267770IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00097005
Approve Migrator279318652025-07-04 12:26:58224 days ago1751632018IN
0x3345E557...B8562Aa9c
0 ETH0.000000050.00120014
Approve Migrator279021092025-07-03 19:55:06225 days ago1751572506IN
0x3345E557...B8562Aa9c
0 ETH0.000000050.00120006
Approve Migrator278872982025-07-03 11:41:24225 days ago1751542884IN
0x3345E557...B8562Aa9c
0 ETH0.000000070.00120021
Approve Migrator278056782025-07-01 14:20:44227 days ago1751379644IN
0x3345E557...B8562Aa9c
0 ETH0.000000120.00120015
Approve Migrator276398082025-06-27 18:11:44231 days ago1751047904IN
0x3345E557...B8562Aa9c
0 ETH00.00000657
Approve Migrator275571252025-06-25 20:15:38233 days ago1750882538IN
0x3345E557...B8562Aa9c
0 ETH0.000000040.00099965

Latest 4 internal transactions

Parent Transaction Hash Block From To Amount
360602442026-01-08 16:12:5636 days ago1767888776
0x3345E557...B8562Aa9c
1 wei
360595832026-01-08 15:50:5436 days ago1767887454
0x3345E557...B8562Aa9c
20 wei
359757462026-01-06 17:16:2038 days ago1767719780
0x3345E557...B8562Aa9c
1 wei
359749672026-01-06 16:50:2238 days ago1767718222
0x3345E557...B8562Aa9c
25 wei

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
StreamableFeesLocker

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 0 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

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

import { IPositionManager } from "@v4-periphery/interfaces/IPositionManager.sol";
import { Actions } from "@v4-periphery/libraries/Actions.sol";
import { PoolKey } from "@v4-core/types/PoolKey.sol";
import { Currency } from "@v4-core/types/Currency.sol";
import { ERC721, ERC721TokenReceiver } from "@solmate/tokens/ERC721.sol";
import { ReentrancyGuard } from "@solady/utils/ReentrancyGuard.sol";
import { Ownable } from "@openzeppelin/access/Ownable.sol";
/// @notice Data structure for beneficiary information
/// @param beneficiary Address of the beneficiary
/// @param shares Share of fees allocated to this beneficiary (in WAD)

struct BeneficiaryData {
    address beneficiary;
    uint96 shares;
}

/// @notice Data structure for position information
/// @param recipient Address that will receive the NFT after unlocking
/// @param startDate Timestamp when the position was locked
/// @param lockDuration Duration of the position lock
/// @param isUnlocked Whether the position has been unlocked
/// @param beneficiaries Array of beneficiaries and their shares
struct PositionData {
    address recipient;
    uint32 startDate;
    uint32 lockDuration;
    bool isUnlocked;
    BeneficiaryData[] beneficiaries;
}

/// @notice Thrown when a non-position manager calls a function
error NonPositionManager();

/// @notice Thrown when a migrator is not approved
error NotApprovedMigrator();

/// @notice Thrown when a position is not found
error PositionNotFound();

/// @notice Thrown when a position is already unlocked
error PositionAlreadyUnlocked();

/// @notice Thrown when a beneficiary is invalid
error InvalidBeneficiary();

/// @notice Emitted when a position is locked
/// @param tokenId The ID of the locked position
/// @param beneficiaries Array of beneficiaries and their shares
/// @param unlockDate Timestamp when the position will be unlocked
event Lock(uint256 indexed tokenId, BeneficiaryData[] beneficiaries, uint256 unlockDate);

/// @notice Emitted when a position is unlocked
/// @param tokenId The ID of the unlocked position
/// @param recipient Address that received the NFT
event Unlock(uint256 indexed tokenId, address recipient);

/// @notice Emitted when fees are distributed to a beneficiary
/// @param tokenId The ID of the position
/// @param amount0 Amount of token0 distributed
/// @param amount1 Amount of token1 distributed
event DistributeFees(uint256 indexed tokenId, uint256 amount0, uint256 amount1);

/// @notice Emitted when fees are released to a beneficiary
/// @param tokenId The ID of the position
/// @param beneficiary Address that received the fees
/// @param amount0 Amount of token0 released
/// @param amount1 Amount of token1 released
event Release(uint256 indexed tokenId, address beneficiary, uint256 amount0, uint256 amount1);

/// @notice Emitted when a beneficiary is updated
/// @param tokenId The ID of the position
/// @param oldBeneficiary Previous beneficiary address
/// @param newBeneficiary New beneficiary address
event UpdateBeneficiary(uint256 indexed tokenId, address oldBeneficiary, address newBeneficiary);

/// @notice Emitted when a migrator is approved
/// @param migrator Address of the migrator
/// @param approval Whether the migrator is approved
event MigratorApproval(address indexed migrator, bool approval);

/// @dev WAD constant for precise decimal calculations
uint256 constant WAD = 1e18;

/// @dev The dead address used for no-op governance
address constant DEAD_ADDRESS = address(0xdead);

/// @title StreamableFeesLocker
/// @notice A contract that manages fee streaming for Uniswap V4 positions
/// @dev Allows locking positions for a specified duration and streaming fees to multiple beneficiaries
/// @dev Uses instant distribution mechanism for fees
contract StreamableFeesLocker is ERC721TokenReceiver, ReentrancyGuard, Ownable {
    /// @notice Address of the Uniswap V4 position manager
    IPositionManager public immutable positionManager;

    /// @notice Mapping of token IDs to their position data
    mapping(uint256 tokenId => PositionData) public positions;

    /// @notice Mapping of beneficiary addresses to their claimable balances for each currency
    mapping(address beneficiary => mapping(Currency currency => uint256 releasableBalance)) public beneficiariesClaims;

    /// @notice Mapping of currency balances in the contract
    mapping(Currency currency => uint256 balanceOfSelf) public currencyBalances;

    /// @notice Mapping of approved migrators
    mapping(address migrator => bool approved) public approvedMigrators;

    /// @notice Anyone can send ETH to this contract
    receive() external payable { }

    /// @notice Constructor
    /// @param positionManager_ Address of the Uniswap V4 position manager
    /// @param owner_ Address of the owner of the contract
    constructor(IPositionManager positionManager_, address owner_) Ownable(owner_) {
        positionManager = positionManager_;
    }

    /// @notice Modifier to restrict function access to the position manager
    modifier onlyPositionManager() {
        if (msg.sender != address(positionManager)) {
            revert NonPositionManager();
        }
        _;
    }

    /// @notice Modifier to restrict sender to approved migrators only
    /// @param migrator Address of the migrator
    modifier onlyApprovedMigrator(
        address migrator
    ) {
        if (!approvedMigrators[migrator]) {
            revert NotApprovedMigrator();
        }
        _;
    }

    /// @notice Handles incoming ERC721 tokens and initializes position data
    /// @param from Address that is transferring the token
    /// @param tokenId ID of the token being transferred
    /// @param positionData Encoded data containing recipient and beneficiaries
    /// @return bytes4 The ERC721 receiver selector
    function onERC721Received(
        address, // operator (unused)
        address from,
        uint256 tokenId,
        bytes calldata positionData
    ) external override onlyPositionManager onlyApprovedMigrator(from) returns (bytes4) {
        (address recipient, uint32 lockDuration, BeneficiaryData[] memory beneficiaries) =
            abi.decode(positionData, (address, uint32, BeneficiaryData[]));

        // Note: If recipient is DEAD_ADDRESS (0xdead), the position will be permanently locked
        // and beneficiaries can collect fees in perpetuity
        positions[tokenId] = PositionData({
            beneficiaries: beneficiaries,
            startDate: uint32(block.timestamp),
            isUnlocked: false,
            recipient: recipient,
            lockDuration: lockDuration
        });

        emit Lock(tokenId, beneficiaries, recipient != DEAD_ADDRESS ? block.timestamp + lockDuration : 0);

        return ERC721TokenReceiver.onERC721Received.selector;
    }

    /// @notice Accrues and distributes fees for a position
    /// @param tokenId ID of the position to accrue fees for
    function distributeFees(
        uint256 tokenId
    ) external nonReentrant {
        PositionData memory position = positions[tokenId];
        require(position.startDate != 0, PositionNotFound());
        require(position.isUnlocked != true, PositionAlreadyUnlocked());

        // Get pool info
        (PoolKey memory poolKey,) = positionManager.getPoolAndPositionInfo(tokenId);

        // Get the amount of fees to claim
        bytes memory actions = abi.encodePacked(uint8(Actions.DECREASE_LIQUIDITY), uint8(Actions.TAKE_PAIR));
        bytes[] memory params = new bytes[](2);
        params[0] = abi.encode(tokenId, 0, 0, 0, new bytes(0));
        params[1] = abi.encode(poolKey.currency0, poolKey.currency1, address(this));

        positionManager.modifyLiquidities(abi.encode(actions, params), block.timestamp);

        BeneficiaryData[] memory beneficiaries = position.beneficiaries;

        (uint256 currency0ToDistribute, uint256 currency1ToDistribute) = _updateCurrencyBalances(poolKey);

        uint256 amount0Distributed;
        uint256 amount1Distributed;
        address beneficiary;
        for (uint256 i; i < beneficiaries.length; ++i) {
            beneficiary = beneficiaries[i].beneficiary;
            uint256 shares = beneficiaries[i].shares;

            // Calculate share of fees for this beneficiary
            uint256 amount0 = currency0ToDistribute * shares / WAD;
            uint256 amount1 = currency1ToDistribute * shares / WAD;

            amount0Distributed += amount0;
            amount1Distributed += amount1;

            if (i == beneficiaries.length - 1) {
                // Distribute the remaining fees to the last beneficiary
                amount0 += currency0ToDistribute > amount0Distributed ? currency0ToDistribute - amount0Distributed : 0;
                amount1 += currency1ToDistribute > amount1Distributed ? currency1ToDistribute - amount1Distributed : 0;
            }

            _distributeFees(beneficiary, poolKey, amount0, amount1);
        }

        // Note: For no-op governance, if recipient is DEAD_ADDRESS (0xdead), the position will be permanently locked
        // and beneficiaries can collect fees in perpetuity
        if (block.timestamp >= position.startDate + position.lockDuration && position.recipient != DEAD_ADDRESS) {
            position.isUnlocked = true;

            // Update the position in storage
            positions[tokenId] = position;

            // Transfer the position to the recipient (if the recipient is a contract, it must implement `onERC721Received`)
            ERC721(address(positionManager)).safeTransferFrom(address(this), position.recipient, tokenId, new bytes(0));

            emit Unlock(tokenId, position.recipient);
        } else {
            // Update the position in storage
            positions[tokenId] = position;
        }

        emit DistributeFees(tokenId, currency0ToDistribute, currency1ToDistribute);
    }

    /// @notice Releases accrued fees to the caller
    /// @param tokenId ID of the position to release fees from
    function releaseFees(
        uint256 tokenId
    ) external nonReentrant {
        // Check if position exists
        PositionData memory position = positions[tokenId];
        require(position.startDate != 0, PositionNotFound());

        // Check if sender is a beneficiary
        bool isBeneficiary = false;
        for (uint256 i = 0; i < position.beneficiaries.length; i++) {
            if (position.beneficiaries[i].beneficiary == msg.sender) {
                isBeneficiary = true;
                break;
            }
        }
        require(isBeneficiary, InvalidBeneficiary());

        _releaseFees(tokenId, msg.sender);
    }

    /// @notice Updates currency balances and calculates distributable amounts
    /// @param poolKey Pool information
    /// @return amount0ToDistribute Amount of token0 to distribute
    /// @return amount1ToDistribute Amount of token1 to distribute
    function _updateCurrencyBalances(
        PoolKey memory poolKey
    ) internal returns (uint256 amount0ToDistribute, uint256 amount1ToDistribute) {
        // Cache currency balances for reentrancy protection
        uint256 currency0Balance = poolKey.currency0.balanceOfSelf();
        uint256 currency1Balance = poolKey.currency1.balanceOfSelf();

        // Calculate the amount of fees to distribute
        amount0ToDistribute = currency0Balance - currencyBalances[poolKey.currency0];
        amount1ToDistribute = currency1Balance - currencyBalances[poolKey.currency1];

        // Update the global balance
        currencyBalances[poolKey.currency0] += amount0ToDistribute;
        currencyBalances[poolKey.currency1] += amount1ToDistribute;
    }

    /// @notice Distributes fees to a beneficiary
    /// @param beneficiary Address to distribute fees to
    /// @param poolKey Pool information
    /// @param amount0 Amount of token0 to distribute
    /// @param amount1 Amount of token1 to distribute
    function _distributeFees(address beneficiary, PoolKey memory poolKey, uint256 amount0, uint256 amount1) internal {
        beneficiariesClaims[beneficiary][poolKey.currency0] += amount0;
        beneficiariesClaims[beneficiary][poolKey.currency1] += amount1;
    }

    /// @notice Releases fees to a beneficiary
    /// @param tokenId ID of the position
    /// @param beneficiary Address to release fees to
    function _releaseFees(uint256 tokenId, address beneficiary) internal {
        // Get pool info
        (PoolKey memory poolKey,) = positionManager.getPoolAndPositionInfo(tokenId);

        // Get the amount of fees to release
        uint256 amount0ToRelease = beneficiariesClaims[beneficiary][poolKey.currency0];
        uint256 amount1ToRelease = beneficiariesClaims[beneficiary][poolKey.currency1];

        // Reset the claims
        beneficiariesClaims[beneficiary][poolKey.currency0] = 0;
        beneficiariesClaims[beneficiary][poolKey.currency1] = 0;

        // Update currency balances
        currencyBalances[poolKey.currency0] -= amount0ToRelease;
        currencyBalances[poolKey.currency1] -= amount1ToRelease;

        // Release the fees
        if (amount0ToRelease > 0) {
            poolKey.currency0.transfer(beneficiary, amount0ToRelease);
        }
        if (amount1ToRelease > 0) {
            poolKey.currency1.transfer(beneficiary, amount1ToRelease);
        }

        emit Release(tokenId, beneficiary, amount0ToRelease, amount1ToRelease);
    }

    /// @notice Updates the beneficiary address for a position
    /// @param tokenId ID of the position
    /// @param newBeneficiary New beneficiary address
    function updateBeneficiary(uint256 tokenId, address newBeneficiary) external nonReentrant {
        // Get position data
        PositionData memory position = positions[tokenId];
        require(position.startDate != 0, PositionNotFound());
        require(newBeneficiary != address(0), InvalidBeneficiary());

        // Get the index of the beneficiary to transfer ownership to `newBeneficiary`
        uint256 length = position.beneficiaries.length;
        bool found = false;
        for (uint256 i; i != length; ++i) {
            if (position.beneficiaries[i].beneficiary == msg.sender) {
                // Release fees for the old beneficiary
                _releaseFees(tokenId, msg.sender);

                // Update the beneficiary
                position.beneficiaries[i].beneficiary = newBeneficiary;
                found = true;
                break;
            }
        }
        require(found, InvalidBeneficiary());

        // Update the position data
        positions[tokenId] = position;

        emit UpdateBeneficiary(tokenId, msg.sender, newBeneficiary);
    }

    /// @notice Approves a migrator
    /// @param migrator Address of the migrator
    function approveMigrator(
        address migrator
    ) external onlyOwner {
        if (!approvedMigrators[migrator]) {
            approvedMigrators[migrator] = true;
            emit MigratorApproval(address(migrator), true);
        }
    }

    /// @notice Revokes a migrator
    /// @param migrator Address of the migrator
    function revokeMigrator(
        address migrator
    ) external onlyOwner {
        if (approvedMigrators[migrator]) {
            approvedMigrators[migrator] = false;
            emit MigratorApproval(address(migrator), false);
        }
    }
}

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";

import {INotifier} from "./INotifier.sol";
import {IImmutableState} from "./IImmutableState.sol";
import {IERC721Permit_v4} from "./IERC721Permit_v4.sol";
import {IEIP712_v4} from "./IEIP712_v4.sol";
import {IMulticall_v4} from "./IMulticall_v4.sol";
import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol";
import {IUnorderedNonce} from "./IUnorderedNonce.sol";
import {IPermit2Forwarder} from "./IPermit2Forwarder.sol";

/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is
    INotifier,
    IImmutableState,
    IERC721Permit_v4,
    IEIP712_v4,
    IMulticall_v4,
    IPoolInitializer_v4,
    IUnorderedNonce,
    IPermit2Forwarder
{
    /// @notice Thrown when the caller is not approved to modify a position
    error NotApproved(address caller);
    /// @notice Thrown when the block.timestamp exceeds the user-provided deadline
    error DeadlinePassed(uint256 deadline);
    /// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked.
    /// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified.
    error PoolManagerMustBeLocked();

    /// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
    /// @dev This is the standard entrypoint for the PositionManager
    /// @param unlockData is an encoding of actions, and parameters for those actions
    /// @param deadline is the deadline for the batched actions to be executed
    function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;

    /// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager
    /// @dev This must be called by a contract that has already unlocked the v4 PoolManager
    /// @param actions the actions to perform
    /// @param params the parameters to provide for the actions
    function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;

    /// @notice Used to get the ID that will be used for the next minted liquidity position
    /// @return uint256 The next token ID
    function nextTokenId() external view returns (uint256);

    /// @notice Returns the liquidity of a position
    /// @param tokenId the ERC721 tokenId
    /// @return liquidity the position's liquidity, as a liquidityAmount
    /// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library
    function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity);

    /// @notice Returns the pool key and position info of a position
    /// @param tokenId the ERC721 tokenId
    /// @return poolKey the pool key of the position
    /// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
    function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);

    /// @notice Returns the position info of a position
    /// @param tokenId the ERC721 tokenId
    /// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
    function positionInfo(uint256 tokenId) external view returns (PositionInfo);
}

File 3 of 33 : Actions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
    // pool actions
    // liquidity actions
    uint256 internal constant INCREASE_LIQUIDITY = 0x00;
    uint256 internal constant DECREASE_LIQUIDITY = 0x01;
    uint256 internal constant MINT_POSITION = 0x02;
    uint256 internal constant BURN_POSITION = 0x03;
    uint256 internal constant INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
    uint256 internal constant MINT_POSITION_FROM_DELTAS = 0x05;

    // swapping
    uint256 internal constant SWAP_EXACT_IN_SINGLE = 0x06;
    uint256 internal constant SWAP_EXACT_IN = 0x07;
    uint256 internal constant SWAP_EXACT_OUT_SINGLE = 0x08;
    uint256 internal constant SWAP_EXACT_OUT = 0x09;

    // donate
    // note this is not supported in the position manager or router
    uint256 internal constant DONATE = 0x0a;

    // closing deltas on the pool manager
    // settling
    uint256 internal constant SETTLE = 0x0b;
    uint256 internal constant SETTLE_ALL = 0x0c;
    uint256 internal constant SETTLE_PAIR = 0x0d;
    // taking
    uint256 internal constant TAKE = 0x0e;
    uint256 internal constant TAKE_ALL = 0x0f;
    uint256 internal constant TAKE_PORTION = 0x10;
    uint256 internal constant TAKE_PAIR = 0x11;

    uint256 internal constant CLOSE_CURRENCY = 0x12;
    uint256 internal constant CLEAR_OR_TAKE = 0x13;
    uint256 internal constant SWEEP = 0x14;

    uint256 internal constant WRAP = 0x15;
    uint256 internal constant UNWRAP = 0x16;

    // minting/burning 6909s to close deltas
    // note this is not supported in the position manager or router
    uint256 internal constant MINT_6909 = 0x17;
    uint256 internal constant BURN_6909 = 0x18;
}

File 4 of 33 : 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;
}

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

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

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

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

    /*//////////////////////////////////////////////////////////////
                         METADATA STORAGE/LOGIC
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    function tokenURI(uint256 id) public view virtual returns (string memory);

    /*//////////////////////////////////////////////////////////////
                      ERC721 BALANCE/OWNER STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 => address) internal _ownerOf;

    mapping(address => uint256) internal _balanceOf;

    function ownerOf(uint256 id) public view virtual returns (address owner) {
        require((owner = _ownerOf[id]) != address(0), "NOT_MINTED");
    }

    function balanceOf(address owner) public view virtual returns (uint256) {
        require(owner != address(0), "ZERO_ADDRESS");

        return _balanceOf[owner];
    }

    /*//////////////////////////////////////////////////////////////
                         ERC721 APPROVAL STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 => address) public getApproved;

    mapping(address => mapping(address => bool)) public isApprovedForAll;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(string memory _name, string memory _symbol) {
        name = _name;
        symbol = _symbol;
    }

    /*//////////////////////////////////////////////////////////////
                              ERC721 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 id) public virtual {
        address owner = _ownerOf[id];

        require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");

        getApproved[id] = spender;

        emit Approval(owner, spender, id);
    }

    function setApprovalForAll(address operator, bool approved) public virtual {
        isApprovedForAll[msg.sender][operator] = approved;

        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function transferFrom(
        address from,
        address to,
        uint256 id
    ) public virtual {
        require(from == _ownerOf[id], "WRONG_FROM");

        require(to != address(0), "INVALID_RECIPIENT");

        require(
            msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
            "NOT_AUTHORIZED"
        );

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        unchecked {
            _balanceOf[from]--;

            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        delete getApproved[id];

        emit Transfer(from, to, id);
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id
    ) public virtual {
        transferFrom(from, to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        bytes calldata data
    ) public virtual {
        transferFrom(from, to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    /*//////////////////////////////////////////////////////////////
                              ERC165 LOGIC
    //////////////////////////////////////////////////////////////*/

    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return
            interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
            interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
            interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 id) internal virtual {
        require(to != address(0), "INVALID_RECIPIENT");

        require(_ownerOf[id] == address(0), "ALREADY_MINTED");

        // Counter overflow is incredibly unrealistic.
        unchecked {
            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        emit Transfer(address(0), to, id);
    }

    function _burn(uint256 id) internal virtual {
        address owner = _ownerOf[id];

        require(owner != address(0), "NOT_MINTED");

        // Ownership check above ensures no underflow.
        unchecked {
            _balanceOf[owner]--;
        }

        delete _ownerOf[id];

        delete getApproved[id];

        emit Transfer(owner, address(0), id);
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL SAFE MINT LOGIC
    //////////////////////////////////////////////////////////////*/

    function _safeMint(address to, uint256 id) internal virtual {
        _mint(to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function _safeMint(
        address to,
        uint256 id,
        bytes memory data
    ) internal virtual {
        _mint(to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }
}

/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721TokenReceiver {
    function onERC721Received(
        address,
        address,
        uint256,
        bytes calldata
    ) external virtual returns (bytes4) {
        return ERC721TokenReceiver.onERC721Received.selector;
    }
}

File 7 of 33 : 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)
            }
        }
        _;
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * @dev PositionInfo is a packed version of solidity structure.
 * Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
 *
 * Layout:
 * 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
 *
 * Fields in the direction from the least significant bit:
 *
 * A flag to know if the tokenId is subscribed to an address
 * uint8 hasSubscriber;
 *
 * The tickUpper of the position
 * int24 tickUpper;
 *
 * The tickLower of the position
 * int24 tickLower;
 *
 * The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
 * bytes25 poolId;
 *
 * Note: If more bits are needed, hasSubscriber can be a single bit.
 *
 */
type PositionInfo is uint256;

using PositionInfoLibrary for PositionInfo global;

library PositionInfoLibrary {
    PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);

    uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
    uint256 internal constant MASK_8_BITS = 0xFF;
    uint24 internal constant MASK_24_BITS = 0xFFFFFF;
    uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
    uint256 internal constant SET_SUBSCRIBE = 0x01;
    uint8 internal constant TICK_LOWER_OFFSET = 8;
    uint8 internal constant TICK_UPPER_OFFSET = 32;

    /// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
    function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
        assembly ("memory-safe") {
            _poolId := and(MASK_UPPER_200_BITS, info)
        }
    }

    function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
        assembly ("memory-safe") {
            _tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
        }
    }

    function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
        assembly ("memory-safe") {
            _tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
        }
    }

    function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
        assembly ("memory-safe") {
            _hasSubscriber := and(MASK_8_BITS, info)
        }
    }

    /// @dev this does not actually set any storage
    function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
        assembly ("memory-safe") {
            _info := or(info, SET_SUBSCRIBE)
        }
    }

    /// @dev this does not actually set any storage
    function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
        assembly ("memory-safe") {
            _info := and(info, SET_UNSUBSCRIBE)
        }
    }

    /// @notice Creates the default PositionInfo struct
    /// @dev Called when minting a new position
    /// @param _poolKey the pool key of the position
    /// @param _tickLower the lower tick of the position
    /// @param _tickUpper the upper tick of the position
    /// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
    function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
        internal
        pure
        returns (PositionInfo info)
    {
        bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
        assembly {
            info :=
                or(
                    or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
                    shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
                )
        }
    }
}

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

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

/// @title INotifier
/// @notice Interface for the Notifier contract
interface INotifier {
    /// @notice Thrown when unsubscribing without a subscriber
    error NotSubscribed();
    /// @notice Thrown when a subscriber does not have code
    error NoCodeSubscriber();
    /// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications
    error GasLimitTooLow();
    /// @notice Wraps the revert message of the subscriber contract on a reverting subscription
    error SubscriptionReverted(address subscriber, bytes reason);
    /// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification
    error ModifyLiquidityNotificationReverted(address subscriber, bytes reason);
    /// @notice Wraps the revert message of the subscriber contract on a reverting burn notification
    error BurnNotificationReverted(address subscriber, bytes reason);
    /// @notice Thrown when a tokenId already has a subscriber
    error AlreadySubscribed(uint256 tokenId, address subscriber);

    /// @notice Emitted on a successful call to subscribe
    event Subscription(uint256 indexed tokenId, address indexed subscriber);
    /// @notice Emitted on a successful call to unsubscribe
    event Unsubscription(uint256 indexed tokenId, address indexed subscriber);

    /// @notice Returns the subscriber for a respective position
    /// @param tokenId the ERC721 tokenId
    /// @return subscriber the subscriber contract
    function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber);

    /// @notice Enables the subscriber to receive notifications for a respective position
    /// @param tokenId the ERC721 tokenId
    /// @param newSubscriber the address of the subscriber contract
    /// @param data caller-provided data that's forwarded to the subscriber contract
    /// @dev Calling subscribe when a position is already subscribed will revert
    /// @dev payable so it can be multicalled with NATIVE related actions
    /// @dev will revert if pool manager is locked
    function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable;

    /// @notice Removes the subscriber from receiving notifications for a respective position
    /// @param tokenId the ERC721 tokenId
    /// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified
    /// @dev payable so it can be multicalled with NATIVE related actions
    /// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable.
    /// @dev will revert if pool manager is locked
    function unsubscribe(uint256 tokenId) external payable;

    /// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe
    /// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function
    function unsubscribeGasLimit() external view returns (uint256);
}

File 11 of 33 : IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}

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

/// @title IERC721Permit_v4
/// @notice Interface for the ERC721Permit_v4 contract
interface IERC721Permit_v4 {
    error SignatureDeadlineExpired();
    error NoSelfPermit();
    error Unauthorized();

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
    /// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
    /// @dev payable so it can be multicalled with NATIVE related actions
    function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature)
        external
        payable;

    /// @notice Set an operator with full permission to an owner's tokens via signature
    /// @param owner The address that is setting the operator
    /// @param operator The address that will be set as an operator for the owner
    /// @param approved The permission to set on the operator
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
    /// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
    /// @dev payable so it can be multicalled with NATIVE related actions
    function permitForAll(
        address owner,
        address operator,
        bool approved,
        uint256 deadline,
        uint256 nonce,
        bytes calldata signature
    ) external payable;
}

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

/// @title IEIP712_v4
/// @notice Interface for the EIP712 contract
interface IEIP712_v4 {
    /// @notice Returns the domain separator for the current chain.
    /// @return bytes32 The domain separator
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

/// @title IMulticall_v4
/// @notice Interface for the Multicall_v4 contract
interface IMulticall_v4 {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
    /// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

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

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

/// @title IPoolInitializer_v4
/// @notice Interface for the PoolInitializer_v4 contract
interface IPoolInitializer_v4 {
    /// @notice Initialize a Uniswap v4 Pool
    /// @dev If the pool is already initialized, this function will not revert and just return type(int24).max
    /// @param key The PoolKey of the pool to initialize
    /// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96
    /// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed
    function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24);
}

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

/// @title IUnorderedNonce
/// @notice Interface for the UnorderedNonce contract
interface IUnorderedNonce {
    error NonceAlreadyUsed();

    /// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap
    /// @dev word is at most type(uint248).max
    function nonces(address owner, uint256 word) external view returns (uint256);

    /// @notice Revoke a nonce by spending it, preventing it from being used again
    /// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce
    /// @dev payable so it can be multicalled with native-token related actions
    function revokeNonce(uint256 nonce) external payable;
}

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

import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";

/// @title IPermit2Forwarder
/// @notice Interface for the Permit2Forwarder contract
interface IPermit2Forwarder {
    /// @notice allows forwarding a single permit to permit2
    /// @dev this function is payable to allow multicall with NATIVE based actions
    /// @param owner the owner of the tokens
    /// @param permitSingle the permit data
    /// @param signature the signature of the permit; abi.encodePacked(r, s, v)
    /// @return err the error returned by a reverting permit call, empty if successful
    function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature)
        external
        payable
        returns (bytes memory err);

    /// @notice allows forwarding batch permits to permit2
    /// @dev this function is payable to allow multicall with NATIVE based actions
    /// @param owner the owner of the tokens
    /// @param _permitBatch a batch of approvals
    /// @param signature the signature of the permit; abi.encodePacked(r, s, v)
    /// @return err the error returned by a reverting permit call, empty if successful
    function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature)
        external
        payable
        returns (bytes memory err);
}

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

// 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)
        }
    }
}

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

// 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))
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";

/// @title ISubscriber
/// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager
interface ISubscriber {
    /// @notice Called when a position subscribes to this subscriber contract
    /// @param tokenId the token ID of the position
    /// @param data additional data passed in by the caller
    function notifySubscribe(uint256 tokenId, bytes memory data) external;

    /// @notice Called when a position unsubscribes from the subscriber
    /// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment)
    /// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft()
    /// @param tokenId the token ID of the position
    function notifyUnsubscribe(uint256 tokenId) external;

    /// @notice Called when a position is burned
    /// @param tokenId the token ID of the position
    /// @param owner the current owner of the tokenId
    /// @param info information about the position
    /// @param liquidity the amount of liquidity decreased in the position, may be 0
    /// @param feesAccrued the fees accrued by the position if liquidity was decreased
    function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued)
        external;

    /// @notice Called when a position modifies its liquidity or collects fees
    /// @param tokenId the token ID of the position
    /// @param liquidityChange the change in liquidity on the underlying position
    /// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call
    /// @dev Note that feesAccrued can be artificially inflated by a malicious user
    /// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves;
    /// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued
    function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external;
}

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

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

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

/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
    /// @notice Thrown when an allowance on a token has expired.
    /// @param deadline The timestamp at which the allowed amount is no longer valid
    error AllowanceExpired(uint256 deadline);

    /// @notice Thrown when an allowance on a token has been depleted.
    /// @param amount The maximum amount allowed
    error InsufficientAllowance(uint256 amount);

    /// @notice Thrown when too many nonces are invalidated.
    error ExcessiveInvalidation();

    /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
    event NonceInvalidation(
        address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
    );

    /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
    event Approval(
        address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
    );

    /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
    event Permit(
        address indexed owner,
        address indexed token,
        address indexed spender,
        uint160 amount,
        uint48 expiration,
        uint48 nonce
    );

    /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
    event Lockdown(address indexed owner, address token, address spender);

    /// @notice The permit data for a token
    struct PermitDetails {
        // ERC20 token address
        address token;
        // the maximum amount allowed to spend
        uint160 amount;
        // timestamp at which a spender's token allowances become invalid
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice The permit message signed for a single token allowance
    struct PermitSingle {
        // the permit data for a single token alownce
        PermitDetails details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The permit message signed for multiple token allowances
    struct PermitBatch {
        // the permit data for multiple token allowances
        PermitDetails[] details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The saved permissions
    /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    struct PackedAllowance {
        // amount allowed
        uint160 amount;
        // permission expiry
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice A token spender pair.
    struct TokenSpenderPair {
        // the token the spender is approved
        address token;
        // the spender address
        address spender;
    }

    /// @notice Details for a token transfer.
    struct AllowanceTransferDetails {
        // the owner of the token
        address from;
        // the recipient of the token
        address to;
        // the amount of the token
        uint160 amount;
        // the token to be transferred
        address token;
    }

    /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
    /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
    /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
    function allowance(address user, address token, address spender)
        external
        view
        returns (uint160 amount, uint48 expiration, uint48 nonce);

    /// @notice Approves the spender to use up to amount of the specified token up until the expiration
    /// @param token The token to approve
    /// @param spender The spender address to approve
    /// @param amount The approved amount of the token
    /// @param expiration The timestamp at which the approval is no longer valid
    /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;

    /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitSingle Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitBatch Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;

    /// @notice Transfer approved tokens from one address to another
    /// @param from The address to transfer from
    /// @param to The address of the recipient
    /// @param amount The amount of the token to transfer
    /// @param token The token address to transfer
    /// @dev Requires the from address to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(address from, address to, uint160 amount, address token) external;

    /// @notice Transfer approved tokens in a batch
    /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
    /// @dev Requires the from addresses to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;

    /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
    /// by batch revoking approvals
    /// @param approvals Array of approvals to revoke.
    function lockdown(TokenSpenderPair[] calldata approvals) external;

    /// @notice Invalidate nonces for a given (token, spender) pair
    /// @param token The token to invalidate nonces for
    /// @param spender The spender to invalidate nonces for
    /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
    /// @dev Can't invalidate more than 2**16 nonces per transaction.
    function invalidateNonces(address token, address spender, uint48 newNonce) external;
}

// 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)
        }
    }
}

// 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)
        }
    }
}

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

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

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

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

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

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

Settings
{
  "remappings": [
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-core/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@solmate/=lib/v4-core/lib/solmate/src/",
    "@solady/=lib/solady/src/",
    "src:@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "test:@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "@v4-periphery/=lib/v4-periphery/src/",
    "@v4-periphery-test/=lib/v4-periphery/test/",
    "@v4-core-test/=lib/v4-periphery/lib/v4-core/test/",
    "@v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "@v3-periphery/=lib/v3-periphery/contracts/",
    "@v3-core/=lib/v3-core/contracts/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@universal-router/=lib/universal-router/contracts/",
    "@uniswap/v2-core/contracts/interfaces/=src/interfaces/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "@uniswap/v3-periphery/=lib/universal-router/lib/v3-periphery/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/universal-router/lib/v4-periphery/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "solady/=lib/solady/src/",
    "solmate/=lib/universal-router/lib/solmate/",
    "universal-router/=lib/universal-router/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 0
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "libraries": {}
}

Contract ABI

API
[{"inputs":[{"internalType":"contract IPositionManager","name":"positionManager_","type":"address"},{"internalType":"address","name":"owner_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InvalidBeneficiary","type":"error"},{"inputs":[],"name":"NonPositionManager","type":"error"},{"inputs":[],"name":"NotApprovedMigrator","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PositionAlreadyUnlocked","type":"error"},{"inputs":[],"name":"PositionNotFound","type":"error"},{"inputs":[],"name":"Reentrancy","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"DistributeFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"components":[{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint96","name":"shares","type":"uint96"}],"indexed":false,"internalType":"struct BeneficiaryData[]","name":"beneficiaries","type":"tuple[]"},{"indexed":false,"internalType":"uint256","name":"unlockDate","type":"uint256"}],"name":"Lock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"migrator","type":"address"},{"indexed":false,"internalType":"bool","name":"approval","type":"bool"}],"name":"MigratorApproval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"beneficiary","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Release","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"}],"name":"Unlock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"oldBeneficiary","type":"address"},{"indexed":false,"internalType":"address","name":"newBeneficiary","type":"address"}],"name":"UpdateBeneficiary","type":"event"},{"inputs":[{"internalType":"address","name":"migrator","type":"address"}],"name":"approveMigrator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"migrator","type":"address"}],"name":"approvedMigrators","outputs":[{"internalType":"bool","name":"approved","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"Currency","name":"currency","type":"address"}],"name":"beneficiariesClaims","outputs":[{"internalType":"uint256","name":"releasableBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"currencyBalances","outputs":[{"internalType":"uint256","name":"balanceOfSelf","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"distributeFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"positionData","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"positionManager","outputs":[{"internalType":"contract IPositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"positions","outputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint32","name":"startDate","type":"uint32"},{"internalType":"uint32","name":"lockDuration","type":"uint32"},{"internalType":"bool","name":"isUnlocked","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"releaseFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"migrator","type":"address"}],"name":"revokeMigrator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"newBeneficiary","type":"address"}],"name":"updateBeneficiary","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60a03461011057601f611d4738819003918201601f19168301916001600160401b03831184841017610114578084926040948552833981010312610110578051906001600160a01b038216820361011057602001516001600160a01b03811691908290036101105781156100fd575f80546001600160a01b031981168417825560405193916001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09080a3608052611c1e90816101298239608051818181610349015281816104b901528181610656015281816106b601528181610a3501528181610aa40152818161133301526118640152f35b631e4fbdf760e01b5f525f60045260245ffd5b5f80fd5b634e487b7160e01b5f52604160045260245ffdfe6080604052600436101561001a575b3615610018575f80fd5b005b5f803560e01c8063150b7a02146112cc5780632f83ad6c146112945780633e8eb5a414610faa5780634a719bd414610e385780636029bf9f146103bf578063715018a614610378578063791b98bc14610333578063880d6c75146102f45780638da5cb5b146102cd57806393f213931461027a57806399fbab881461021b578063df81c4e3146101aa578063e5145d4a146101345763f2fde38b146100bf575061000e565b34610131576020366003190112610131576100d8611676565b6100e06119f7565b6001600160a01b0316801561011d5781546001600160a01b03198116821783556001600160a01b03165f80516020611bd28339815191528380a380f35b631e4fbdf760e01b82526004829052602482fd5b80fd5b50346101315760203660031901126101315761014e611676565b6101566119f7565b6001600160a01b03168082526004602052604082205460ff1615610178575080f35b808252600460205260408220600160ff198254161790555f80516020611bf2833981519152602060405160018152a280f35b5034610131576020366003190112610131576101c4611676565b6101cc6119f7565b6001600160a01b03168082526004602052604082205460ff166101ed575080f35b80825260046020526040822060ff1981541690555f80516020611bf28339815191526020604051848152a280f35b503461013157602036600319011261013157604060809160043581526001602052205460ff6040519160018060a01b038116835263ffffffff8160a01c16602084015263ffffffff8160c01c16604084015260e01c1615156060820152f35b5034610131576040366003190112610131576040610296611676565b9161029f61168c565b9260018060a01b031681526002602052209060018060a01b03165f52602052602060405f2054604051908152f35b5034610131578060031936011261013157546040516001600160a01b039091168152602090f35b50346101315760203660031901126101315760209060ff906040906001600160a01b0361031f611676565b168152600484522054166040519015158152f35b50346101315780600319360112610131576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346101315780600319360112610131576103916119f7565b80546001600160a01b03198116825581906001600160a01b03165f80516020611bd28339815191528280a380f35b5034610d65576020366003190112610d65573068929eee149b4bd212685414610e2b573068929eee149b4bd21268556004355f52600160205260405f2060016040519161040b836116bd565b60ff8154838060a01b038116855263ffffffff8160a01c16602086015263ffffffff8160c01c16604086015260e01c161515606084015201805461044e816116fb565b9161045c60405193846116d8565b81835260208301905f5260205f205f915b838310610df85750505050608082015263ffffffff60208201511615610de95760016060820151151514610dda57604051637ba03aad60e01b815260048035908201529060c0826024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa918215610d5a575f92610da8575b50604051600160f81b6020820152601160f81b602182015260028152916105196022846116d8565b60609260405161052985826116d8565b60028152601f1985015f5b818110610d9857505060209461058e61059c60405161055389826116d8565b5f8152601f198901368a8301376040519283916004358b8401525f60408401525f868401525f608084015260a08084015260c0830190611814565b03601f1981018352826116d8565b6105a583611732565b526105af82611732565b50835186850151604080516001600160a01b03938416818b0152929091169082015230828201528181526105e46080826116d8565b6105ed83611753565b526105f782611753565b5061060f604051938492604089850152830190611814565b91601f1982840301604083015280518084528784019388808360051b8301019301945f915b8a848410610d69575050505050610654925003601f1981018352826116d8565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163b15610d65575f6106ab916040518093819263dd46508f60e01b8352604060048401526044830190611814565b4260248301520381837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af18015610d5a57610d45575b506080820151815190949390610709906001600160a01b0316611b60565b9361076061074161072460018060a01b038587015116611b60565b85516001600160a01b031684526003855260408420549097611838565b848401516001600160a01b031683526003845260408320549096611838565b9460018060a01b0384511682526003835260408220610780828254611725565b9055838301516001600160a01b03168252600383526040822080546107a6908890611725565b9055818297835b81518110156109195797988998906001600160a01b036107cd8385611763565b5151166001600160601b03886107e38587611763565b51015116916107f28388611712565b670de0b6b3a764000090049b8c9361080991611712565b670de0b6b3a7640000900495869361082091611725565b9561082a91611725565b9a8451805f1981011161090557908c8e6001969594935f190186146108b6575b505081895260028a5260408920858060a01b038c5116868060a01b03165f528a5261087a60405f20918254611725565b905587526002885260408720838060a01b03898b015116848060a01b03165f5288526108ab60405f20918254611725565b9055019897986107ad565b6108db6108ed938c969396508a8c115f146108fe576108d58b8d611838565b90611725565b94808211156108f5576108d591611838565b918c8e61084a565b50508990611725565b8c90611725565b634e487b7160e01b89526011600452602489fd5b50505085838663ffffffff60208201511663ffffffff6040830151160163ffffffff8111610d315763ffffffff1642101580610d1b575b15610bf157600160608201818152600435875281845260408088208451815460208701519387015194516001600160e81b03199091166001600160a01b03929092169190911760a09390931b63ffffffff60a01b169290921760c09390931b63ffffffff60c01b169290921790151560e01b60ff60e01b1617815560808301518051929190910190600160401b8311610bdd5784908254848455808510610bb5575b50019087528387208488925b848410610b7e575050835160405189945092506001600160a01b03169050610a2685836116d8565b828252601f19850136868401377f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163b15610b7a57610a9f9183916040519384928392635c46a7ef60e11b845230600485015260248401526004356044840152608060648401526084830190611814565b0381837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af18015610b6f57610b56575b5050516040516001600160a01b039091168152600435907f027d6c6704a7913d85498305191e7bb755d64034c42fb5169c726408f65b3ce2908390a25b6040519283528201527f125472b1b527506b5b8381590760f796fd9c88ba5886399d71abc083c6dafa20604060043592a23868929eee149b4bd212685580f35b81610b60916116d8565b610b6b578486610ad9565b8480fd5b6040513d84823e3d90fd5b8280fd5b805180519083015160a01b6001600160a01b0319166001600160a01b039190911617835560019384019392909201918691016109fe565b838a5284838b2091820191015b818110610bcf57506109f2565b8a8155879350600101610bc2565b634e487b7160e01b88526041600452602488fd5b6004358552600180835260408087208351815460208601519386015160608701516001600160e81b03199092166001600160a01b03939093169290921760a09490941b63ffffffff60a01b169390931760c09190911b63ffffffff60c01b161791151560e01b60ff60e01b169190911781556080929092015180519290910190600160401b8311610d075783908254848455808510610cdf575b50019086528286208387925b848410610ca8575050505050610b16565b805180519083015160a01b6001600160a01b0319166001600160a01b03919091161783556001938401939290920191859101610c97565b83895284838a2091820191015b818110610cf95750610c8b565b898155869350600101610cec565b634e487b7160e01b87526041600452602487fd5b5080516001600160a01b031661dead1415610950565b634e487b7160e01b86526011600452602486fd5b610d529194505f906116d8565b5f925f6106eb565b6040513d5f823e3d90fd5b5f80fd5b600192949650610d8681929496601f198682030187528951611814565b97019301930190928694929593610634565b6020818401810188905201610534565b610dcb91925060c03d60c011610dd3575b610dc381836116d8565b81019061178b565b50905f6104f1565b503d610db9565b631916c98f60e31b5f5260045ffd5b636ec9be1160e01b5f5260045ffd5b600160208192604051610e0a816116a2565b8554848060a01b038116825260a01c8382015281520192019201919061046d565b63ab143c065f526004601cfd5b34610d65576020366003190112610d65576004353068929eee149b4bd212685414610e2b573068929eee149b4bd2126855805f52600160205260405f2060405190610e82826116bd565b6001815491818060a01b038316845260ff602085019363ffffffff8160a01c16855263ffffffff8160c01c16604087015260e01c161515606085015201918254610ecb816116fb565b93610ed960405195866116d8565b81855260208501905f5260205f205f915b838310610f7757878763ffffffff8860808901928352511615610de9575f805b82518051821015610f6e5733906001600160a01b0390610f2b908490611763565b51511614610f3b57600101610f0a565b50505060015b15610f5f57610f51903390611845565b3868929eee149b4bd2126855005b631559b7d760e21b5f5260045ffd5b50509050610f41565b600160208192604051610f89816116a2565b8554848060a01b038116825260a01c83820152815201920192019190610eea565b34610d65576040366003190112610d6557600435610fc661168c565b3068929eee149b4bd212685414610e2b573068929eee149b4bd2126855815f52600160205260405f209060405191610ffd836116bd565b80549260018060a01b0384168152602081019163ffffffff8560a01c1683526001604083019163ffffffff8760c01c16835260ff606085019760e01c16151587520193845461104b816116fb565b9561105960405197886116d8565b81875260208701905f5260205f205f915b83831061126157505050506080830194855263ffffffff84511615610de9576001600160a01b0316948515610f5f578451515f905f5b8181036111fd575b505015610f5f575f878152600160208190526040909120935184549551935192516001600160e81b03199096166001600160a01b03919091161760a09390931b63ffffffff60a01b169290921760c09190911b63ffffffff60c01b161792151560e01b60ff60e01b16929092178155915180519290910190600160401b83116111e95781548383558084106111c3575b50602001905f5260205f205f915b83831061118c57857fdc49102363197c97922de06511d138180fe1ad161b9d7feb4ee31da1cbef144a6040878151903382526020820152a23868929eee149b4bd2126855005b8051805160209182015160a01b6001600160a01b0319166001600160a01b0391909116178355600193840193929092019101611146565b825f528360205f2091820191015b8181106111de5750611138565b5f81556001016111d1565b634e487b7160e01b5f52604160045260245ffd5b883360018060a01b03611211848c51611763565b5151161461123e57505f19811461122a576001016110a0565b634e487b7160e01b5f52601160045260245ffd5b9250611256915061124f338b611845565b8751611763565b5152600188806110a8565b600160208192604051611273816116a2565b8554848060a01b038116825260a01c8382015281520192019201919061106a565b34610d65576020366003190112610d65576001600160a01b036112b5611676565b165f526003602052602060405f2054604051908152f35b34610d65576080366003190112610d65576112e5611676565b506112ee61168c565b60443590606435906001600160401b038211610d655736602383011215610d655760048201356001600160401b038111610d65578201916024830191368311610d65577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163303611667576001600160a01b03165f9081526004602052604090205460ff161561165857606081840312610d655760248101356001600160a01b03811690819003610d655760448201359163ffffffff8316809303610d65576064810135906001600160401b038211610d65570183604382011215610d65576024810135936113e4856116fb565b956113f260405197886116d8565b858752602087019260206024859860061b83010101928311610d6557604401925b8284106115ff575050505060405161142a816116bd565b8181524263ffffffff16602080830191825260408084018681525f60608601818152608087018b81528c835260019586905293909120955186549551925191516001600160e81b03199096166001600160a01b03919091161760a09290921b63ffffffff60a01b169190911760c09190911b63ffffffff60c01b161792151560e01b60ff60e01b16929092178355905180519290910190600160401b83116111e95781548383558084106115d9575b50602001905f5260205f205f915b8383106115a2575050505061dead14155f1461159b576115079042611725565b60405192604084019060408552518091526060840192905f5b81811061156757867f0c530beb7de1116cce0f7395bab1438fd963a0673077f6c37c39ca6ece8449c08780888860208301520390a2604051630a85bd0160e11b8152602090f35b825180516001600160a01b031686526020908101516001600160601b03168187015260409095019490920191600101611520565b505f611507565b8051805160209182015160a01b6001600160a01b0319166001600160a01b03919091161783556001938401939290920191016114e7565b825f528360205f2091820191015b8181106115f457506114d9565b5f81556001016115e7565b604060248584030112610d655760405190611619826116a2565b84356001600160a01b0381168103610d655782526020850135906001600160601b0382168203610d655782602092836040950152815201930192611413565b637deeb52360e01b5f5260045ffd5b632063bbc160e21b5f5260045ffd5b600435906001600160a01b0382168203610d6557565b602435906001600160a01b0382168203610d6557565b604081019081106001600160401b038211176111e957604052565b60a081019081106001600160401b038211176111e957604052565b601f909101601f19168101906001600160401b038211908210176111e957604052565b6001600160401b0381116111e95760051b60200190565b8181029291811591840414171561122a57565b9190820180921161122a57565b80511561173f5760200190565b634e487b7160e01b5f52603260045260245ffd5b80516001101561173f5760400190565b805182101561173f5760209160051b010190565b51906001600160a01b0382168203610d6557565b8092910360c08112610d655760a013610d65576040516117aa816116bd565b6117b383611777565b81526117c160208401611777565b6020820152604083015162ffffff81168103610d6557604082015260608301518060020b8103610d655760608201526080830151906001600160a01b0382168203610d655760a091608082015292015190565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9190820391821161122a57565b604051637ba03aad60e01b81526004810182905290919060c0816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa8015610d5a577fab8de90aa60ba5a166ba832ebb0ff724e0fb4440a64c2b043bd78000651c0665926060925f926119d5575b506001600160a01b038181165f81815260026020818152604080842088518716855280835281852054868652848452838a01805189168752828552838720548888528686528b518a16885283865284882088905588885295855280518916875291845282862086905589519097168552600390925290922080549396919592938693929190611950908790611838565b905560018060a01b038451165f52600360205260405f20611972848254611838565b90558482816119b8575b5050508161199b575b50505060405192835260208301526040820152a2565b91516119b092906001600160a01b0316611a1d565b5f8281611985565b91516119cd92906001600160a01b0316611a1d565b5f848261197c565b6119ef91925060c03d60c011610dd357610dc381836116d8565b50905f6118c0565b5f546001600160a01b03163303611a0a57565b63118cdaa760e01b5f523360045260245ffd5b9091906001600160a01b0381169081611aab5750505f80808093855af115611a425750565b6040516390bfb86560e01b81526001600160a01b0390911660048201525f602482018190526080604483015260a03d601f01601f191690810160648401523d6084840152903d9060a484013e808201600460a482015260c4633d2cec6f60e21b91015260e40190fd5b60205f604481949682604095865198899363a9059cbb60e01b855260018060a01b0316600485015260248401525af13d15601f3d11600185511416171692828152826020820152015215611afc5750565b6040516390bfb86560e01b8152600481019190915263a9059cbb60e01b602482015260806044820152601f3d01601f191660a0810160648301523d60848301523d5f60a484013e808201600460a482015260c4633c9fd93960e21b91015260e40190fd5b6001600160a01b031680611b7357504790565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610d5a575f91611ba2575090565b90506020813d602011611bc9575b81611bbd602093836116d8565b81010312610d65575190565b3d9150611bb056fe8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0372d23d18ee5ba59c4547d05c7a473aeb8e3bf0c4eeb61bff18f3aa46008cdc5a164736f6c634300081a000a0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca80000000000000000000000000ace07c3c1d3b556d42633211f0da71dc6f6d1c42

Deployed Bytecode

0x6080604052600436101561001a575b3615610018575f80fd5b005b5f803560e01c8063150b7a02146112cc5780632f83ad6c146112945780633e8eb5a414610faa5780634a719bd414610e385780636029bf9f146103bf578063715018a614610378578063791b98bc14610333578063880d6c75146102f45780638da5cb5b146102cd57806393f213931461027a57806399fbab881461021b578063df81c4e3146101aa578063e5145d4a146101345763f2fde38b146100bf575061000e565b34610131576020366003190112610131576100d8611676565b6100e06119f7565b6001600160a01b0316801561011d5781546001600160a01b03198116821783556001600160a01b03165f80516020611bd28339815191528380a380f35b631e4fbdf760e01b82526004829052602482fd5b80fd5b50346101315760203660031901126101315761014e611676565b6101566119f7565b6001600160a01b03168082526004602052604082205460ff1615610178575080f35b808252600460205260408220600160ff198254161790555f80516020611bf2833981519152602060405160018152a280f35b5034610131576020366003190112610131576101c4611676565b6101cc6119f7565b6001600160a01b03168082526004602052604082205460ff166101ed575080f35b80825260046020526040822060ff1981541690555f80516020611bf28339815191526020604051848152a280f35b503461013157602036600319011261013157604060809160043581526001602052205460ff6040519160018060a01b038116835263ffffffff8160a01c16602084015263ffffffff8160c01c16604084015260e01c1615156060820152f35b5034610131576040366003190112610131576040610296611676565b9161029f61168c565b9260018060a01b031681526002602052209060018060a01b03165f52602052602060405f2054604051908152f35b5034610131578060031936011261013157546040516001600160a01b039091168152602090f35b50346101315760203660031901126101315760209060ff906040906001600160a01b0361031f611676565b168152600484522054166040519015158152f35b50346101315780600319360112610131576040517f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03168152602090f35b50346101315780600319360112610131576103916119f7565b80546001600160a01b03198116825581906001600160a01b03165f80516020611bd28339815191528280a380f35b5034610d65576020366003190112610d65573068929eee149b4bd212685414610e2b573068929eee149b4bd21268556004355f52600160205260405f2060016040519161040b836116bd565b60ff8154838060a01b038116855263ffffffff8160a01c16602086015263ffffffff8160c01c16604086015260e01c161515606084015201805461044e816116fb565b9161045c60405193846116d8565b81835260208301905f5260205f205f915b838310610df85750505050608082015263ffffffff60208201511615610de95760016060820151151514610dda57604051637ba03aad60e01b815260048035908201529060c0826024817f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03165afa918215610d5a575f92610da8575b50604051600160f81b6020820152601160f81b602182015260028152916105196022846116d8565b60609260405161052985826116d8565b60028152601f1985015f5b818110610d9857505060209461058e61059c60405161055389826116d8565b5f8152601f198901368a8301376040519283916004358b8401525f60408401525f868401525f608084015260a08084015260c0830190611814565b03601f1981018352826116d8565b6105a583611732565b526105af82611732565b50835186850151604080516001600160a01b03938416818b0152929091169082015230828201528181526105e46080826116d8565b6105ed83611753565b526105f782611753565b5061060f604051938492604089850152830190611814565b91601f1982840301604083015280518084528784019388808360051b8301019301945f915b8a848410610d69575050505050610654925003601f1981018352826116d8565b7f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03163b15610d65575f6106ab916040518093819263dd46508f60e01b8352604060048401526044830190611814565b4260248301520381837f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03165af18015610d5a57610d45575b506080820151815190949390610709906001600160a01b0316611b60565b9361076061074161072460018060a01b038587015116611b60565b85516001600160a01b031684526003855260408420549097611838565b848401516001600160a01b031683526003845260408320549096611838565b9460018060a01b0384511682526003835260408220610780828254611725565b9055838301516001600160a01b03168252600383526040822080546107a6908890611725565b9055818297835b81518110156109195797988998906001600160a01b036107cd8385611763565b5151166001600160601b03886107e38587611763565b51015116916107f28388611712565b670de0b6b3a764000090049b8c9361080991611712565b670de0b6b3a7640000900495869361082091611725565b9561082a91611725565b9a8451805f1981011161090557908c8e6001969594935f190186146108b6575b505081895260028a5260408920858060a01b038c5116868060a01b03165f528a5261087a60405f20918254611725565b905587526002885260408720838060a01b03898b015116848060a01b03165f5288526108ab60405f20918254611725565b9055019897986107ad565b6108db6108ed938c969396508a8c115f146108fe576108d58b8d611838565b90611725565b94808211156108f5576108d591611838565b918c8e61084a565b50508990611725565b8c90611725565b634e487b7160e01b89526011600452602489fd5b50505085838663ffffffff60208201511663ffffffff6040830151160163ffffffff8111610d315763ffffffff1642101580610d1b575b15610bf157600160608201818152600435875281845260408088208451815460208701519387015194516001600160e81b03199091166001600160a01b03929092169190911760a09390931b63ffffffff60a01b169290921760c09390931b63ffffffff60c01b169290921790151560e01b60ff60e01b1617815560808301518051929190910190600160401b8311610bdd5784908254848455808510610bb5575b50019087528387208488925b848410610b7e575050835160405189945092506001600160a01b03169050610a2685836116d8565b828252601f19850136868401377f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03163b15610b7a57610a9f9183916040519384928392635c46a7ef60e11b845230600485015260248401526004356044840152608060648401526084830190611814565b0381837f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03165af18015610b6f57610b56575b5050516040516001600160a01b039091168152600435907f027d6c6704a7913d85498305191e7bb755d64034c42fb5169c726408f65b3ce2908390a25b6040519283528201527f125472b1b527506b5b8381590760f796fd9c88ba5886399d71abc083c6dafa20604060043592a23868929eee149b4bd212685580f35b81610b60916116d8565b610b6b578486610ad9565b8480fd5b6040513d84823e3d90fd5b8280fd5b805180519083015160a01b6001600160a01b0319166001600160a01b039190911617835560019384019392909201918691016109fe565b838a5284838b2091820191015b818110610bcf57506109f2565b8a8155879350600101610bc2565b634e487b7160e01b88526041600452602488fd5b6004358552600180835260408087208351815460208601519386015160608701516001600160e81b03199092166001600160a01b03939093169290921760a09490941b63ffffffff60a01b169390931760c09190911b63ffffffff60c01b161791151560e01b60ff60e01b169190911781556080929092015180519290910190600160401b8311610d075783908254848455808510610cdf575b50019086528286208387925b848410610ca8575050505050610b16565b805180519083015160a01b6001600160a01b0319166001600160a01b03919091161783556001938401939290920191859101610c97565b83895284838a2091820191015b818110610cf95750610c8b565b898155869350600101610cec565b634e487b7160e01b87526041600452602487fd5b5080516001600160a01b031661dead1415610950565b634e487b7160e01b86526011600452602486fd5b610d529194505f906116d8565b5f925f6106eb565b6040513d5f823e3d90fd5b5f80fd5b600192949650610d8681929496601f198682030187528951611814565b97019301930190928694929593610634565b6020818401810188905201610534565b610dcb91925060c03d60c011610dd3575b610dc381836116d8565b81019061178b565b50905f6104f1565b503d610db9565b631916c98f60e31b5f5260045ffd5b636ec9be1160e01b5f5260045ffd5b600160208192604051610e0a816116a2565b8554848060a01b038116825260a01c8382015281520192019201919061046d565b63ab143c065f526004601cfd5b34610d65576020366003190112610d65576004353068929eee149b4bd212685414610e2b573068929eee149b4bd2126855805f52600160205260405f2060405190610e82826116bd565b6001815491818060a01b038316845260ff602085019363ffffffff8160a01c16855263ffffffff8160c01c16604087015260e01c161515606085015201918254610ecb816116fb565b93610ed960405195866116d8565b81855260208501905f5260205f205f915b838310610f7757878763ffffffff8860808901928352511615610de9575f805b82518051821015610f6e5733906001600160a01b0390610f2b908490611763565b51511614610f3b57600101610f0a565b50505060015b15610f5f57610f51903390611845565b3868929eee149b4bd2126855005b631559b7d760e21b5f5260045ffd5b50509050610f41565b600160208192604051610f89816116a2565b8554848060a01b038116825260a01c83820152815201920192019190610eea565b34610d65576040366003190112610d6557600435610fc661168c565b3068929eee149b4bd212685414610e2b573068929eee149b4bd2126855815f52600160205260405f209060405191610ffd836116bd565b80549260018060a01b0384168152602081019163ffffffff8560a01c1683526001604083019163ffffffff8760c01c16835260ff606085019760e01c16151587520193845461104b816116fb565b9561105960405197886116d8565b81875260208701905f5260205f205f915b83831061126157505050506080830194855263ffffffff84511615610de9576001600160a01b0316948515610f5f578451515f905f5b8181036111fd575b505015610f5f575f878152600160208190526040909120935184549551935192516001600160e81b03199096166001600160a01b03919091161760a09390931b63ffffffff60a01b169290921760c09190911b63ffffffff60c01b161792151560e01b60ff60e01b16929092178155915180519290910190600160401b83116111e95781548383558084106111c3575b50602001905f5260205f205f915b83831061118c57857fdc49102363197c97922de06511d138180fe1ad161b9d7feb4ee31da1cbef144a6040878151903382526020820152a23868929eee149b4bd2126855005b8051805160209182015160a01b6001600160a01b0319166001600160a01b0391909116178355600193840193929092019101611146565b825f528360205f2091820191015b8181106111de5750611138565b5f81556001016111d1565b634e487b7160e01b5f52604160045260245ffd5b883360018060a01b03611211848c51611763565b5151161461123e57505f19811461122a576001016110a0565b634e487b7160e01b5f52601160045260245ffd5b9250611256915061124f338b611845565b8751611763565b5152600188806110a8565b600160208192604051611273816116a2565b8554848060a01b038116825260a01c8382015281520192019201919061106a565b34610d65576020366003190112610d65576001600160a01b036112b5611676565b165f526003602052602060405f2054604051908152f35b34610d65576080366003190112610d65576112e5611676565b506112ee61168c565b60443590606435906001600160401b038211610d655736602383011215610d655760048201356001600160401b038111610d65578201916024830191368311610d65577f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03163303611667576001600160a01b03165f9081526004602052604090205460ff161561165857606081840312610d655760248101356001600160a01b03811690819003610d655760448201359163ffffffff8316809303610d65576064810135906001600160401b038211610d65570183604382011215610d65576024810135936113e4856116fb565b956113f260405197886116d8565b858752602087019260206024859860061b83010101928311610d6557604401925b8284106115ff575050505060405161142a816116bd565b8181524263ffffffff16602080830191825260408084018681525f60608601818152608087018b81528c835260019586905293909120955186549551925191516001600160e81b03199096166001600160a01b03919091161760a09290921b63ffffffff60a01b169190911760c09190911b63ffffffff60c01b161792151560e01b60ff60e01b16929092178355905180519290910190600160401b83116111e95781548383558084106115d9575b50602001905f5260205f205f915b8383106115a2575050505061dead14155f1461159b576115079042611725565b60405192604084019060408552518091526060840192905f5b81811061156757867f0c530beb7de1116cce0f7395bab1438fd963a0673077f6c37c39ca6ece8449c08780888860208301520390a2604051630a85bd0160e11b8152602090f35b825180516001600160a01b031686526020908101516001600160601b03168187015260409095019490920191600101611520565b505f611507565b8051805160209182015160a01b6001600160a01b0319166001600160a01b03919091161783556001938401939290920191016114e7565b825f528360205f2091820191015b8181106115f457506114d9565b5f81556001016115e7565b604060248584030112610d655760405190611619826116a2565b84356001600160a01b0381168103610d655782526020850135906001600160601b0382168203610d655782602092836040950152815201930192611413565b637deeb52360e01b5f5260045ffd5b632063bbc160e21b5f5260045ffd5b600435906001600160a01b0382168203610d6557565b602435906001600160a01b0382168203610d6557565b604081019081106001600160401b038211176111e957604052565b60a081019081106001600160401b038211176111e957604052565b601f909101601f19168101906001600160401b038211908210176111e957604052565b6001600160401b0381116111e95760051b60200190565b8181029291811591840414171561122a57565b9190820180921161122a57565b80511561173f5760200190565b634e487b7160e01b5f52603260045260245ffd5b80516001101561173f5760400190565b805182101561173f5760209160051b010190565b51906001600160a01b0382168203610d6557565b8092910360c08112610d655760a013610d65576040516117aa816116bd565b6117b383611777565b81526117c160208401611777565b6020820152604083015162ffffff81168103610d6557604082015260608301518060020b8103610d655760608201526080830151906001600160a01b0382168203610d655760a091608082015292015190565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9190820391821161122a57565b604051637ba03aad60e01b81526004810182905290919060c0816024817f0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca806001600160a01b03165afa8015610d5a577fab8de90aa60ba5a166ba832ebb0ff724e0fb4440a64c2b043bd78000651c0665926060925f926119d5575b506001600160a01b038181165f81815260026020818152604080842088518716855280835281852054868652848452838a01805189168752828552838720548888528686528b518a16885283865284882088905588885295855280518916875291845282862086905589519097168552600390925290922080549396919592938693929190611950908790611838565b905560018060a01b038451165f52600360205260405f20611972848254611838565b90558482816119b8575b5050508161199b575b50505060405192835260208301526040820152a2565b91516119b092906001600160a01b0316611a1d565b5f8281611985565b91516119cd92906001600160a01b0316611a1d565b5f848261197c565b6119ef91925060c03d60c011610dd357610dc381836116d8565b50905f6118c0565b5f546001600160a01b03163303611a0a57565b63118cdaa760e01b5f523360045260245ffd5b9091906001600160a01b0381169081611aab5750505f80808093855af115611a425750565b6040516390bfb86560e01b81526001600160a01b0390911660048201525f602482018190526080604483015260a03d601f01601f191690810160648401523d6084840152903d9060a484013e808201600460a482015260c4633d2cec6f60e21b91015260e40190fd5b60205f604481949682604095865198899363a9059cbb60e01b855260018060a01b0316600485015260248401525af13d15601f3d11600185511416171692828152826020820152015215611afc5750565b6040516390bfb86560e01b8152600481019190915263a9059cbb60e01b602482015260806044820152601f3d01601f191660a0810160648301523d60848301523d5f60a484013e808201600460a482015260c4633c9fd93960e21b91015260e40190fd5b6001600160a01b031680611b7357504790565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610d5a575f91611ba2575090565b90506020813d602011611bc9575b81611bbd602093836116d8565b81010312610d65575190565b3d9150611bb056fe8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0372d23d18ee5ba59c4547d05c7a473aeb8e3bf0c4eeb61bff18f3aa46008cdc5a164736f6c634300081a000a

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca80000000000000000000000000ace07c3c1d3b556d42633211f0da71dc6f6d1c42

-----Decoded View---------------
Arg [0] : positionManager_ (address): 0x4B2C77d209D3405F41a037Ec6c77F7F5b8e2ca80
Arg [1] : owner_ (address): 0xaCE07c3c1D3b556D42633211f0Da71dc6F6d1c42

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 0000000000000000000000004b2c77d209d3405f41a037ec6c77f7f5b8e2ca80
Arg [1] : 000000000000000000000000ace07c3c1d3b556d42633211f0da71dc6f6d1c42


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
0x3345E557c5C0b474bE1eb4693264008B8562Aa9c
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.