ETH Price: $2,346.42 (+1.25%)

Contract

0x0f0Bf801b11a97dFa163e0e7439624e8C2a9224D

Overview

ETH Balance

Linea Mainnet LogoLinea Mainnet LogoLinea Mainnet Logo0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

6 Internal Transactions found.

Latest 6 internal transactions

Advanced mode:
Parent Transaction Hash Block From To
252324082025-11-03 14:09:1491 days ago1762178954
0x0f0Bf801...8C2a9224D
0 ETH
252324082025-11-03 14:09:1491 days ago1762178954
0x0f0Bf801...8C2a9224D
0 ETH
252324082025-11-03 14:09:1491 days ago1762178954
0x0f0Bf801...8C2a9224D
0 ETH
252324082025-11-03 14:09:1491 days ago1762178954
0x0f0Bf801...8C2a9224D
0 ETH
252324082025-11-03 14:09:1491 days ago1762178954
0x0f0Bf801...8C2a9224D
0 ETH
252324082025-11-03 14:09:1491 days ago1762178954
0x0f0Bf801...8C2a9224D
0 ETH
Cross-Chain Transactions
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x944283fD...6DeF7dD02
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
UIHelper

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 2000 runs

Other Settings:
paris EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun
pragma solidity ^0.8.0;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";

import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IWETH9} from "@uniswap/v4-periphery/src/interfaces/external/IWETH9.sol";
import {ICLMMAdapter} from "contracts/interfaces/ICLMMAdapter.sol";
import {ITokenLaunchpad} from "contracts/interfaces/ITokenLaunchpad.sol";
import {IUIHelper} from "contracts/interfaces/IUIHelper.sol";
import {IOpenOceanCaller, IOpenOceanExchange} from "contracts/interfaces/thirdparty/IOpenOcean.sol";
import {ReferralRewards} from "contracts/ReferralRewards.sol";
import {IReferralSystem} from "contracts/interfaces/IReferralSystem.sol";

contract UIHelper is
    IUIHelper,
    ReentrancyGuard,
    IOpenOceanCaller,
    IERC721Receiver
{
    using SafeERC20 for IERC20;

    IWETH9 public immutable weth;
    IOpenOceanExchange public immutable openOcean;
    ITokenLaunchpad public immutable launchpad;
    ICLMMAdapter public immutable adapter;
    IERC20 public immutable fundingToken;
    ReferralRewards public immutable referralRewards;
    IReferralSystem public referralSystem;
    receive() external payable {}

    constructor(address _weth, address _openocean, address _launchpad) {
        weth = IWETH9(_weth);
        openOcean = IOpenOceanExchange(_openocean);
        launchpad = ITokenLaunchpad(_launchpad);
        adapter = ICLMMAdapter(launchpad.adapter());
        fundingToken = IERC20(launchpad.fundingToken());
        referralRewards = ReferralRewards(launchpad.referralRewarder());
        fundingToken.forceApprove(address(adapter), type(uint256).max);
        fundingToken.forceApprove(address(launchpad), type(uint256).max);
        referralSystem = IReferralSystem(launchpad.referralSystem());
    }

    function makeCalls(
        CallDescription[] memory desc
    ) external payable override {
        require(msg.sender == address(openOcean), "Only router can call");
        for (uint256 i = 0; i < desc.length; i++) {
            (bool success, ) = address(uint160(desc[i].target)).call{
                gas: desc[i].gasLimit,
                value: desc[i].value
            }(desc[i].data);
            require(success, "subcall failed");
        }
    }

    /// @inheritdoc IUIHelper
    function createAndBuy(
        OpenOceanParams memory _openOceanParams,
        ITokenLaunchpad.CreateParams memory _params,
        address _expected,
        uint256 _amount,
        bytes8 _creatorReferralCode
    )
        external
        payable
        override
        nonReentrant
        returns (
            address token,
            uint256 received,
            uint256 swapped,
            uint256 tokenId
        )
    {
        // Track initial balances to prevent draining pre-existing tokens
        InitialBalances memory initialBalances = InitialBalances({
            tokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenOut: address(_openOceanParams.tokenOut) == address(0)
                ? 0
                : _openOceanParams.tokenOut.balanceOf(address(this)),
            fundingToken: fundingToken.balanceOf(address(this)),
            tokenOut: 0
        });

        _performOpenOceanSwap(_openOceanParams);

        (token, received, tokenId) = launchpad.createAndBuy(
            _params,
            _expected,
            _amount,
            _creatorReferralCode
        );

        // send the nft to the user
        launchpad.safeTransferFrom(address(this), msg.sender, tokenId);

        _purgeAll(_openOceanParams, IERC20(token), initialBalances);
    }

    /// @inheritdoc IUIHelper
    function buyWithExactInputWithOpenOcean(
        OpenOceanParams memory _openOceanParams,
        IERC20 _tokenOut,
        uint256 _minAmountOut,
        uint160 _sqrtPriceLimitX96,
        bytes8 _referralCode
    ) external payable override nonReentrant returns (uint256 amountOut) {
        // Track initial balances to prevent draining pre-existing tokens
        InitialBalances memory initialBalances = InitialBalances({
            tokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenOut: address(_openOceanParams.tokenOut) == address(0)
                ? 0
                : _openOceanParams.tokenOut.balanceOf(address(this)),
            fundingToken: fundingToken.balanceOf(address(this)),
            tokenOut: _tokenOut.balanceOf(address(this))
        });

        _performOpenOceanSwap(_openOceanParams);

        // we now have fundingToken; We swap it for the token out
        uint256 currentFundingBalance = fundingToken.balanceOf(address(this));
        if (currentFundingBalance <= initialBalances.fundingToken) revert NoFundingTokensReceived();
        uint256 _amountIn = currentFundingBalance - initialBalances.fundingToken;
        amountOut = adapter.swapWithExactInput(
            fundingToken,
            _tokenOut,
            _amountIn,
            _minAmountOut,
            _sqrtPriceLimitX96,
            _referralCode,
            msg.sender
        );

        // send everything back & collect fees
        _purgeAll(_openOceanParams, _tokenOut, initialBalances);
        launchpad.claimFees(_tokenOut);
    }

    /// @notice Buy with exact input and automatically swap collected fees to fundingToken
    /// @param _openOceanParams OpenOcean params for the main swap
    /// @param _tokenOut The token to receive
    /// @param _minAmountOut Minimum amount of tokens to receive
    /// @param _sqrtPriceLimitX96 Price limit for the swap
    /// @param _referralCode Referral code
    function buyWithExactInputWithOpenOceanAndSwapFees(
        OpenOceanParams memory _openOceanParams,
        IERC20 _tokenOut,
        uint256 _minAmountOut,
        uint160 _sqrtPriceLimitX96,
        bytes8 _referralCode
    ) external payable nonReentrant returns (uint256 amountOut) {
        // Perform the main buy
        // Track initial balances to prevent draining pre-existing tokens
        InitialBalances memory initialBalances = InitialBalances({
            tokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenOut: address(_openOceanParams.tokenOut) == address(0)
                ? 0
                : _openOceanParams.tokenOut.balanceOf(address(this)),
            fundingToken: fundingToken.balanceOf(address(this)),
            tokenOut: _tokenOut.balanceOf(address(this))
        });

        _performOpenOceanSwap(_openOceanParams);

        // we now have fundingToken; We swap it for the token out
        uint256 currentFundingBalance = fundingToken.balanceOf(address(this));
        if (currentFundingBalance <= initialBalances.fundingToken) revert NoFundingTokensReceived();
        uint256 _amountIn = currentFundingBalance - initialBalances.fundingToken;
        amountOut = adapter.swapWithExactInput(
            fundingToken,
            _tokenOut,
            _amountIn,
            _minAmountOut,
            _sqrtPriceLimitX96,
            _referralCode,
            msg.sender
        );

        // send everything back & collect fees
        _purgeAll(_openOceanParams, _tokenOut, initialBalances);
        launchpad.claimFees(_tokenOut);

        // Automatically swap any SOMETHING token fees to fundingToken (reward token)
        _swapFeesToFundingTokenViaAdapter(_tokenOut);
    }

    /// @inheritdoc IUIHelper
    function sellWithExactInputWithOpenOcean(
        OpenOceanParams memory _openOceanParams,
        IERC20 _tokenIn,
        uint256 _amountToSell,
        uint160 _sqrtPriceLimitX96,
        bytes8 _referralCode
    ) external payable override nonReentrant returns (uint256 amountSwapOut) {
        // Track initial balances to prevent draining pre-existing tokens
        InitialBalances memory initialBalances = InitialBalances({
            tokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenOut: address(_openOceanParams.tokenOut) == address(0)
                ? 0
                : _openOceanParams.tokenOut.balanceOf(address(this)),
            fundingToken: fundingToken.balanceOf(address(this)),
            tokenOut: _tokenIn.balanceOf(address(this))
        });

        _tokenIn.safeTransferFrom(msg.sender, address(this), _amountToSell);
        _tokenIn.forceApprove(address(adapter), type(uint256).max);

        // we now have token; we sell it for fundingToken
        amountSwapOut = adapter.swapWithExactInput(
            _tokenIn,
            fundingToken,
            _amountToSell,
            _openOceanParams.tokenAmountIn,
            _sqrtPriceLimitX96,
            _referralCode,
            msg.sender
        );

        // if needed we zap the fundingToken for any other token
        if (_openOceanParams.calls.length > 0) {
            if (address(_openOceanParams.tokenIn) != address(fundingToken))
                revert InvalidTokenIn();
            if (_openOceanParams.tokenAmountIn != 0)
                revert TokenAmountInMustBeZero();
            _performOpenOceanSwap(_openOceanParams);
        }

        // send everything back & collect fees
        _purgeAll(_openOceanParams, _tokenIn, initialBalances);
        launchpad.claimFees(_tokenIn);
        
    }

    /// @notice Sell with exact input and automatically swap collected fees to fundingToken
    /// @param _openOceanParams OpenOcean params for the main swap
    /// @param _tokenIn The token to sell (SOMETHING token)
    /// @param _amountToSell Amount of tokens to sell
    /// @param _sqrtPriceLimitX96 Price limit for the swap
    /// @param _referralCode Referral code
    function sellWithExactInputWithOpenOceanAndSwapFees(
        OpenOceanParams memory _openOceanParams,
        IERC20 _tokenIn,
        uint256 _amountToSell,
        uint160 _sqrtPriceLimitX96,
        bytes8 _referralCode
    ) external payable nonReentrant returns (uint256 amountSwapOut) {
        // Track initial balances to prevent draining pre-existing tokens
        InitialBalances memory initialBalances = InitialBalances({
            tokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenIn: address(_openOceanParams.tokenIn) == address(0)
                ? 0
                : _openOceanParams.tokenIn.balanceOf(address(this)),
            openOceanTokenOut: address(_openOceanParams.tokenOut) == address(0)
                ? 0
                : _openOceanParams.tokenOut.balanceOf(address(this)),
            fundingToken: fundingToken.balanceOf(address(this)),
            tokenOut: _tokenIn.balanceOf(address(this))
        });

        _tokenIn.safeTransferFrom(msg.sender, address(this), _amountToSell);
        _tokenIn.forceApprove(address(adapter), type(uint256).max);

        // we now have token; we sell it for fundingToken
        amountSwapOut = adapter.swapWithExactInput(
            _tokenIn,
            fundingToken,
            _amountToSell,
            _openOceanParams.tokenAmountIn,
            _sqrtPriceLimitX96,
            _referralCode,
            msg.sender
        );

        // if needed we zap the fundingToken for any other token
        if (_openOceanParams.calls.length > 0) {
            if (address(_openOceanParams.tokenIn) != address(fundingToken))
                revert InvalidTokenIn();
            if (_openOceanParams.tokenAmountIn != 0)
                revert TokenAmountInMustBeZero();
            _performOpenOceanSwap(_openOceanParams);
        }

        // send everything back & collect fees
        _purgeAll(_openOceanParams, _tokenIn, initialBalances);
        launchpad.claimFees(_tokenIn);

        // Automatically swap any SOMETHING token fees to fundingToken (reward token)
        _swapFeesToFundingTokenViaAdapter(_tokenIn);
    }

    /// @notice Swap collected fees from ReferralRewards (in token) to fundingToken via adapter
    /// @dev Flow: Pull token from ReferralRewards -> Swap to fundingToken via adapter -> Send back to ReferralRewards
    /// @param _token The token to swap from (must have a pool with fundingToken)
    function _swapFeesToFundingTokenViaAdapter(IERC20 _token) internal {
        // Skip if token is already fundingToken
        if (address(_token) == address(fundingToken)) return;
        
        // Get the entire token balance from ReferralRewards
        uint256 amountIn = _token.balanceOf(address(referralRewards));
        if (amountIn == 0) return; // Nothing to swap
        
        // Withdraw tokens from ReferralRewards to this contract
        referralRewards.emergencyWithdraw(_token, amountIn);
        
        // Approve adapter to spend the token
        _token.forceApprove(address(adapter), type(uint256).max);

        // Swap token to fundingToken via adapter, send directly to ReferralRewards
        adapter.swapWithExactInput(
            _token,
            fundingToken,
            amountIn,
            0, // No minimum (can add slippage protection if needed)
            0, // No price limit
            bytes8(0), // No referral code for fee swaps
            address(referralRewards) // Send fundingToken directly to ReferralRewards
        );
    }

    /// @notice Purges all tokens from the contract
    /// @param openOceanParams The parameters for the swap
    /// @param _tokenOut The token output
    /// @param initialBalances The initial balances before the transaction
    function _purgeAll(
        OpenOceanParams memory openOceanParams,
        IERC20 _tokenOut,
        InitialBalances memory initialBalances
    ) internal {
        _purge(
            address(openOceanParams.tokenIn),
            initialBalances.openOceanTokenIn
        );
        _purge(
            address(openOceanParams.tokenOut),
            initialBalances.openOceanTokenOut
        );
        _purge(address(fundingToken), initialBalances.fundingToken);
        _purge(address(_tokenOut), initialBalances.tokenOut);
    }

    /// @notice Purges the given token
    /// @param token The token to purge
    /// @param initialBalance The initial balance of the token before the transaction
    function _purge(address token, uint256 initialBalance) internal {
        if (token == address(0)) {
            if (address(this).balance > initialBalance) {
                (bool success, ) = msg.sender.call{
                    value: address(this).balance - initialBalance
                }("");
                if (!success) revert ETHTransferFailed();
            }
        } else {
            uint256 currentBalance = IERC20(token).balanceOf(address(this));
            if (currentBalance > initialBalance) {
                IERC20(token).safeTransfer(
                    msg.sender,
                    currentBalance - initialBalance
                );
            }
        }
    }

    /// @notice Performs OpenOcean swap
    /// @param params The parameters for the swap
    function _performOpenOceanSwap(OpenOceanParams memory params) internal {
        // Handle input token transfers and approvals
        if (address(params.tokenIn) == address(0)) {
            if (msg.value != params.tokenAmountIn) revert InvalidETHAmount();
        } else if (params.tokenAmountIn > 0) {
            params.tokenIn.safeTransferFrom(
                msg.sender,
                address(this),
                params.tokenAmountIn
            );
            params.tokenIn.forceApprove(address(openOcean), type(uint256).max);
        }

        // Only perform swap if there are calls to execute
        if (params.calls.length > 0) {
            IOpenOceanExchange.SwapDescription
                memory swapDesc = IOpenOceanExchange.SwapDescription({
                    srcToken: params.tokenIn,
                    dstToken: params.tokenOut,
                    srcReceiver: address(this), // Contract receives the tokens first
                    dstReceiver: address(this), // Contract receives the output tokens
                    amount: params.tokenAmountIn,
                    minReturnAmount: params.minReturnAmount,
                    guaranteedAmount: params.guaranteedAmount,
                    flags: params.flags,
                    referrer: params.referrer,
                    permit: params.permit
                });

            // Execute the swap and handle aggregator reverts
            uint256 returnAmount;
            try openOcean.swap{value: msg.value}(
                IOpenOceanCaller(address(this)),
                swapDesc,
                params.calls
            ) returns (uint256 _returnAmount) {
                returnAmount = _returnAmount;
            } catch {
                revert OpenOceanCallFailed();
            }

            if (returnAmount < params.minReturnAmount) {
                revert InsufficientOutputAmount(
                    returnAmount,
                    params.minReturnAmount
                );
            }
        }
    }

    /// @notice Required implementation for IERC721Receiver to receive ERC721 tokens
    function onERC721Received(
        address,
        address,
        uint256,
        bytes calldata
    ) external pure override returns (bytes4) {
        return IERC721Receiver.onERC721Received.selector;
    }
}

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

// 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
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

File 6 of 45 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

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

File 7 of 45 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

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

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

File 11 of 45 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// 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
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/Hashes.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? _efficientKeccak256(a, b) : _efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function _efficientKeccak256(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

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

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

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

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

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

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.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 32 of 45 : 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 {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title IWETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun

pragma solidity ^0.8.0;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IClPool} from "contracts/interfaces/thirdparty/IClPool.sol";

/// @title Concentrated Liquidity Market Maker Adapter Interface
/// @notice Interface for interacting with concentrated liquidity pools
/// @dev Implements single-sided liquidity provision and fee claiming
interface ICLMMAdapter {
  /// @notice Parameters for adding liquidity to a pool
    struct AddLiquidityParams {
    IERC20 tokenBase;
    IERC20 tokenQuote;
    int24 tick0;
    int24 tick1;
    int24 tick2;
  }
  
  /// @notice Emitted when single-sided liquidity is added
  /// @param token The base token address
  /// @param pool The pool address
  /// @param tick0 The first tick
  /// @param tick1 The second tick
  /// @param tick2 The third tick
  /// @param tokenId0 The NFT token ID for first position
  /// @param tokenId1 The NFT token ID for second position
  event LiquidityAdded(
    address indexed token,
    address indexed pool,
    int24 tick0,
    int24 tick1,
    int24 tick2,
    uint256 tokenId0,
    uint256 tokenId1
  );

  /// @notice Emitted when a swap with exact input is executed
  /// @param tokenIn The input token address
  /// @param tokenOut The output token address
  /// @param amountIn The amount of input tokens
  /// @param amountOut The amount of output tokens
  /// @param recipient The recipient address
  event SwapExecutedExactInput(
    address indexed tokenIn,
    address indexed tokenOut,
    uint256 amountIn,
    uint256 amountOut,
    address indexed recipient
  );

  /// @notice Emitted when a swap with exact output is executed
  /// @param tokenIn The input token address
  /// @param tokenOut The output token address
  /// @param amountIn The amount of input tokens
  /// @param amountOut The amount of output tokens
  /// @param recipient The recipient address
  event SwapExecutedExactOutput(
    address indexed tokenIn,
    address indexed tokenOut,
    uint256 amountIn,
    uint256 amountOut,
    address indexed recipient
  );

  /// @notice Thrown when caller is not the launchpad contract
  error Unauthorized();

  /// @notice Thrown when tick ordering is invalid (tick0 must be < tick1 < tick2)
  error InvalidTickOrdering();

  /// @notice Thrown when a tick is not aligned to the tick spacing
  /// @param tick The tick that is not aligned
  error TickNotAligned(int24 tick);

  /// @notice Thrown when tick0 is not greater than MIN_TICK
  /// @param tick0 The provided tick0
  /// @param minTick The minimum allowed tick
  error Tick0OutOfRange(int24 tick0, int24 minTick);

  /// @notice Thrown when tick2 is not less than MAX_TICK
  /// @param tick2 The provided tick2
  /// @param maxTick The maximum allowed tick
  error Tick2OutOfRange(int24 tick2, int24 maxTick);

  /// @notice Add single-sided liquidity to a concentrated pool
  /// @dev Provides liquidity across three ticks with different amounts
  /// @param _params The liquidity parameters
  /// @return pool The address of the pool
  function addSingleSidedLiquidity(AddLiquidityParams memory _params) external returns (address pool);

  /// @notice Swap a token with exact output
  /// @param _tokenIn The token to swap
  /// @param _tokenOut The token to receive
  /// @param _amountOut The amount of tokens to swap
  /// @param _maxAmountIn The maximum amount of tokens to receive
  /// @param _sqrtPriceLimitX96 The price limit for the swap (0 = no limit)
  /// @param _referralCode Optional referral code (bytes8(0) for no referral)
  /// @param _user The actual user performing the swap (for referral tracking)
  /// @return amountIn The amount of tokens received
  function swapWithExactOutput(
    IERC20 _tokenIn,
    IERC20 _tokenOut,
    uint256 _amountOut,
    uint256 _maxAmountIn,
    uint160 _sqrtPriceLimitX96,
    bytes8 _referralCode,
    address _user
  ) external returns (uint256 amountIn);

  /// @notice Swap a token with exact input
  /// @param _tokenIn The token to swap
  /// @param _tokenOut The token to receive
  /// @param _amountIn The amount of tokens to swap
  /// @param _minAmountOut The minimum amount of tokens to receive
  /// @param _sqrtPriceLimitX96 The price limit for the swap (0 = no limit)
  /// @param _referralCode Optional referral code (bytes8(0) for no referral)
  /// @param _user The actual user performing the swap (for referral tracking)
  /// @return amountOut The amount of tokens received
  function swapWithExactInput(
    IERC20 _tokenIn,
    IERC20 _tokenOut,
    uint256 _amountIn,
    uint256 _minAmountOut,
    uint160 _sqrtPriceLimitX96,
    bytes8 _referralCode,
    address _user
  ) external returns (uint256 amountOut);

  /// @notice Returns the address of the Launchpad contract
  /// @return launchpad The address of the Launchpad contract
  function launchpad() external view returns (address launchpad);

  /// @notice Claim accumulated fees from the pool
  /// @param _token The token address to claim fees for
  /// @return fee0 The amount of token0 fees to claim
  /// @return fee1 The amount of token1 fees to claim
  function claimFees(address _token) external returns (uint256 fee0, uint256 fee1);

  /// @notice claimed fees from the pool
  /// @param _token The token address to claim fees for
  /// @return fee0 The amount of token0 fees to claim
  /// @return fee1 The amount of token1 fees to claim
  function claimedFees(address _token) external view returns (uint256 fee0, uint256 fee1);
}

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun

pragma solidity ^0.8.0;

/// @title IReferralSystem Interface
/// @notice Interface for the ReferralSystem contract that handles referral tracking
/// @dev Rewards are calculated off-chain based on trading fees and distributed via Merkle proofs
interface IReferralSystem {
  /// @notice Referral data structure
  /// @param referralCode Unique 8-byte referral code
  /// @param referrer Address who referred this user
  /// @param totalReferrals Total number of direct referrals
  /// @param isActive Whether the referral code is active
  /// @param createdAt Timestamp when referral code was created
  struct ReferralData {
    bytes8 referralCode;
    address referrer;
    uint256 totalReferrals;
    bool isActive;
    uint256 createdAt;
  }

  /// @notice Emitted when a referral code is registered
  /// @param user Address of the user registering the code
  /// @param referralCode The referral code registered
  event ReferralCodeRegistered(address indexed user, bytes8 referralCode);

  /// @notice Emitted when a referral relationship is established
  /// @param referrer Address of the referrer
  /// @param referee Address of the referee
  /// @param referralCode The referral code used
  event ReferralRelationshipEstablished(
    address indexed referrer,
    address indexed referee,
    bytes8 referralCode
  );

  /// @notice Emitted when referral registration is enabled/disabled
  /// @param enabled Whether registration is enabled
  event ReferralRegistrationToggled(bool enabled);

  /// @notice Emitted when rewards are claimed
  /// @param user Address claiming rewards
  /// @param amount Amount of rewards claimed
  event RewardsClaimed(address indexed user, address indexed token, uint256 amount);

  /// @notice Emitted when a creator referral code is recorded
  /// @param token Address of the token
  /// @param creatorReferralCode The creator referral code recorded
  event CreatorReferralCodeRecorded(address indexed token, bytes8 creatorReferralCode);

  // Errors
  error InvalidReferralCode();
  error ReferralCodeAlreadyTaken();
  error UserAlreadyHasReferralCode();
  error ReferralRegistrationDisabled();
  error InvalidUserAddress();
  error InvalidVolume();
  error CannotReferYourself();
  error CircularReferralNotAllowed();
  error PercentageTooHigh();
  error UnauthorizedAccess();
  error InvalidTokenAddress();
  error CreatorReferralCodeAlreadyRecorded();

  /// @notice Registers a referral code for the caller
  /// @param referralCode The 8-byte referral code to register
  function registerReferralCode(bytes8 referralCode) external;

  /// @notice Registers a referral code for another user (admin only)
  /// @param user Address of the user to register the code for
  /// @param referralCode The 8-byte referral code to register
  function registerReferralCodeFor(address user, bytes8 referralCode) external;

  /// @notice Generates a referral code from an address
  /// @param user Address to generate code from
  /// @return referralCode Generated 8-byte referral code
  function generateReferralCodeFromAddress(address user) external view returns (bytes8);

  /// @notice Generates a referral code from a custom string
  /// @param customString Custom string to generate code from
  /// @return referralCode Generated 8-byte referral code
  function generateReferralCodeFromString(string memory customString) external view returns (bytes8);

  /// @notice Records a creator referral code for a token
  /// @param token Address of the token
  /// @param creatorReferralCode The creator referral code to record
  function recordCreatorReferralCode(address token, bytes8 creatorReferralCode) external;

  /// @notice Gets the creator referrer for a token
  /// @param token Address of the token
  /// @return creatorReferrer Address of the creator referrer
  /// @return creatorReferralCode The creator referral code
  function getCreatorReferrerByToken(address token) external view returns (address, bytes8);

  /// @notice Establishes a referral relationship if not already set
  /// @param user Address of the user being referred
  /// @param referralCode Referral code used
  function useReferralCode(address user, bytes8 referralCode) external;

  /// @notice Gets the referrer for a user
  /// @param user Address of the user
  /// @return referrer Address of the referrer
  function getReferrer(address user) external view returns (address);

  /// @notice Gets all referees for a referrer
  /// @param referrer Address of the referrer
  /// @return referees Array of referee addresses
  function getReferees(address referrer) external view returns (address[] memory);

  /// @notice Gets total number of referrals for a referrer
  /// @param referrer Address of the referrer
  /// @return count Number of referrals
  function getReferralCount(address referrer) external view returns (uint256);

  /// @notice Checks if a referral code is available
  /// @param referralCode The referral code to check
  /// @return available Whether the code is available
  function isReferralCodeAvailable(bytes8 referralCode) external view returns (bool);

  /// @notice Gets the user for a referral code
  /// @param referralCode The referral code
  /// @return user Address of the user who owns the code
  function getReferralCodeOwner(bytes8 referralCode) external view returns (address);

  /// @notice Gets total claimed rewards for a user
  /// @param user Address of the user
  /// @return claimed Total rewards claimed
  function getClaimedRewards(address user, address token) external view returns (uint256);

  /// @notice Records claimed rewards for a user (only callable by rewards contract)
  /// @param user Address of the user
  /// @param amount Amount of rewards claimed
  function recordClaimedRewards(address user, address token, uint256 amount) external;

  /// @notice Toggles referral registration (admin only)
  /// @param enabled Whether to enable registration
  function toggleReferralRegistration(bool enabled) external;

  /// @notice Checks if referral registration is enabled
  /// @return enabled Whether registration is enabled
  function isReferralRegistrationEnabled() external view returns (bool);
}

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.0;

import {ICLMMAdapter} from "./ICLMMAdapter.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IReferralSystem} from "./IReferralSystem.sol";

/// @title ITokenLaunchpad Interface
/// @notice Interface for the TokenLaunchpad contract that handles token launches
interface ITokenLaunchpad is IERC721 {
  /// @notice Parameters required to create a new token launch
  /// @param name The name of the token
  /// @param symbol The symbol of the token
  /// @param metadata IPFS hash or other metadata about the token
  /// @param fundingToken The token used for funding the launch
  /// @param salt Random value to ensure unique deployment address
  /// @param launchTick The tick at which the token launches
  /// @param graduationTick The tick that must be reached for graduation
  /// @param upperMaxTick The maximum tick allowed
  /// @param graduationLiquidity The liquidity at graduation
  /// @param fee The fee for the token liquidity pair
  /// @param adapter The adapter used for the token launch
  struct CreateParams {
    bytes32 salt;
    string metadata;
    string name;
    string symbol;
  }

  // Contains numeric launch parameters
  struct ValueParams {
    int24 launchTick;
    int24 graduationTick;
    int24 upperMaxTick;
    uint24 fee;
    int24 tickSpacing;
    uint256 graduationLiquidity;
  }

  /// @notice Emitted when fee settings are updated
  /// @param feeDestination The address where fees will be sent
  /// @param fee The new fee amount
  event FeeUpdated(address indexed feeDestination, uint256 fee);

  /// @notice Emitted when a token is launched
  /// @param token The token that was launched
  /// @param adapter The address of the adapter used to launch the token
  /// @param pool The address of the pool for the token
  /// @param params The parameters used to launch the token
  event TokenLaunched(IERC20 indexed token, address indexed adapter, address indexed pool, CreateParams params);

  /// @notice Emitted when referral settings are updated
  /// @param referralDestination The address where referrals will be sent
  /// @param referralFee The new referral fee amount
  event ReferralUpdated(address indexed referralDestination, uint256 referralFee);

  /// @notice Emitted when tokens are allocated to the creator
  /// @param token The token that was launched
  /// @param creator The address of the creator
  /// @param amount The amount of tokens allocated to the creator
  event CreatorAllocation(IERC20 indexed token, address indexed creator, uint256 amount);

  /// @notice Emitted when the cron is updated
  /// @param newCron The new cron address
  event CronUpdated(address indexed newCron);

  /// @notice Emitted when the metadata URL is updated
  /// @param metadataUrl The new metadata URL
  event MetadataUrlUpdated(string metadataUrl);

  /// @notice Emitted when the launch ticks are updated
  /// @param _launchTick The new launch tick
  /// @param _graduationTick The new graduation tick
  /// @param _upperMaxTick The new upper max tick
  event LaunchTicksUpdated(int24 _launchTick, int24 _graduationTick, int24 _upperMaxTick);

  /// @notice Emitted when a fee is claimed for a token
  /// @param _token The token that the fee was claimed for
  /// @param _fee0 The amount of fee claimed for token0
  /// @param _fee1 The amount of fee claimed for token1
  event FeeClaimed(IERC20 indexed _token, uint256 _fee0, uint256 _fee1);

  /// @notice Thrown when the deployed token address doesn't match the expected address
  error InvalidTokenAddress();

  /// @notice Thrown when caller is not the cron or owner
  error Unauthorized();

  /// @notice Emitted when the protocol treasury address is updated
  /// @param newTreasury The new treasury address
  event TreasuryUpdated(address indexed newTreasury);
  
  /// @notice Emitted when the referral rewarder contract address is updated
  /// @param newReferralRewarder The new referral rewarder contract address
  event ReferralRewarderUpdated(address indexed newReferralRewarder);

  /// @notice Initializes the launchpad contract
  /// @param _owner The owner address
  /// @param _fundingToken The funding token address
  /// @param _adapter The adapter address
  function initialize(address _owner, address _fundingToken, address _adapter) external;

  /// @notice Gets the funding token
  /// @return fundingToken The funding token
  function fundingToken() external view returns (IERC20 fundingToken);

  /// @notice Creates a new token launch
  /// @param p The parameters for the token launch
  /// @param expected The expected address where token will be deployed
  /// @param amount The amount of tokens to buy
  /// @param creatorReferralCode The creator referral code used by the token creator
  /// @return token The address of the newly created token
  /// @return received The amount of tokens received if the user chooses to buy at launch
  /// @return tokenId The token id of the newly created token
  function createAndBuy(CreateParams memory p, address expected, uint256 amount, bytes8 creatorReferralCode)
    external
    payable
    returns (address token, uint256 received, uint256 tokenId);

  /// @notice Gets the adapter
  /// @return adapter The adapter
  function adapter() external view returns (ICLMMAdapter adapter);

  /// @notice Gets the total number of tokens launched
  /// @return totalTokens The total count of launched tokens
  function getTotalTokens() external view returns (uint256 totalTokens);

  /// @notice Claims accumulated fees for a specific token
  /// @param _token The token to claim fees for
  function claimFees(IERC20 _token) external;

  /// @notice Gets the claimed fees for a token
  /// @param _token The token to get the claimed fees for
  /// @return claimedFees0 The claimed fees for the token
  /// @return claimedFees1 The claimed fees for the token
  function claimedFees(IERC20 _token) external view returns (uint256 claimedFees0, uint256 claimedFees1);

  /// @notice Gets the referral rewarder
  /// @return referralRewarder The referral rewarder
  function referralRewarder() external view returns (address referralRewarder);

  /// @notice Get the referral system contract address
  /// @return The referral system contract address
  function referralSystem() external view returns (IReferralSystem);

  /// @notice Sets the referral system contract address
  /// @param _referralSystem The new referral system contract address
  function setReferralSystem(address _referralSystem) external;

  /// @notice Get the cron address
  /// @return The cron address
  function cron() external view returns (address);

  /// @notice Get the something treasury address
  /// @return The treasury address
  function somethingTreasury() external view returns (address);

  /// @notice Set the something treasury address
  /// @param _treasury The new treasury address
  function setSomethingTreasury(address _treasury) external;

  /// @notice Set the referral rewarder address
  /// @param _referralRewarder The new referral rewarder address
  function setReferralRewarder(address _referralRewarder) external;

  /// @notice Get the launch tick
  /// @return The launch tick
  function launchTick() external view returns (int24);

  /// @notice Set launch ticks
  /// @param _launchTick The launch tick
  /// @param _graduationTick The graduation tick
  /// @param _upperMaxTick The upper max tick
  function setLaunchTicks(int24 _launchTick, int24 _graduationTick, int24 _upperMaxTick) external;
}

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun
pragma solidity ^0.8.0;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ITokenLaunchpad} from "./ITokenLaunchpad.sol";
import {IOpenOceanCaller} from "./thirdparty/IOpenOcean.sol";

/// @title UI Helper Interface
/// @notice Interface for the UIHelper contract that facilitates token creation, buying, and selling with OpenOcean integration
interface IUIHelper {
    /// @notice Parameters for OpenOcean aggregator integration
    struct OpenOceanParams {
        IERC20 tokenIn;
        uint256 tokenAmountIn;
        IERC20 tokenOut;
        uint256 minReturnAmount;
        uint256 guaranteedAmount;
        uint256 flags;
        address referrer;
        bytes permit;
        IOpenOceanCaller.CallDescription[] calls;
    }
    struct InitialBalances {
        uint256 tokenIn;
        uint256 openOceanTokenIn;
        uint256 openOceanTokenOut;
        uint256 fundingToken;
        uint256 tokenOut;
    }

    /// @notice Thrown when no funding tokens were received after zap
    error NoFundingTokensReceived();

    /// @notice Thrown when the token in doesn't match the funding token
    error InvalidTokenIn();

    /// @notice Thrown when token amount in should be zero
    error TokenAmountInMustBeZero();

    /// @notice Thrown when ETH transfer fails
    error ETHTransferFailed();

    /// @notice Thrown when msg.value doesn't match the expected ETH amount
    error InvalidETHAmount();

    /// @notice Thrown when the OpenOcean aggregator call fails
    error OpenOceanCallFailed();

    /// @notice Thrown when received amount is less than minimum required
    /// @param received The amount received
    /// @param minimum The minimum amount required
    error InsufficientOutputAmount(uint256 received, uint256 minimum);

    /// @notice Creates a new token and buys it using OpenOcean for swapping
    /// @param _openOceanParams The parameters for the OpenOcean swap
    /// @param _params The token creation parameters
    /// @param _expected The expected token address (0 for no validation)
    /// @param _amount The amount of funding token to buy with
    /// @param _creatorReferralCode The creator referral code used by the token creator
    /// @return token The address of the created token
    /// @return received The amount of tokens received from the buy
    /// @return swapped The amount swapped for initial listing
    /// @return tokenId The NFT token ID representing ownership
    function createAndBuy(
        OpenOceanParams memory _openOceanParams,
        ITokenLaunchpad.CreateParams memory _params,
        address _expected,
        uint256 _amount,
        bytes8 _creatorReferralCode
    )
        external
        payable
        returns (
            address token,
            uint256 received,
            uint256 swapped,
            uint256 tokenId
        );

    /// @notice Buys a token with exact input using OpenOcean
    /// @param _openOceanParams The parameters for the OpenOcean swap
    /// @param _tokenOut The token to receive
    /// @param _minAmountOut The minimum amount of tokens to receive
    /// @param _sqrtPriceLimitX96 The price limit for the swap (0 = no limit)
    /// @param _referralCode Optional referral code to use (bytes8(0) for no referral)
    /// @return amountOut The amount of tokens received
    function buyWithExactInputWithOpenOcean(
        OpenOceanParams memory _openOceanParams,
        IERC20 _tokenOut,
        uint256 _minAmountOut,
        uint160 _sqrtPriceLimitX96,
        bytes8 _referralCode
    ) external payable returns (uint256 amountOut);

    /// @notice Sells a token with exact input using OpenOcean
    /// @param _openOceanParams The parameters for the OpenOcean swap
    /// @param _tokenIn The token to sell
    /// @param _amountToSell The amount of tokens to sell
    /// @param _sqrtPriceLimitX96 The price limit for the swap (0 = no limit)
    /// @param _referralCode Optional referral code to use (bytes8(0) for no referral)
    /// @return amountSwapOut The amount received from the swap
    function sellWithExactInputWithOpenOcean(
        OpenOceanParams memory _openOceanParams,
        IERC20 _tokenIn,
        uint256 _amountToSell,
        uint160 _sqrtPriceLimitX96,
        bytes8 _referralCode
    ) external payable returns (uint256 amountSwapOut);
}

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun

pragma solidity ^0.8.0;

import "./pool/IClPoolActions.sol";
import "./pool/IClPoolDerivedState.sol";
import "./pool/IClPoolImmutables.sol";
import "./pool/IClPoolOwnerActions.sol";
import "./pool/IClPoolState.sol";

/// @title The interface for a CL V2 Pool
/// @notice A CL pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IClPool is IClPoolImmutables, IClPoolState, IClPoolDerivedState, IClPoolActions, IClPoolOwnerActions {
  /// @notice Initializes a pool with parameters provided
  function initialize(
    address _factory,
    address _nfpManager,
    address _veRam,
    address _voter,
    address _token0,
    address _token1,
    uint24 _fee,
    int24 _tickSpacing
  ) external;
}

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun
pragma solidity ^0.8.0;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IOpenOceanCaller {
    struct CallDescription {
        uint256 target;
        uint256 gasLimit;
        uint256 value;
        bytes data;
    }
    function makeCalls(CallDescription[] memory desc) external payable;
}

interface IOpenOceanExchange {
    struct SwapDescription {
        IERC20 srcToken;
        IERC20 dstToken;
        address srcReceiver;
        address dstReceiver;
        uint256 amount;
        uint256 minReturnAmount;
        uint256 guaranteedAmount;
        uint256 flags;
        address referrer;
        bytes permit;
    }

    function swap(
        IOpenOceanCaller caller,
        SwapDescription calldata desc,
        IOpenOceanCaller.CallDescription[] calldata calls
    ) external payable returns (uint256 returnAmount);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IClPoolActions {
  /// @notice Sets the initial price for the pool
  /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
  /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
  function initialize(uint160 sqrtPriceX96) external;

  /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position at index 0
  /// @dev The caller of this method receives a callback in the form of IRamsesV2MintCallback#ramsesV2MintCallback
  /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
  /// on tickLower, tickUpper, the amount of liquidity, and the current price.
  /// @param recipient The address for which the liquidity will be created
  /// @param tickLower The lower tick of the position in which to add liquidity
  /// @param tickUpper The upper tick of the position in which to add liquidity
  /// @param amount The amount of liquidity to mint
  /// @param data Any data that should be passed through to the callback
  /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the
  /// callback
  /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the
  /// callback
  function mint(address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data)
    external
    returns (uint256 amount0, uint256 amount1);

  /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
  /// @dev The caller of this method receives a callback in the form of IRamsesV2MintCallback#ramsesV2MintCallback
  /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
  /// on tickLower, tickUpper, the amount of liquidity, and the current price.
  /// @param recipient The address for which the liquidity will be created
  /// @param index The index for which the liquidity will be created
  /// @param tickLower The lower tick of the position in which to add liquidity
  /// @param tickUpper The upper tick of the position in which to add liquidity
  /// @param amount The amount of liquidity to mint
  /// @param veNFTTokenId The veNFT tokenId to attach to the position
  /// @param data Any data that should be passed through to the callback
  /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the
  /// callback
  /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the
  /// callback
  function mint(
    address recipient,
    uint256 index,
    int24 tickLower,
    int24 tickUpper,
    uint128 amount,
    uint256 veNFTTokenId,
    bytes calldata data
  ) external returns (uint256 amount0, uint256 amount1);

  /// @notice Collects tokens owed to a position
  /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
  /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
  /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
  /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
  /// @param recipient The address which should receive the fees collected
  /// @param tickLower The lower tick of the position for which to collect fees
  /// @param tickUpper The upper tick of the position for which to collect fees
  /// @param amount0Requested How much token0 should be withdrawn from the fees owed
  /// @param amount1Requested How much token1 should be withdrawn from the fees owed
  /// @return amount0 The amount of fees collected in token0
  /// @return amount1 The amount of fees collected in token1
  function collect(
    address recipient,
    int24 tickLower,
    int24 tickUpper,
    uint128 amount0Requested,
    uint128 amount1Requested
  ) external returns (uint128 amount0, uint128 amount1);

  /// @notice Collects tokens owed to a position
  /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
  /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
  /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
  /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
  /// @param recipient The address which should receive the fees collected
  /// @param index The index of the position to be collected
  /// @param tickLower The lower tick of the position for which to collect fees
  /// @param tickUpper The upper tick of the position for which to collect fees
  /// @param amount0Requested How much token0 should be withdrawn from the fees owed
  /// @param amount1Requested How much token1 should be withdrawn from the fees owed
  /// @return amount0 The amount of fees collected in token0
  /// @return amount1 The amount of fees collected in token1
  function collect(
    address recipient,
    uint256 index,
    int24 tickLower,
    int24 tickUpper,
    uint128 amount0Requested,
    uint128 amount1Requested
  ) external returns (uint128 amount0, uint128 amount1);

  /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position at index 0
  /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
  /// @dev Fees must be collected separately via a call to #collect
  /// @param tickLower The lower tick of the position for which to burn liquidity
  /// @param tickUpper The upper tick of the position for which to burn liquidity
  /// @param amount How much liquidity to burn
  /// @return amount0 The amount of token0 sent to the recipient
  /// @return amount1 The amount of token1 sent to the recipient
  function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1);

  /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
  /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
  /// @dev Fees must be collected separately via a call to #collect
  /// @param index The index for which the liquidity will be burned
  /// @param tickLower The lower tick of the position for which to burn liquidity
  /// @param tickUpper The upper tick of the position for which to burn liquidity
  /// @param amount How much liquidity to burn
  /// @return amount0 The amount of token0 sent to the recipient
  /// @return amount1 The amount of token1 sent to the recipient
  function burn(uint256 index, int24 tickLower, int24 tickUpper, uint128 amount)
    external
    returns (uint256 amount0, uint256 amount1);

  /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
  /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
  /// @dev Fees must be collected separately via a call to #collect
  /// @param index The index for which the liquidity will be burned
  /// @param tickLower The lower tick of the position for which to burn liquidity
  /// @param tickUpper The upper tick of the position for which to burn liquidity
  /// @param amount How much liquidity to burn
  /// @param veNFTTokenId The veNFT Token Id to attach
  /// @return amount0 The amount of token0 sent to the recipient
  /// @return amount1 The amount of token1 sent to the recipient
  function burn(uint256 index, int24 tickLower, int24 tickUpper, uint128 amount, uint256 veNFTTokenId)
    external
    returns (uint256 amount0, uint256 amount1);

  /// @notice Swap token0 for token1, or token1 for token0
  /// @dev The caller of this method receives a callback in the form of IRamsesV2SwapCallback#ramsesV2SwapCallback
  /// @param recipient The address to receive the output of the swap
  /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
  /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or
  /// exact output (negative)
  /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
  /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
  /// @param data Any data to be passed through to the callback
  /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
  /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
  function swap(
    address recipient,
    bool zeroForOne,
    int256 amountSpecified,
    uint160 sqrtPriceLimitX96,
    bytes calldata data
  ) external returns (int256 amount0, int256 amount1);

  /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
  /// @dev The caller of this method receives a callback in the form of IRamsesV2FlashCallback#ramsesV2FlashCallback
  /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
  /// with 0 amount{0,1} and sending the donation amount(s) from the callback
  /// @param recipient The address which will receive the token0 and token1 amounts
  /// @param amount0 The amount of token0 to send
  /// @param amount1 The amount of token1 to send
  /// @param data Any data to be passed through to the callback
  function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;

  /// @notice Increase the maximum number of price and liquidity observations that this pool will store
  /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
  /// the input observationCardinalityNext.
  /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
  function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IClPoolDerivedState {
  /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block
  /// timestamp
  /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one
  /// representing
  /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted
  /// average tick,
  /// you must call it with secondsAgos = [3600, 0].
  /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
  /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
  /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
  /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
  /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each
  /// `secondsAgos` from the current block timestamp
  /// @return secondsPerBoostedLiquidityPeriodX128s Cumulative seconds per boosted liquidity-in-range value as of each
  /// `secondsAgos` from the current block timestamp
  function observe(uint32[] calldata secondsAgos)
    external
    view
    returns (
      int56[] memory tickCumulatives,
      uint160[] memory secondsPerLiquidityCumulativeX128s,
      uint160[] memory secondsPerBoostedLiquidityPeriodX128s
    );

  /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
  /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
  /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
  /// snapshot is taken and the second snapshot is taken. Boosted data is only valid if it's within the same period
  /// @param tickLower The lower tick of the range
  /// @param tickUpper The upper tick of the range
  /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
  /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
  /// @return secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted liquidity for the range
  /// @return secondsInside The snapshot of seconds per liquidity for the range
  function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
    external
    view
    returns (
      int56 tickCumulativeInside,
      uint160 secondsPerLiquidityInsideX128,
      uint160 secondsPerBoostedLiquidityInsideX128,
      uint32 secondsInside
    );

  /// @notice Returns the seconds per liquidity and seconds inside a tick range for a period
  /// @param tickLower The lower tick of the range
  /// @param tickUpper The upper tick of the range
  /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
  /// @return secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted liquidity for the range
  function periodCumulativesInside(uint32 period, int24 tickLower, int24 tickUpper)
    external
    view
    returns (uint160 secondsPerLiquidityInsideX128, uint160 secondsPerBoostedLiquidityInsideX128);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IClPoolImmutables {
  /// @notice The contract that deployed the pool, which must adhere to the IClPoolFactory interface
  /// @return The contract address
  function factory() external view returns (address);

  /// @notice The contract that manages CL NFPs, which must adhere to the INonfungiblePositionManager interface
  /// @return The contract address
  function nfpManager() external view returns (address);

  /// @notice The contract that manages veNFTs, which must adhere to the IVotingEscrow interface
  /// @return The contract address
  function votingEscrow() external view returns (address);

  /// @notice The contract that manages RA votes, which must adhere to the IVoter interface
  /// @return The contract address
  function voter() external view returns (address);

  /// @notice The first of the two tokens of the pool, sorted by address
  /// @return The token contract address
  function token0() external view returns (address);

  /// @notice The second of the two tokens of the pool, sorted by address
  /// @return The token contract address
  function token1() external view returns (address);

  /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
  /// @return The fee
  function fee() external view returns (uint24);

  /// @notice The pool tick spacing
  /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
  /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
  /// This value is an int24 to avoid casting even though it is always positive.
  /// @return The tick spacing
  function tickSpacing() external view returns (int24);

  /// @notice The maximum amount of position liquidity that can use any tick in the range
  /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
  /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
  /// @return The max amount of liquidity per tick
  function maxLiquidityPerTick() external view returns (uint128);

  /// @notice returns the current fee set for the pool
  function currentFee() external view returns (uint24);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IClPoolOwnerActions {
  /// @notice Set the protocol's % share of the fees
  /// @dev Fees start at 50%, with 5% increments
  function setFeeProtocol() external;

  /// @notice Collect the protocol fee accrued to the pool
  /// @param recipient The address to which collected protocol fees should be sent
  /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
  /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
  /// @return amount0 The protocol fee collected in token0
  /// @return amount1 The protocol fee collected in token1
  function collectProtocol(address recipient, uint128 amount0Requested, uint128 amount1Requested)
    external
    returns (uint128 amount0, uint128 amount1);

  function setFee(uint24 _fee) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IClPoolState {
  /// @notice reads arbitrary storage slots and returns the bytes
  /// @param slots The slots to read from
  /// @return returnData The data read from the slots
  function readStorage(bytes32[] calldata slots) external view returns (bytes32[] memory returnData);

  /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
  /// when accessed externally.
  /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
  /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
  /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
  /// boundary.
  /// observationIndex The index of the last oracle observation that was written,
  /// observationCardinality The current maximum number of observations stored in the pool,
  /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
  /// feeProtocol The protocol fee for both tokens of the pool.
  /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
  /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
  /// unlocked Whether the pool is currently locked to reentrancy
  function slot0()
    external
    view
    returns (
      uint160 sqrtPriceX96,
      int24 tick,
      uint16 observationIndex,
      uint16 observationCardinality,
      uint16 observationCardinalityNext,
      uint8 feeProtocol,
      bool unlocked
    );

  /// @notice Returns the last tick of a given period
  /// @param period The period in question
  /// @return previousPeriod The period before current period
  /// @dev this is because there might be periods without trades
  ///  startTick The start tick of the period
  ///  lastTick The last tick of the period, if the period is finished
  ///  endSecondsPerLiquidityPeriodX128 Seconds per liquidity at period's end
  ///  endSecondsPerBoostedLiquidityPeriodX128 Seconds per boosted liquidity at period's end
  function periods(uint256 period)
    external
    view
    returns (
      uint32 previousPeriod,
      int24 startTick,
      int24 lastTick,
      uint160 endSecondsPerLiquidityCumulativeX128,
      uint160 endSecondsPerBoostedLiquidityCumulativeX128,
      uint32 boostedInRange
    );

  /// @notice The last period where a trade or liquidity change happened
  function lastPeriod() external view returns (uint256);

  /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the
  /// pool
  /// @dev This value can overflow the uint256
  function feeGrowthGlobal0X128() external view returns (uint256);

  /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the
  /// pool
  /// @dev This value can overflow the uint256
  function feeGrowthGlobal1X128() external view returns (uint256);

  /// @notice The amounts of token0 and token1 that are owed to the protocol
  /// @dev Protocol fees will never exceed uint128 max in either token
  function protocolFees() external view returns (uint128 token0, uint128 token1);

  /// @notice The currently in range liquidity available to the pool
  /// @dev This value has no relationship to the total liquidity across all ticks
  function liquidity() external view returns (uint128);

  /// @notice The currently in range derived liquidity available to the pool
  /// @dev This value has no relationship to the total liquidity across all ticks
  function boostedLiquidity() external view returns (uint128);

  /// @notice Get the boost information for a specific position at a period
  /// @return boostAmount the amount of boost this position has for this period,
  /// veNFTAmount the amount of veNFTs attached to this position for this period,
  /// secondsDebtX96 used to account for changes in the deposit amount during the period
  /// boostedSecondsDebtX96 used to account for changes in the boostAmount and veNFT locked during the period,
  function boostInfos(uint256 period, bytes32 key)
    external
    view
    returns (uint128 boostAmount, int128 veNFTAmount, int256 secondsDebtX96, int256 boostedSecondsDebtX96);

  /// @notice Look up information about a specific tick in the pool
  /// @param tick The tick to look up
  /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
  /// tick upper,
  /// liquidityNet how much liquidity changes when the pool price crosses the tick,
  /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
  /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
  /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
  /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current
  /// tick,
  /// secondsOutside the seconds spent on the other side of the tick from the current tick,
  /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to
  /// false.
  /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
  /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
  /// a specific position.
  function ticks(int24 tick)
    external
    view
    returns (
      uint128 liquidityGross,
      int128 liquidityNet,
      uint128 boostedLiquidityGross,
      int128 boostedLiquidityNet,
      uint256 feeGrowthOutside0X128,
      uint256 feeGrowthOutside1X128,
      int56 tickCumulativeOutside,
      uint160 secondsPerLiquidityOutsideX128,
      uint32 secondsOutside,
      bool initialized
    );

  /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
  function tickBitmap(int16 wordPosition) external view returns (uint256);

  /// @notice Returns the information about a position by the position's key
  /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
  /// @return liquidity The amount of liquidity in the position,
  /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
  /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
  /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
  /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
  /// @return attachedVeNFTId the veNFT tokenId attached to the position
  function positions(bytes32 key)
    external
    view
    returns (
      uint128 liquidity,
      uint256 feeGrowthInside0LastX128,
      uint256 feeGrowthInside1LastX128,
      uint128 tokensOwed0,
      uint128 tokensOwed1,
      uint256 attachedVeNFTId
    );

  /// @notice Returns a period's total boost amount and total veNFT attached
  /// @param period Period timestamp
  /// @return totalBoostAmount The total amount of boost this period has,
  /// @return totalVeNFTAmount The total amount of veNFTs attached to this period
  function boostInfos(uint256 period) external view returns (uint128 totalBoostAmount, int128 totalVeNFTAmount);

  /// @notice Get the period seconds debt of a specific position
  /// @param period the period number
  /// @param recipient recipient address
  /// @param index position index
  /// @param tickLower lower bound of range
  /// @param tickUpper upper bound of range
  /// @return secondsDebtX96 seconds the position was not in range for the period
  /// @return boostedSecondsDebtX96 boosted seconds the period
  function positionPeriodDebt(uint256 period, address recipient, uint256 index, int24 tickLower, int24 tickUpper)
    external
    view
    returns (int256 secondsDebtX96, int256 boostedSecondsDebtX96);

  /// @notice get the period seconds in range of a specific position
  /// @param period the period number
  /// @param owner owner address
  /// @param index position index
  /// @param tickLower lower bound of range
  /// @param tickUpper upper bound of range
  /// @return periodSecondsInsideX96 seconds the position was not in range for the period
  /// @return periodBoostedSecondsInsideX96 boosted seconds the period
  function positionPeriodSecondsInRange(uint256 period, address owner, uint256 index, int24 tickLower, int24 tickUpper)
    external
    view
    returns (uint256 periodSecondsInsideX96, uint256 periodBoostedSecondsInsideX96);

  /// @notice Returns data about a specific observation index
  /// @param index The element of the observations array to fetch
  /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
  /// ago, rather than at a specific index in the array.
  /// @return blockTimestamp The timestamp of the observation,
  /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation
  /// timestamp,
  /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the
  /// observation timestamp,
  /// @return initialized whether the observation has been initialized and the values are safe to use
  function observations(uint256 index)
    external
    view
    returns (
      uint32 blockTimestamp,
      int56 tickCumulative,
      uint160 secondsPerLiquidityCumulativeX128,
      bool initialized,
      uint160 secondsPerBoostedLiquidityPeriodX128
    );
}

// SPDX-License-Identifier: AGPL-3.0-or-later

// ▗▖   ▗▞▀▚▖█ ▄ ▗▞▀▚▖▄   ▄ ▗▞▀▚▖
// ▐▌   ▐▛▀▀▘█ ▄ ▐▛▀▀▘█   █ ▐▛▀▀▘
// ▐▛▀▚▖▝▚▄▄▖█ █ ▝▚▄▄▖ ▀▄▀  ▝▚▄▄▖
// ▐▙▄▞▘     █ █
// ▄ ▄▄▄▄
// ▄ █   █
// █ █   █
// █
//  ▄▄▄  ▄▄▄  ▄▄▄▄  ▗▄▄▄▖▗▄▄▄▖▗▖ ▗▖▄ ▄▄▄▄
// ▀▄▄  █   █ █ █ █ ▐▌     █  ▐▌ ▐▌▄ █   █
// ▄▄▄▀ ▀▄▄▀ █   █ ▐▛▀▀▘  █  ▐▛▀▜▌█ █   █
//                  ▐▙▄▄▖  █  ▐▌ ▐▌█     ▗▄▖
//                                      ▐▌ ▐▌
//                                       ▝▀▜▌
//                                      ▐▙▄▞▘

// Website: https://something.fun

pragma solidity ^0.8.0;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {IReferralSystem} from "contracts/interfaces/IReferralSystem.sol";

/// @title ReferralRewards
/// @notice Contract for managing referral reward distribution using merkle trees
/// @dev Distributes trading fee rewards to referrers (split between layer 1 and layer 2)
/// @dev Reward amounts are calculated off-chain based on actual fees collected
contract ReferralRewards is Ownable, AccessControl, ReentrancyGuard, Pausable {
  using SafeERC20 for IERC20;

  // Custom errors for gas optimization
  error UnauthorizedAccess();
  error InvalidAmount();
  error AlreadyClaimed();
  error InvalidMerkleProof();
  error BatchTooLarge();
  error ProofTooLong();
  error InvalidAddress();
  error OverflowDetected();

  /// @notice Referral reward claim data
  /// @param user Address of the user claiming rewards
  /// @param token Address of the token being claimed
  /// @param amount Amount of rewards to claim for this token
  /// @param merkleProof Merkle proof for verification
  struct ClaimRewardsInput {
    address user;
    address token;
    uint256 amount;
    bytes32[] merkleProof;
  }

  // Constants for security and gas optimization
  uint256 public MAX_BATCH_SIZE;
  uint256 public constant MAX_MERKLE_PROOF_LENGTH = 32;
  uint256 public constant MIN_CLAIM_AMOUNT = 1e12; // 0.000001 tokens
  uint256 public constant MAX_CLAIM_AMOUNT = type(uint128).max;

  // Access control roles
  bytes32 public constant MERKLE_SERVER_ROLE = keccak256("MERKLE_SERVER_ROLE");
  bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE");

  // Storage mappings
  mapping(address => mapping(address => uint256)) public userTokenClaimedRewards; // user => token => claimed amount
  mapping(address => uint256) public userLastClaimTimestamp;

  // State variables
  IReferralSystem public referralSystem;
  IERC20 public rewardToken;
  address public treasury;
  bytes32 public merkleRoot;
  uint256 public lastMerkleUpdate;

  // Enhanced events
  event MerkleRootUpdated(bytes32 indexed newMerkleRoot, uint256 timestamp);
  
  event RewardsClaimed(
    address indexed user,
    address indexed token,
    uint256 amount,
    uint256 timestamp
  );
  
  event BatchRewardsClaimed(
    address indexed user,
    uint256 totalAmount,
    uint256 claimCount,
    uint256 timestamp
  );
  
  event TreasuryUpdated(address indexed newTreasury);

  constructor(
    address _referralSystem,
    address _rewardToken,
    address _treasury,
    uint256 _maxBatchSize
  ) Ownable(msg.sender) {
    if (_referralSystem == address(0) || _rewardToken == address(0) || _treasury == address(0)) {
      revert InvalidAddress();
    }

    referralSystem = IReferralSystem(_referralSystem);
    rewardToken = IERC20(_rewardToken);
    treasury = _treasury;
    MAX_BATCH_SIZE = _maxBatchSize;

    // Set up roles
    _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    _grantRole(MERKLE_SERVER_ROLE, msg.sender);
    _grantRole(REWARD_DISTRIBUTOR_ROLE, msg.sender);
  }

  /// @notice Updates the Merkle root for reward distribution
  /// @param _merkleRoot The new Merkle root containing all claimable rewards
  function updateMerkleRoot(bytes32 _merkleRoot) external onlyRole(MERKLE_SERVER_ROLE) whenNotPaused {
    if (_merkleRoot == bytes32(0)) revert InvalidAddress();
    
    merkleRoot = _merkleRoot;
    lastMerkleUpdate = block.timestamp;
    
    emit MerkleRootUpdated(_merkleRoot, block.timestamp);
  }

  /// @notice Claims rewards with comprehensive security checks
  /// @dev Only callable by an authorized distributor (e.g., Launchpad) with REWARD_DISTRIBUTOR_ROLE
  /// @param input Claim input containing user, amount, and proof
  function claimRewards(ClaimRewardsInput calldata input) external nonReentrant whenNotPaused {
    _validateClaimInput(input);
    _processClaim(input);
  }

  /// @notice Batch claims rewards with DoS protection
  /// @dev Only callable by an authorized distributor (e.g., Launchpad) with REWARD_DISTRIBUTOR_ROLE
  /// @param inputs Array of claim inputs
  function batchClaimRewards(ClaimRewardsInput[] calldata inputs) external nonReentrant whenNotPaused {
    if (inputs.length == 0 || inputs.length > MAX_BATCH_SIZE) revert BatchTooLarge();

    uint256 totalAmount = 0;

    for (uint256 i = 0; i < inputs.length; ) {
      ClaimRewardsInput calldata input = inputs[i];
      _validateClaimInput(input);

      // Accumulate total for overflow check
      uint256 newTotal = totalAmount + input.amount;
      if (newTotal < totalAmount) revert OverflowDetected();
      totalAmount = newTotal;

      _processClaim(input);

      unchecked { ++i; }
    }

    emit BatchRewardsClaimed(msg.sender, totalAmount, inputs.length, block.timestamp);
  }

  /// @notice Internal function to validate claim input
  function _validateClaimInput(ClaimRewardsInput calldata input) internal view {
    if (input.user == address(0)) revert InvalidAddress();
    if (input.token == address(0)) revert InvalidAddress();
    if (input.amount == 0) revert InvalidAmount();
    if (input.amount < MIN_CLAIM_AMOUNT || input.amount > MAX_CLAIM_AMOUNT) revert InvalidAmount();
    if (input.merkleProof.length == 0 || input.merkleProof.length > MAX_MERKLE_PROOF_LENGTH) {
      revert ProofTooLong();
    }
    if (merkleRoot == bytes32(0)) revert InvalidMerkleProof();
  }

  /// @notice Internal function to process a claim
  function _processClaim(ClaimRewardsInput calldata input) internal {
    // Create leaf hash: keccak256(user, token, totalClaimable)
    // Note: totalClaimable is the cumulative amount the user can claim for this specific token
    bytes32 leaf = keccak256(abi.encodePacked(
      input.user,
      input.token,
      input.amount  // This is the total claimable amount for this user for this token
    ));

    // Verify merkle proof
    if (!MerkleProof.verify(input.merkleProof, merkleRoot, leaf)) {
      revert InvalidMerkleProof();
    }

    // Calculate how much is actually claimable (total - already claimed for this token)
    uint256 alreadyClaimed = userTokenClaimedRewards[input.user][input.token];
    if (input.amount <= alreadyClaimed) revert AlreadyClaimed();
    
    uint256 claimableAmount = input.amount - alreadyClaimed;

    // Update user statistics with overflow protection
    uint256 newUserTokenTotal = userTokenClaimedRewards[input.user][input.token] + claimableAmount;
    if (newUserTokenTotal < userTokenClaimedRewards[input.user][input.token]) revert OverflowDetected();

    userTokenClaimedRewards[input.user][input.token] = newUserTokenTotal;
    userLastClaimTimestamp[input.user] = block.timestamp;

    // Record claimed rewards in the referral system
    referralSystem.recordClaimedRewards(input.user, input.token, claimableAmount);

    // Transfer rewards (in the specified token)
    IERC20(input.token).safeTransfer(input.user, claimableAmount);

    emit RewardsClaimed(input.user, input.token, claimableAmount, block.timestamp);
  }

  /// @notice Get total claimed rewards for a user for a specific token
  /// @param user Address of the user
  /// @param token Address of the token
  /// @return claimed Total amount of rewards claimed by the user for this token
  function getClaimedRewards(address user, address token) external view returns (uint256) {
    return userTokenClaimedRewards[user][token];
  }

  /// @notice Get last claim timestamp for a user
  /// @param user Address of the user
  /// @return timestamp When the user last claimed rewards
  function getLastClaimTimestamp(address user) external view returns (uint256) {
    return userLastClaimTimestamp[user];
  }

  /// @notice Get the current Merkle root
  /// @return root The current Merkle root
  function getMerkleRoot() external view returns (bytes32) {
    return merkleRoot;
  }

  /// @notice Get when the Merkle root was last updated
  /// @return timestamp Last update time
  function getLastMerkleUpdate() external view returns (uint256) {
    return lastMerkleUpdate;
  }

  // Admin functions with proper access control

  /// @notice Set treasury address
  /// @param _treasury New treasury address
  function setTreasury(address _treasury) external onlyRole(DEFAULT_ADMIN_ROLE) {
    if (_treasury == address(0)) revert InvalidAddress();
    treasury = _treasury;
    emit TreasuryUpdated(_treasury);
  }

  /// @notice Emergency pause all operations
  function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
    _pause();
  }

  /// @notice Resume all operations
  function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
    _unpause();
  }

  /// @notice Emergency withdraw tokens
  /// @param token Token to withdraw
  /// @param amount Amount to withdraw
  function emergencyWithdraw(IERC20 token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
    token.safeTransfer(msg.sender, amount);
  }

  /// @notice Grant merkle server role
  /// @param server Address to grant role to
  function grantMerkleServerRole(address server) external onlyRole(DEFAULT_ADMIN_ROLE) {
    if (server == address(0)) revert InvalidAddress();
    _grantRole(MERKLE_SERVER_ROLE, server);
  }

  /// @notice Revoke merkle server role
  /// @param server Address to revoke role from
  function revokeMerkleServerRole(address server) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _revokeRole(MERKLE_SERVER_ROLE, server);
  }

  /// @notice Get treasury address
  /// @return treasury The treasury address
  function getTreasury() external view returns (address) {
    return treasury;
  }

  // Required by AccessControl
  function supportsInterface(bytes4 interfaceId) public view override(AccessControl) returns (bool) {
    return super.supportsInterface(interfaceId);
  }
}

Settings
{
  "viaIR": true,
  "optimizer": {
    "enabled": true,
    "runs": 2000
  },
  "evmVersion": "paris",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_weth","type":"address"},{"internalType":"address","name":"_openocean","type":"address"},{"internalType":"address","name":"_launchpad","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"received","type":"uint256"},{"internalType":"uint256","name":"minimum","type":"uint256"}],"name":"InsufficientOutputAmount","type":"error"},{"inputs":[],"name":"InvalidETHAmount","type":"error"},{"inputs":[],"name":"InvalidTokenIn","type":"error"},{"inputs":[],"name":"NoFundingTokensReceived","type":"error"},{"inputs":[],"name":"OpenOceanCallFailed","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"TokenAmountInMustBeZero","type":"error"},{"inputs":[],"name":"adapter","outputs":[{"internalType":"contract ICLMMAdapter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"tokenAmountIn","type":"uint256"},{"internalType":"contract IERC20","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minReturnAmount","type":"uint256"},{"internalType":"uint256","name":"guaranteedAmount","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"bytes","name":"permit","type":"bytes"},{"components":[{"internalType":"uint256","name":"target","type":"uint256"},{"internalType":"uint256","name":"gasLimit","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IOpenOceanCaller.CallDescription[]","name":"calls","type":"tuple[]"}],"internalType":"struct IUIHelper.OpenOceanParams","name":"_openOceanParams","type":"tuple"},{"internalType":"contract IERC20","name":"_tokenOut","type":"address"},{"internalType":"uint256","name":"_minAmountOut","type":"uint256"},{"internalType":"uint160","name":"_sqrtPriceLimitX96","type":"uint160"},{"internalType":"bytes8","name":"_referralCode","type":"bytes8"}],"name":"buyWithExactInputWithOpenOcean","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"tokenAmountIn","type":"uint256"},{"internalType":"contract IERC20","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minReturnAmount","type":"uint256"},{"internalType":"uint256","name":"guaranteedAmount","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"bytes","name":"permit","type":"bytes"},{"components":[{"internalType":"uint256","name":"target","type":"uint256"},{"internalType":"uint256","name":"gasLimit","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IOpenOceanCaller.CallDescription[]","name":"calls","type":"tuple[]"}],"internalType":"struct IUIHelper.OpenOceanParams","name":"_openOceanParams","type":"tuple"},{"internalType":"contract IERC20","name":"_tokenOut","type":"address"},{"internalType":"uint256","name":"_minAmountOut","type":"uint256"},{"internalType":"uint160","name":"_sqrtPriceLimitX96","type":"uint160"},{"internalType":"bytes8","name":"_referralCode","type":"bytes8"}],"name":"buyWithExactInputWithOpenOceanAndSwapFees","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"tokenAmountIn","type":"uint256"},{"internalType":"contract IERC20","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minReturnAmount","type":"uint256"},{"internalType":"uint256","name":"guaranteedAmount","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"bytes","name":"permit","type":"bytes"},{"components":[{"internalType":"uint256","name":"target","type":"uint256"},{"internalType":"uint256","name":"gasLimit","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IOpenOceanCaller.CallDescription[]","name":"calls","type":"tuple[]"}],"internalType":"struct IUIHelper.OpenOceanParams","name":"_openOceanParams","type":"tuple"},{"components":[{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"string","name":"metadata","type":"string"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"}],"internalType":"struct ITokenLaunchpad.CreateParams","name":"_params","type":"tuple"},{"internalType":"address","name":"_expected","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes8","name":"_creatorReferralCode","type":"bytes8"}],"name":"createAndBuy","outputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"received","type":"uint256"},{"internalType":"uint256","name":"swapped","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"fundingToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"launchpad","outputs":[{"internalType":"contract ITokenLaunchpad","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"target","type":"uint256"},{"internalType":"uint256","name":"gasLimit","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IOpenOceanCaller.CallDescription[]","name":"desc","type":"tuple[]"}],"name":"makeCalls","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"openOcean","outputs":[{"internalType":"contract IOpenOceanExchange","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referralRewards","outputs":[{"internalType":"contract ReferralRewards","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referralSystem","outputs":[{"internalType":"contract IReferralSystem","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"tokenAmountIn","type":"uint256"},{"internalType":"contract IERC20","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minReturnAmount","type":"uint256"},{"internalType":"uint256","name":"guaranteedAmount","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"bytes","name":"permit","type":"bytes"},{"components":[{"internalType":"uint256","name":"target","type":"uint256"},{"internalType":"uint256","name":"gasLimit","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IOpenOceanCaller.CallDescription[]","name":"calls","type":"tuple[]"}],"internalType":"struct IUIHelper.OpenOceanParams","name":"_openOceanParams","type":"tuple"},{"internalType":"contract IERC20","name":"_tokenIn","type":"address"},{"internalType":"uint256","name":"_amountToSell","type":"uint256"},{"internalType":"uint160","name":"_sqrtPriceLimitX96","type":"uint160"},{"internalType":"bytes8","name":"_referralCode","type":"bytes8"}],"name":"sellWithExactInputWithOpenOcean","outputs":[{"internalType":"uint256","name":"amountSwapOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"tokenAmountIn","type":"uint256"},{"internalType":"contract IERC20","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"minReturnAmount","type":"uint256"},{"internalType":"uint256","name":"guaranteedAmount","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"bytes","name":"permit","type":"bytes"},{"components":[{"internalType":"uint256","name":"target","type":"uint256"},{"internalType":"uint256","name":"gasLimit","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IOpenOceanCaller.CallDescription[]","name":"calls","type":"tuple[]"}],"internalType":"struct IUIHelper.OpenOceanParams","name":"_openOceanParams","type":"tuple"},{"internalType":"contract IERC20","name":"_tokenIn","type":"address"},{"internalType":"uint256","name":"_amountToSell","type":"uint256"},{"internalType":"uint160","name":"_sqrtPriceLimitX96","type":"uint160"},{"internalType":"bytes8","name":"_referralCode","type":"bytes8"}],"name":"sellWithExactInputWithOpenOceanAndSwapFees","outputs":[{"internalType":"uint256","name":"amountSwapOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"weth","outputs":[{"internalType":"contract IWETH9","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

0x61014080604052346102f657606081612f2980380380916100208285610387565b8339810103126102f6576020816100386004936103c0565b9061005060406100498584016103c0565b92016103c0565b60016000556001600160a01b0392831660805290821660a0521660c081905260405162fab73f60e21b815292839182905afa9081156102b857600091610345575b5060e05260c0516040516378065f2760e01b815290602090829060049082906001600160a01b03165afa9081156102b857600091610303575b506101005260c05160405163825662ad60e01b815290602090829060049082906001600160a01b03165afa9081156102b8576000916102c4575b506001600160a01b03908116610120526101005160e0516101299290811691166103d4565b6101005160c051610146916001600160a01b0391821691166103d4565b60c051604051632813a1db60e21b815290602090829060049082906001600160a01b03165afa9081156102b85760009161026f575b50600180546001600160a01b0319166001600160a01b0392909216919091179055604051612a3c90816104ed823960805181611b87015260a051818181610b6801528181611b430152818161245201526125d5015260c0518181816102a80152818161085401528181610f05015281816118990152611c98015260e05181818161080e01528181610ebf01528181611324015281816117bf01528181611c5501526127700152610100518181816102480152818161068801528181610d380152818161126201528181611680015281816116fd0152818161264201526126850152610120518181816111e601526126b60152f35b6020813d6020116102b0575b8161028860209383610387565b810103126102ac5751906001600160a01b03821682036102a957503861017b565b80fd5b5080fd5b3d915061027b565b6040513d6000823e3d90fd5b90506020813d6020116102fb575b816102df60209383610387565b810103126102f6576102f0906103c0565b38610104565b600080fd5b3d91506102d2565b6020813d60201161033d575b8161031c60209383610387565b810103126102ac5751906001600160a01b03821682036102a95750386100ca565b3d915061030f565b6020813d60201161037f575b8161035e60209383610387565b810103126102ac5751906001600160a01b03821682036102a9575038610091565b3d9150610351565b601f909101601f19168101906001600160401b038211908210176103aa57604052565b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b03821682036102f657565b60405190602060008184019463095ea7b360e01b865260018060a01b031694856024860152811960448601526044855261040f606486610387565b84519082855af16000513d8261046c575b50501561042c57505050565b61046561046a936040519063095ea7b360e01b60208301526024820152600060448201526044815261045f606482610387565b82610491565b610491565b565b90915061048957506001600160a01b0381163b15155b3880610420565b600114610482565b906000602091828151910182855af1156102b8576000513d6104e357506001600160a01b0381163b155b6104c25750565b635274afe760e01b60009081526001600160a01b0391909116600452602490fd5b600114156104bb56fe608080604052600436101561001d575b50361561001b57600080fd5b005b600090813560e01c90816302669b5214611c795750806303eadcfc14611c35578063150b7a0214611bab5780633fc8cef314611b6757806370a0448514611b23578063770fe9e6146116a457806378065f2714611660578063971afc4f1461120a578063995deaba146111c65780639dd7023a14610ce3578063a04e876c14610cbc578063a8920d2b14610b30578063f1229b4f146106315763f792d3f30361000f5760a060031936011261062e5760043567ffffffffffffffff8111610483576100ec903690600401611eaa565b6024359167ffffffffffffffff831161062e576080600319843603011261062e576040519061011a82611d2e565b83600401358252602484013567ffffffffffffffff8111610483576101459060043691870101611d89565b9360208301948552604481013567ffffffffffffffff8111610423576101719060043691840101611d89565b9060408401918252606481013567ffffffffffffffff81116104325761019c91369101600401611d89565b60608401908152604435956001600160a01b038716809703610432576084359477ffffffffffffffffffffffffffffffffffffffffffffffff19861680960361062c576101e76120c8565b86516001600160a01b0316806105bc575084975b87516001600160a01b03168061054d5750855b60408901516001600160a01b0316806104de5750865b604051916370a0823160e01b83523060048401526020836024816001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165afa9283156104d357899361049a575b506040519b6102868d611cfc565b8c5260208c015260408b015260608a01528560808a01526102a68861226f565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031696879460405196879586957f06c2a3c200000000000000000000000000000000000000000000000000000000875260048701608090525160848701525160a4860160809052610104860161032391612087565b9051908581036083190160c487015261033b91612087565b9051908481036083190160e486015261035391612087565b916024840152606435604484015260648301520381855a94606095f192831561048f57829083928495610436575b50803b15610432576040517f42842e0e000000000000000000000000000000000000000000000000000000008152306004820152336024820152604481018690529084908290606490829084905af180156104275761040e575b506080956001600160a01b036103f392168096612602565b60018255604051938452602084015260408301526060820152f35b610419848092611d4a565b61042357386103db565b8280fd5b6040513d86823e3d90fd5b8380fd5b92509350506060813d606011610487575b8161045460609383611d4a565b81010312610483578051906001600160a01b038216820361042357604060208201519101519190919338610381565b5080fd5b3d9150610447565b6040513d84823e3d90fd5b9092506020813d6020116104cb575b816104b660209383611d4a565b810103126104c657519138610278565b600080fd5b3d91506104a9565b6040513d8b823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa908115610542578891610510575b50610224565b90506020813d60201161053a575b8161052b60209383611d4a565b810103126104c657513861050a565b3d915061051e565b6040513d8a823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b157879161057f575b5061020e565b90506020813d6020116105a9575b8161059a60209383611d4a565b810103126104c6575138610579565b3d915061058d565b6040513d89823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa9081156106215786916105ef575b50976101fb565b90506020813d602011610619575b8161060a60209383611d4a565b810103126104c65751386105e8565b3d91506105fd565b6040513d88823e3d90fd5b845b80fd5b5061063b36611f7b565b91949390926106486120c8565b81516001600160a01b031680610acb575084915b80516001600160a01b031680610a66575085935b60408201516001600160a01b031680610a025750865b7f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b038216604051906370a0823160e01b8252306004830152602082602481845afa9182156109f7578b926109c3575b506040516370a0823160e01b81523060048201526001600160a01b038816996020826024818e5afa9182156109b8578d92610981575b5090602494602093926040519b6107298d611cfc565b8c52848c015260408b015260608a0193845260808a01526107498761226f565b604051938480926370a0823160e01b82523060048301525afa918215610976578a92610942575b50805182111561091a57899a9261079260209593610801939c9b9c519061200a565b604051633df6f17160e01b81526001600160a01b039283166004820152828916602482015260448101919091526064810194909452909916608483015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48201523360c4820152968790819060e4820190565b0381886001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af195861561090f5785966108d2575b509061084a9291612602565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016803b1561042357602483926040519485938492630ad0753560e11b845260048401525af180156108c7576108b2575b50600160209255604051908152f35b6108bd838092611d4a565b61048357386108a3565b6040513d85823e3d90fd5b9291945094506020823d602011610907575b816108f160209383611d4a565b810103126104c65790519385939061084a61083e565b3d91506108e4565b6040513d87823e3d90fd5b60048a7f400b91a1000000000000000000000000000000000000000000000000000000008152fd5b9091506020813d60201161096e575b8161095e60209383611d4a565b810103126104c657519038610770565b3d9150610951565b6040513d8c823e3d90fd5b9291506020833d6020116109b0575b8161099d60209383611d4a565b810103126104c657915190916024610713565b3d9150610990565b6040513d8f823e3d90fd5b9091506020813d6020116109ef575b816109df60209383611d4a565b810103126104c6575190386106dd565b3d91506109d2565b6040513d8d823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa908115610542578891610a34575b50610686565b90506020813d602011610a5e575b81610a4f60209383611d4a565b810103126104c6575138610a2e565b3d9150610a42565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b1578791610a99575b5093610670565b90506020813d602011610ac3575b81610ab460209383611d4a565b810103126104c6575138610a92565b3d9150610aa7565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610621578691610afe575b509161065c565b90506020813d602011610b28575b81610b1960209383611d4a565b810103126104c6575138610af7565b3d9150610b0c565b50602060031936011261062e5760043567ffffffffffffffff811161048357610b5d903690600401611dce565b906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163303610c5e57805b8251811015610c5a5781806001600160a01b03610bad848761202d565b5151166020610bbc858861202d565b5101516040610bcb868961202d565b5101516060610bda878a61202d565b5101519260208451940192f1610bee612057565b5015610bfc57600101610b90565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600e60248201527f73756263616c6c206661696c65640000000000000000000000000000000000006044820152fd5b5080f35b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f4f6e6c7920726f757465722063616e2063616c6c0000000000000000000000006044820152fd5b503461062e578060031936011261062e5760206001600160a01b0360015416604051908152f35b50610ced36611f7b565b919093610cf86120c8565b80516001600160a01b031680611161575085915b81516001600160a01b0316806110fc575086935b60408301516001600160a01b0316806110985750875b7f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b038216604051906370a0823160e01b8252306004830152602082602481845afa91821561108d578c92611059575b506040516370a0823160e01b81523060048201526001600160a01b038b16998d916020816024818f5afa92831561104d5792611016575b5090602494602093926040519b610dda8d611cfc565b8c52848c015260408b015260608a0193845260808a0152610dfa8861226f565b604051938480926370a0823160e01b82523060048301525afa9182156109f7578b92610fe2575b508051821115610fba578a9796959492610e4360209593610eb293519061200a565b604051633df6f17160e01b81526001600160a01b039283166004820152828c16602482015260448101919091526064810194909452909916608483015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48201523360c4820152968790819060e4820190565b0381876001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af1958615610427578496610f81575b509084610efb92612602565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016803b1561042357602483926040519485938492630ad0753560e11b845260048401525af1801561042757610f6c575b50602092610f63600192612670565b55604051908152f35b610f77848092611d4a565b6104235738610f54565b91935094506020813d602011610fb2575b81610f9f60209383611d4a565b810103126104c657519385929084610eef565b3d9150610f92565b60048b7f400b91a1000000000000000000000000000000000000000000000000000000008152fd5b9091506020813d60201161100e575b81610ffe60209383611d4a565b810103126104c657519038610e21565b3d9150610ff1565b9291506020833d602011611045575b8161103260209383611d4a565b810103126104c657915190916024610dc4565b3d9150611025565b604051903d90823e3d90fd5b9091506020813d602011611085575b8161107560209383611d4a565b810103126104c657519038610d8d565b3d9150611068565b6040513d8e823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa9081156104d35789916110ca575b50610d36565b90506020813d6020116110f4575b816110e560209383611d4a565b810103126104c65751386110c4565b3d91506110d8565b6020602491604051928380926370a0823160e01b82523060048301525afa90811561054257889161112f575b5093610d20565b90506020813d602011611159575b8161114a60209383611d4a565b810103126104c6575138611128565b3d915061113d565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b1578791611194575b5091610d0c565b90506020813d6020116111be575b816111af60209383611d4a565b810103126104c657513861118d565b3d91506111a2565b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b508061121536611f7b565b909492936112216120c8565b80516001600160a01b0316806115f8575083915b81516001600160a01b031680611590575084935b60408301516001600160a01b031680611528575085905b7f0000000000000000000000000000000000000000000000000000000000000000926001600160a01b03841692604051906370a0823160e01b8252306004830152602082602481885afa918215610976578a926114f1575b50906024916001600160a01b038c169960208b604051958680926370a0823160e01b82523060048301525afa93841561108d578c946114ba575b50604051996113008b611cfc565b8a5260208a01526040890152606088015260808701526113228230338c612103565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691611357838b612167565b602086018051604051633df6f17160e01b81526001600160a01b038d811660048301529788166024820152604481019390935260648301529a909416608485015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48401523360c48401529197918860e481895a94602095f197881561062157869861147f575b5090829161010088940151516113f8575b505090610efb9291612602565b9180949596506001600160a01b03919350511603611457575161142f578592918482611426610efb9461226f565b909192386113eb565b6004867f4168c773000000000000000000000000000000000000000000000000000000008152fd5b6004877fd70f29d2000000000000000000000000000000000000000000000000000000008152fd5b9291955096506020823d6020116114b2575b8161149e60209383611d4a565b810103126104c657905195879490866113da565b3d9150611491565b9b50925060208b3d6020116114e9575b816114d760209383611d4a565b810103126104c6578d9a5192386112f2565b3d91506114ca565b915098506020813d602011611520575b8161150e60209383611d4a565b810103126104c657518b9860246112b8565b3d9150611501565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b157879161155b575b5090611260565b9650506020863d602011611588575b8161157760209383611d4a565b810103126104c65788955138611554565b3d915061156a565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156106215786916115c3575b5093611249565b9550506020853d6020116115f0575b816115df60209383611d4a565b810103126104c657879451386115bc565b3d91506115d2565b6020602491604051928380926370a0823160e01b82523060048301525afa90811561090f57859161162b575b5091611235565b9450506020843d602011611658575b8161164760209383611d4a565b810103126104c65786935138611624565b3d915061163a565b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b50806116af36611f7b565b91929094936116bc6120c8565b80516001600160a01b031680611aba575084925b81516001600160a01b031680611a55575085945b60408301516001600160a01b0316806119ec575086905b7f0000000000000000000000000000000000000000000000000000000000000000926001600160a01b03841692604051906370a0823160e01b8252306004830152602082602481885afa9081156109f7578b916119b3575b6040516370a0823160e01b81523060048201526001600160a01b038a169b9093506020846024818f5afa9384156109b8578d8095611979575b50506040519a61179b8c611cfc565b8b5260208b015260408a0152606089015260808801526117bd82303389612103565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316916117f28388612167565b602086018051604051633df6f17160e01b81526001600160a01b038a811660048301529788166024820152604481019390935260648301529a909416608485015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48401523360c48401529197918860e4818a5a94602095f19788156105b1578798611941575b506101008301515161190b575b50509061188f9291612602565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016803b1561042357602483926040519485938492630ad0753560e11b845260048401525af180156108c75792600191816020956118fb575b505055604051908152f35b61190491611d4a565b38816118f0565b909192939495506001600160a01b0383511603611457575161142f579161188f918361193888969561226f565b90919238611882565b9097506020813d602011611971575b8161195d60209383611d4a565b8101031261196d57519638611875565b8680fd5b3d9150611950565b819295509060209182903d84116119ab575b6119958284611d4a565b50810103126119a7575192388d61178c565b8c80fd5b3d915061198b565b90506020823d6020116119e4575b816119ce60209383611d4a565b810103126119e0576024915190611753565b8a80fd5b3d91506119c1565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610542578891611a1f575b50906116fb565b90506020813d602011611a4d575b81611a3a60209383611d4a565b81010312611a49575138611a18565b8780fd5b3d9150611a2d565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b1578791611a88575b50946116e4565b90506020813d602011611ab2575b81611aa360209383611d4a565b8101031261196d575138611a81565b3d9150611a96565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610621578691611aed575b50926116d0565b90506020813d602011611b1b575b81611b0860209383611d4a565b81010312611b17575138611ae6565b8580fd5b3d9150611afb565b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b503461062e57608060031936011261062e57611bc5611cbc565b50611bce611cd2565b5060643567ffffffffffffffff8111610483573660238201121561048357806004013567ffffffffffffffff8111610423573691016024011161062e5760206040517f150b7a02000000000000000000000000000000000000000000000000000000008152f35b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b9050346104835781600319360112610483576020906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b600435906001600160a01b03821682036104c657565b602435906001600160a01b03821682036104c657565b35906001600160a01b03821682036104c657565b60a0810190811067ffffffffffffffff821117611d1857604052565b634e487b7160e01b600052604160045260246000fd5b6080810190811067ffffffffffffffff821117611d1857604052565b90601f601f19910116810190811067ffffffffffffffff821117611d1857604052565b67ffffffffffffffff8111611d1857601f01601f191660200190565b81601f820112156104c657602081359101611da382611d6d565b92611db16040519485611d4a565b828452828201116104c65781600092602092838601378301015290565b9080601f830112156104c65781359167ffffffffffffffff8311611d18578260051b60405193611e016020830186611d4a565b8452602080850191830101918383116104c65760208101915b838310611e2957505050505090565b823567ffffffffffffffff81116104c6578201906080601f1983880301126104c65760405190611e5882611d2e565b60208301358252604083013560208301526060830135604083015260808301359167ffffffffffffffff83116104c657611e9a88602080969581960101611d89565b6060820152815201920191611e1a565b9190610120838203126104c65760405190610120820182811067ffffffffffffffff821117611d18576040528193611ee181611ce8565b835260208101356020840152611ef960408201611ce8565b6040840152606081013560608401526080810135608084015260a081013560a0840152611f2860c08201611ce8565b60c084015260e081013567ffffffffffffffff81116104c65782611f4d918301611d89565b60e08401526101008101359167ffffffffffffffff83116104c65761010092611f769201611dce565b910152565b60a06003198201126104c6576004359067ffffffffffffffff82116104c657611fa691600401611eaa565b906024356001600160a01b03811681036104c65790604435906064356001600160a01b03811681036104c6579060843577ffffffffffffffffffffffffffffffffffffffffffffffff19811681036104c65790565b908160209103126104c6575190565b9190820391821161201757565b634e487b7160e01b600052601160045260246000fd5b80518210156120415760209160051b010190565b634e487b7160e01b600052603260045260246000fd5b3d15612082573d9061206882611d6d565b916120766040519384611d4a565b82523d6000602084013e565b606090565b919082519283825260005b8481106120b3575050601f19601f8460006020809697860101520116010190565b80602080928401015182828601015201612092565b6002600054146120d9576002600055565b7f3ee5aeb50000000000000000000000000000000000000000000000000000000060005260046000fd5b6040517f23b872dd0000000000000000000000000000000000000000000000000000000060208201526001600160a01b03928316602482015292909116604483015260648083019390935291815261216591612160608483611d4a565b612866565b565b60405190602060006001600160a01b03828501957f095ea7b300000000000000000000000000000000000000000000000000000000875216948560248601527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6044860152604485526121db606486611d4a565b84519082855af16000513d8261224a575b5050156121f857505050565b61216061216593604051907f095ea7b300000000000000000000000000000000000000000000000000000000602083015260248201526000604482015260448152612244606482611d4a565b82612866565b90915061226757506001600160a01b0381163b15155b38806121ec565b600114612260565b80516001600160a01b03168061259e575060208101513403612574575b610100810180515161229c575050565b6001600160a01b03825116906001600160a01b03604084015116906020840151936060810194855160808301519060a08401519260e06001600160a01b0360c08701511695015195604051986101408a018a811067ffffffffffffffff821117611d185760409a999a9897969594939298528852602088019889526040880196308852606089019030825260808a0192835260a08a0193845260c08a0194855260e08a019586526101008a019687526101208a0197885251976040519a8b9a7f90411a32000000000000000000000000000000000000000000000000000000008c523060048d015260248c0160609052516001600160a01b031660648c0152516001600160a01b031660848b0152516001600160a01b031660a48a0152516001600160a01b031660c48901525160e4880152516101048701525161012486015251610144850152516001600160a01b031661016484015251610184830161014090526101a4830161240c91612087565b828103600319016044840152815180825260208201918160051b810160200193602001926000915b83831061251e57505050505090806020920381346001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af1600091816124ea575b506124ac577fa4532fc20000000000000000000000000000000000000000000000000000000060005260046000fd5b9051908181106124ba575050565b7fd28d3eb50000000000000000000000000000000000000000000000000000000060005260045260245260446000fd5b9091506020813d602011612516575b8161250660209383611d4a565b810103126104c65751903861247d565b3d91506124f9565b91939550919360208061256283601f198660019603018752608060608b51805184528581015186850152604081015160408501520151918160608201520190612087565b97019301930190928695949293612434565b7f242b035c0000000000000000000000000000000000000000000000000000000060005260046000fd5b6020820151806125b0575b505061228c565b6125bd9130903390612103565b6125fb6001600160a01b038251166001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690612167565b38806125a9565b6080612165936126376001600160a01b0360408195612629838251166020870151906128e3565b0151166040830151906128e3565b6126676060820151847f0000000000000000000000000000000000000000000000000000000000000000166128e3565b015191166128e3565b6001600160a01b038116906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016808314612861576001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690604051936370a0823160e01b8552600092806004870152602086602481855afa95861561042757849661282d575b50851561282557803b15610432576040517f95ccea67000000000000000000000000000000000000000000000000000000008152826004820152866024820152848160448183865af1801561090f5761280b575b5090836020949560e4936127976001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168093612167565b6040519889968795633df6f17160e01b87526004870152602486015260448501528260648501528260848501528260a485015260c48401525af190811561104d57506127e05750565b6128019060203d602011612804575b6127f98183611d4a565b810190611ffb565b50565b503d6127ef565b908461281c60209660e49594611d4a565b94509091612759565b505050505050565b9095506020813d602011612859575b8161284960209383611d4a565b8101031261043257519438612705565b3d915061283c565b505050565b906000602091828151910182855af1156128d7576000513d6128ce57506001600160a01b0381163b155b6128975750565b6001600160a01b03907f5274afe7000000000000000000000000000000000000000000000000000000006000521660045260246000fd5b60011415612890565b6040513d6000823e3d90fd5b6001600160a01b03168061294857508047116128fc5750565b6000808061290b81944761200a565b335af1612916612057565b501561291e57565b7fb12d13eb0000000000000000000000000000000000000000000000000000000060005260046000fd5b6040516370a0823160e01b8152306004820152602081602481855afa9081156128d7576000916129d4575b5082811161298057505050565b6121659261298d9161200a565b6040517fa9059cbb00000000000000000000000000000000000000000000000000000000602082015233602482015260448082019290925290815290612160606483611d4a565b906020823d6020116129fe575b816129ee60209383611d4a565b8101031261062e57505138612973565b3d91506129e156fea2646970667358221220f286ab2fa6b565f98b3e644701872b37b5ef166a186d95d72ef15ed8890f0ebb64736f6c634300081c0033000000000000000000000000e5d7c2a44ffddf6b295a15c148167daaaf5cf34f0000000000000000000000006352a56caadc4f1e25cd6c75970fa768a3304e64000000000000000000000000a7a7141b5a8d24c50c6bd65b1a6c8acde192e7a6

Deployed Bytecode

0x608080604052600436101561001d575b50361561001b57600080fd5b005b600090813560e01c90816302669b5214611c795750806303eadcfc14611c35578063150b7a0214611bab5780633fc8cef314611b6757806370a0448514611b23578063770fe9e6146116a457806378065f2714611660578063971afc4f1461120a578063995deaba146111c65780639dd7023a14610ce3578063a04e876c14610cbc578063a8920d2b14610b30578063f1229b4f146106315763f792d3f30361000f5760a060031936011261062e5760043567ffffffffffffffff8111610483576100ec903690600401611eaa565b6024359167ffffffffffffffff831161062e576080600319843603011261062e576040519061011a82611d2e565b83600401358252602484013567ffffffffffffffff8111610483576101459060043691870101611d89565b9360208301948552604481013567ffffffffffffffff8111610423576101719060043691840101611d89565b9060408401918252606481013567ffffffffffffffff81116104325761019c91369101600401611d89565b60608401908152604435956001600160a01b038716809703610432576084359477ffffffffffffffffffffffffffffffffffffffffffffffff19861680960361062c576101e76120c8565b86516001600160a01b0316806105bc575084975b87516001600160a01b03168061054d5750855b60408901516001600160a01b0316806104de5750865b604051916370a0823160e01b83523060048401526020836024816001600160a01b037f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c165afa9283156104d357899361049a575b506040519b6102868d611cfc565b8c5260208c015260408b015260608a01528560808a01526102a68861226f565b7f000000000000000000000000a7a7141b5a8d24c50c6bd65b1a6c8acde192e7a66001600160a01b031696879460405196879586957f06c2a3c200000000000000000000000000000000000000000000000000000000875260048701608090525160848701525160a4860160809052610104860161032391612087565b9051908581036083190160c487015261033b91612087565b9051908481036083190160e486015261035391612087565b916024840152606435604484015260648301520381855a94606095f192831561048f57829083928495610436575b50803b15610432576040517f42842e0e000000000000000000000000000000000000000000000000000000008152306004820152336024820152604481018690529084908290606490829084905af180156104275761040e575b506080956001600160a01b036103f392168096612602565b60018255604051938452602084015260408301526060820152f35b610419848092611d4a565b61042357386103db565b8280fd5b6040513d86823e3d90fd5b8380fd5b92509350506060813d606011610487575b8161045460609383611d4a565b81010312610483578051906001600160a01b038216820361042357604060208201519101519190919338610381565b5080fd5b3d9150610447565b6040513d84823e3d90fd5b9092506020813d6020116104cb575b816104b660209383611d4a565b810103126104c657519138610278565b600080fd5b3d91506104a9565b6040513d8b823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa908115610542578891610510575b50610224565b90506020813d60201161053a575b8161052b60209383611d4a565b810103126104c657513861050a565b3d915061051e565b6040513d8a823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b157879161057f575b5061020e565b90506020813d6020116105a9575b8161059a60209383611d4a565b810103126104c6575138610579565b3d915061058d565b6040513d89823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa9081156106215786916105ef575b50976101fb565b90506020813d602011610619575b8161060a60209383611d4a565b810103126104c65751386105e8565b3d91506105fd565b6040513d88823e3d90fd5b845b80fd5b5061063b36611f7b565b91949390926106486120c8565b81516001600160a01b031680610acb575084915b80516001600160a01b031680610a66575085935b60408201516001600160a01b031680610a025750865b7f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c906001600160a01b038216604051906370a0823160e01b8252306004830152602082602481845afa9182156109f7578b926109c3575b506040516370a0823160e01b81523060048201526001600160a01b038816996020826024818e5afa9182156109b8578d92610981575b5090602494602093926040519b6107298d611cfc565b8c52848c015260408b015260608a0193845260808a01526107498761226f565b604051938480926370a0823160e01b82523060048301525afa918215610976578a92610942575b50805182111561091a57899a9261079260209593610801939c9b9c519061200a565b604051633df6f17160e01b81526001600160a01b039283166004820152828916602482015260448101919091526064810194909452909916608483015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48201523360c4820152968790819060e4820190565b0381886001600160a01b037f000000000000000000000000735c2ad31748a515894247ef9b37036f3c9ed40b165af195861561090f5785966108d2575b509061084a9291612602565b6001600160a01b037f000000000000000000000000a7a7141b5a8d24c50c6bd65b1a6c8acde192e7a616803b1561042357602483926040519485938492630ad0753560e11b845260048401525af180156108c7576108b2575b50600160209255604051908152f35b6108bd838092611d4a565b61048357386108a3565b6040513d85823e3d90fd5b9291945094506020823d602011610907575b816108f160209383611d4a565b810103126104c65790519385939061084a61083e565b3d91506108e4565b6040513d87823e3d90fd5b60048a7f400b91a1000000000000000000000000000000000000000000000000000000008152fd5b9091506020813d60201161096e575b8161095e60209383611d4a565b810103126104c657519038610770565b3d9150610951565b6040513d8c823e3d90fd5b9291506020833d6020116109b0575b8161099d60209383611d4a565b810103126104c657915190916024610713565b3d9150610990565b6040513d8f823e3d90fd5b9091506020813d6020116109ef575b816109df60209383611d4a565b810103126104c6575190386106dd565b3d91506109d2565b6040513d8d823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa908115610542578891610a34575b50610686565b90506020813d602011610a5e575b81610a4f60209383611d4a565b810103126104c6575138610a2e565b3d9150610a42565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b1578791610a99575b5093610670565b90506020813d602011610ac3575b81610ab460209383611d4a565b810103126104c6575138610a92565b3d9150610aa7565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610621578691610afe575b509161065c565b90506020813d602011610b28575b81610b1960209383611d4a565b810103126104c6575138610af7565b3d9150610b0c565b50602060031936011261062e5760043567ffffffffffffffff811161048357610b5d903690600401611dce565b906001600160a01b037f0000000000000000000000006352a56caadc4f1e25cd6c75970fa768a3304e64163303610c5e57805b8251811015610c5a5781806001600160a01b03610bad848761202d565b5151166020610bbc858861202d565b5101516040610bcb868961202d565b5101516060610bda878a61202d565b5101519260208451940192f1610bee612057565b5015610bfc57600101610b90565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600e60248201527f73756263616c6c206661696c65640000000000000000000000000000000000006044820152fd5b5080f35b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f4f6e6c7920726f757465722063616e2063616c6c0000000000000000000000006044820152fd5b503461062e578060031936011261062e5760206001600160a01b0360015416604051908152f35b50610ced36611f7b565b919093610cf86120c8565b80516001600160a01b031680611161575085915b81516001600160a01b0316806110fc575086935b60408301516001600160a01b0316806110985750875b7f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c906001600160a01b038216604051906370a0823160e01b8252306004830152602082602481845afa91821561108d578c92611059575b506040516370a0823160e01b81523060048201526001600160a01b038b16998d916020816024818f5afa92831561104d5792611016575b5090602494602093926040519b610dda8d611cfc565b8c52848c015260408b015260608a0193845260808a0152610dfa8861226f565b604051938480926370a0823160e01b82523060048301525afa9182156109f7578b92610fe2575b508051821115610fba578a9796959492610e4360209593610eb293519061200a565b604051633df6f17160e01b81526001600160a01b039283166004820152828c16602482015260448101919091526064810194909452909916608483015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48201523360c4820152968790819060e4820190565b0381876001600160a01b037f000000000000000000000000735c2ad31748a515894247ef9b37036f3c9ed40b165af1958615610427578496610f81575b509084610efb92612602565b6001600160a01b037f000000000000000000000000a7a7141b5a8d24c50c6bd65b1a6c8acde192e7a616803b1561042357602483926040519485938492630ad0753560e11b845260048401525af1801561042757610f6c575b50602092610f63600192612670565b55604051908152f35b610f77848092611d4a565b6104235738610f54565b91935094506020813d602011610fb2575b81610f9f60209383611d4a565b810103126104c657519385929084610eef565b3d9150610f92565b60048b7f400b91a1000000000000000000000000000000000000000000000000000000008152fd5b9091506020813d60201161100e575b81610ffe60209383611d4a565b810103126104c657519038610e21565b3d9150610ff1565b9291506020833d602011611045575b8161103260209383611d4a565b810103126104c657915190916024610dc4565b3d9150611025565b604051903d90823e3d90fd5b9091506020813d602011611085575b8161107560209383611d4a565b810103126104c657519038610d8d565b3d9150611068565b6040513d8e823e3d90fd5b6020602491604051928380926370a0823160e01b82523060048301525afa9081156104d35789916110ca575b50610d36565b90506020813d6020116110f4575b816110e560209383611d4a565b810103126104c65751386110c4565b3d91506110d8565b6020602491604051928380926370a0823160e01b82523060048301525afa90811561054257889161112f575b5093610d20565b90506020813d602011611159575b8161114a60209383611d4a565b810103126104c6575138611128565b3d915061113d565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b1578791611194575b5091610d0c565b90506020813d6020116111be575b816111af60209383611d4a565b810103126104c657513861118d565b3d91506111a2565b503461062e578060031936011261062e5760206040516001600160a01b037f000000000000000000000000a889b6495e667790163d113134215ed30876d08d168152f35b508061121536611f7b565b909492936112216120c8565b80516001600160a01b0316806115f8575083915b81516001600160a01b031680611590575084935b60408301516001600160a01b031680611528575085905b7f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c926001600160a01b03841692604051906370a0823160e01b8252306004830152602082602481885afa918215610976578a926114f1575b50906024916001600160a01b038c169960208b604051958680926370a0823160e01b82523060048301525afa93841561108d578c946114ba575b50604051996113008b611cfc565b8a5260208a01526040890152606088015260808701526113228230338c612103565b7f000000000000000000000000735c2ad31748a515894247ef9b37036f3c9ed40b6001600160a01b031691611357838b612167565b602086018051604051633df6f17160e01b81526001600160a01b038d811660048301529788166024820152604481019390935260648301529a909416608485015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48401523360c48401529197918860e481895a94602095f197881561062157869861147f575b5090829161010088940151516113f8575b505090610efb9291612602565b9180949596506001600160a01b03919350511603611457575161142f578592918482611426610efb9461226f565b909192386113eb565b6004867f4168c773000000000000000000000000000000000000000000000000000000008152fd5b6004877fd70f29d2000000000000000000000000000000000000000000000000000000008152fd5b9291955096506020823d6020116114b2575b8161149e60209383611d4a565b810103126104c657905195879490866113da565b3d9150611491565b9b50925060208b3d6020116114e9575b816114d760209383611d4a565b810103126104c6578d9a5192386112f2565b3d91506114ca565b915098506020813d602011611520575b8161150e60209383611d4a565b810103126104c657518b9860246112b8565b3d9150611501565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b157879161155b575b5090611260565b9650506020863d602011611588575b8161157760209383611d4a565b810103126104c65788955138611554565b3d915061156a565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156106215786916115c3575b5093611249565b9550506020853d6020116115f0575b816115df60209383611d4a565b810103126104c657879451386115bc565b3d91506115d2565b6020602491604051928380926370a0823160e01b82523060048301525afa90811561090f57859161162b575b5091611235565b9450506020843d602011611658575b8161164760209383611d4a565b810103126104c65786935138611624565b3d915061163a565b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c168152f35b50806116af36611f7b565b91929094936116bc6120c8565b80516001600160a01b031680611aba575084925b81516001600160a01b031680611a55575085945b60408301516001600160a01b0316806119ec575086905b7f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c926001600160a01b03841692604051906370a0823160e01b8252306004830152602082602481885afa9081156109f7578b916119b3575b6040516370a0823160e01b81523060048201526001600160a01b038a169b9093506020846024818f5afa9384156109b8578d8095611979575b50506040519a61179b8c611cfc565b8b5260208b015260408a0152606089015260808801526117bd82303389612103565b7f000000000000000000000000735c2ad31748a515894247ef9b37036f3c9ed40b6001600160a01b0316916117f28388612167565b602086018051604051633df6f17160e01b81526001600160a01b038a811660048301529788166024820152604481019390935260648301529a909416608485015277ffffffffffffffffffffffffffffffffffffffffffffffff191660a48401523360c48401529197918860e4818a5a94602095f19788156105b1578798611941575b506101008301515161190b575b50509061188f9291612602565b6001600160a01b037f000000000000000000000000a7a7141b5a8d24c50c6bd65b1a6c8acde192e7a616803b1561042357602483926040519485938492630ad0753560e11b845260048401525af180156108c75792600191816020956118fb575b505055604051908152f35b61190491611d4a565b38816118f0565b909192939495506001600160a01b0383511603611457575161142f579161188f918361193888969561226f565b90919238611882565b9097506020813d602011611971575b8161195d60209383611d4a565b8101031261196d57519638611875565b8680fd5b3d9150611950565b819295509060209182903d84116119ab575b6119958284611d4a565b50810103126119a7575192388d61178c565b8c80fd5b3d915061198b565b90506020823d6020116119e4575b816119ce60209383611d4a565b810103126119e0576024915190611753565b8a80fd5b3d91506119c1565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610542578891611a1f575b50906116fb565b90506020813d602011611a4d575b81611a3a60209383611d4a565b81010312611a49575138611a18565b8780fd5b3d9150611a2d565b6020602491604051928380926370a0823160e01b82523060048301525afa9081156105b1578791611a88575b50946116e4565b90506020813d602011611ab2575b81611aa360209383611d4a565b8101031261196d575138611a81565b3d9150611a96565b6020602491604051928380926370a0823160e01b82523060048301525afa908115610621578691611aed575b50926116d0565b90506020813d602011611b1b575b81611b0860209383611d4a565b81010312611b17575138611ae6565b8580fd5b3d9150611afb565b503461062e578060031936011261062e5760206040516001600160a01b037f0000000000000000000000006352a56caadc4f1e25cd6c75970fa768a3304e64168152f35b503461062e578060031936011261062e5760206040516001600160a01b037f000000000000000000000000e5d7c2a44ffddf6b295a15c148167daaaf5cf34f168152f35b503461062e57608060031936011261062e57611bc5611cbc565b50611bce611cd2565b5060643567ffffffffffffffff8111610483573660238201121561048357806004013567ffffffffffffffff8111610423573691016024011161062e5760206040517f150b7a02000000000000000000000000000000000000000000000000000000008152f35b503461062e578060031936011261062e5760206040516001600160a01b037f000000000000000000000000735c2ad31748a515894247ef9b37036f3c9ed40b168152f35b9050346104835781600319360112610483576020906001600160a01b037f000000000000000000000000a7a7141b5a8d24c50c6bd65b1a6c8acde192e7a6168152f35b600435906001600160a01b03821682036104c657565b602435906001600160a01b03821682036104c657565b35906001600160a01b03821682036104c657565b60a0810190811067ffffffffffffffff821117611d1857604052565b634e487b7160e01b600052604160045260246000fd5b6080810190811067ffffffffffffffff821117611d1857604052565b90601f601f19910116810190811067ffffffffffffffff821117611d1857604052565b67ffffffffffffffff8111611d1857601f01601f191660200190565b81601f820112156104c657602081359101611da382611d6d565b92611db16040519485611d4a565b828452828201116104c65781600092602092838601378301015290565b9080601f830112156104c65781359167ffffffffffffffff8311611d18578260051b60405193611e016020830186611d4a565b8452602080850191830101918383116104c65760208101915b838310611e2957505050505090565b823567ffffffffffffffff81116104c6578201906080601f1983880301126104c65760405190611e5882611d2e565b60208301358252604083013560208301526060830135604083015260808301359167ffffffffffffffff83116104c657611e9a88602080969581960101611d89565b6060820152815201920191611e1a565b9190610120838203126104c65760405190610120820182811067ffffffffffffffff821117611d18576040528193611ee181611ce8565b835260208101356020840152611ef960408201611ce8565b6040840152606081013560608401526080810135608084015260a081013560a0840152611f2860c08201611ce8565b60c084015260e081013567ffffffffffffffff81116104c65782611f4d918301611d89565b60e08401526101008101359167ffffffffffffffff83116104c65761010092611f769201611dce565b910152565b60a06003198201126104c6576004359067ffffffffffffffff82116104c657611fa691600401611eaa565b906024356001600160a01b03811681036104c65790604435906064356001600160a01b03811681036104c6579060843577ffffffffffffffffffffffffffffffffffffffffffffffff19811681036104c65790565b908160209103126104c6575190565b9190820391821161201757565b634e487b7160e01b600052601160045260246000fd5b80518210156120415760209160051b010190565b634e487b7160e01b600052603260045260246000fd5b3d15612082573d9061206882611d6d565b916120766040519384611d4a565b82523d6000602084013e565b606090565b919082519283825260005b8481106120b3575050601f19601f8460006020809697860101520116010190565b80602080928401015182828601015201612092565b6002600054146120d9576002600055565b7f3ee5aeb50000000000000000000000000000000000000000000000000000000060005260046000fd5b6040517f23b872dd0000000000000000000000000000000000000000000000000000000060208201526001600160a01b03928316602482015292909116604483015260648083019390935291815261216591612160608483611d4a565b612866565b565b60405190602060006001600160a01b03828501957f095ea7b300000000000000000000000000000000000000000000000000000000875216948560248601527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6044860152604485526121db606486611d4a565b84519082855af16000513d8261224a575b5050156121f857505050565b61216061216593604051907f095ea7b300000000000000000000000000000000000000000000000000000000602083015260248201526000604482015260448152612244606482611d4a565b82612866565b90915061226757506001600160a01b0381163b15155b38806121ec565b600114612260565b80516001600160a01b03168061259e575060208101513403612574575b610100810180515161229c575050565b6001600160a01b03825116906001600160a01b03604084015116906020840151936060810194855160808301519060a08401519260e06001600160a01b0360c08701511695015195604051986101408a018a811067ffffffffffffffff821117611d185760409a999a9897969594939298528852602088019889526040880196308852606089019030825260808a0192835260a08a0193845260c08a0194855260e08a019586526101008a019687526101208a0197885251976040519a8b9a7f90411a32000000000000000000000000000000000000000000000000000000008c523060048d015260248c0160609052516001600160a01b031660648c0152516001600160a01b031660848b0152516001600160a01b031660a48a0152516001600160a01b031660c48901525160e4880152516101048701525161012486015251610144850152516001600160a01b031661016484015251610184830161014090526101a4830161240c91612087565b828103600319016044840152815180825260208201918160051b810160200193602001926000915b83831061251e57505050505090806020920381346001600160a01b037f0000000000000000000000006352a56caadc4f1e25cd6c75970fa768a3304e64165af1600091816124ea575b506124ac577fa4532fc20000000000000000000000000000000000000000000000000000000060005260046000fd5b9051908181106124ba575050565b7fd28d3eb50000000000000000000000000000000000000000000000000000000060005260045260245260446000fd5b9091506020813d602011612516575b8161250660209383611d4a565b810103126104c65751903861247d565b3d91506124f9565b91939550919360208061256283601f198660019603018752608060608b51805184528581015186850152604081015160408501520151918160608201520190612087565b97019301930190928695949293612434565b7f242b035c0000000000000000000000000000000000000000000000000000000060005260046000fd5b6020820151806125b0575b505061228c565b6125bd9130903390612103565b6125fb6001600160a01b038251166001600160a01b037f0000000000000000000000006352a56caadc4f1e25cd6c75970fa768a3304e641690612167565b38806125a9565b6080612165936126376001600160a01b0360408195612629838251166020870151906128e3565b0151166040830151906128e3565b6126676060820151847f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c166128e3565b015191166128e3565b6001600160a01b038116906001600160a01b037f0000000000000000000000007bf60411d3238c508f6bf4603ec651bc2d98034c16808314612861576001600160a01b037f000000000000000000000000a889b6495e667790163d113134215ed30876d08d1690604051936370a0823160e01b8552600092806004870152602086602481855afa95861561042757849661282d575b50851561282557803b15610432576040517f95ccea67000000000000000000000000000000000000000000000000000000008152826004820152866024820152848160448183865af1801561090f5761280b575b5090836020949560e4936127976001600160a01b037f000000000000000000000000735c2ad31748a515894247ef9b37036f3c9ed40b168093612167565b6040519889968795633df6f17160e01b87526004870152602486015260448501528260648501528260848501528260a485015260c48401525af190811561104d57506127e05750565b6128019060203d602011612804575b6127f98183611d4a565b810190611ffb565b50565b503d6127ef565b908461281c60209660e49594611d4a565b94509091612759565b505050505050565b9095506020813d602011612859575b8161284960209383611d4a565b8101031261043257519438612705565b3d915061283c565b505050565b906000602091828151910182855af1156128d7576000513d6128ce57506001600160a01b0381163b155b6128975750565b6001600160a01b03907f5274afe7000000000000000000000000000000000000000000000000000000006000521660045260246000fd5b60011415612890565b6040513d6000823e3d90fd5b6001600160a01b03168061294857508047116128fc5750565b6000808061290b81944761200a565b335af1612916612057565b501561291e57565b7fb12d13eb0000000000000000000000000000000000000000000000000000000060005260046000fd5b6040516370a0823160e01b8152306004820152602081602481855afa9081156128d7576000916129d4575b5082811161298057505050565b6121659261298d9161200a565b6040517fa9059cbb00000000000000000000000000000000000000000000000000000000602082015233602482015260448082019290925290815290612160606483611d4a565b906020823d6020116129fe575b816129ee60209383611d4a565b8101031261062e57505138612973565b3d91506129e156fea2646970667358221220f286ab2fa6b565f98b3e644701872b37b5ef166a186d95d72ef15ed8890f0ebb64736f6c634300081c0033

Block Transaction Gas Used Reward
view all blocks sequenced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ 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.