ETH Price: $2,584.63 (-1.90%)

Contract

0x293A0c49c85F1D8851C665Ac3cE1f1DC2a79bE3d
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Buy NF Ts With E...209532082024-10-13 0:50:352 days ago1728780635IN
0x293A0c49...C2a79bE3d
0.12406134 ETH0.004805948.52422136
Sell721209001942024-10-05 15:20:4710 days ago1728141647IN
0x293A0c49...C2a79bE3d
0 ETH0.003499526.08560341
Buy NF Ts With E...209001672024-10-05 15:15:2310 days ago1728141323IN
0x293A0c49...C2a79bE3d
0.0770238 ETH0.003373385.99586274
Sell721208993602024-10-05 12:33:1110 days ago1728131591IN
0x293A0c49...C2a79bE3d
0 ETH0.002384124.16042326
Buy NF Ts With E...208993322024-10-05 12:27:3510 days ago1728131255IN
0x293A0c49...C2a79bE3d
0.07694822 ETH0.00233394.16537496
Buy NF Ts With E...208959272024-10-05 1:04:5910 days ago1728090299IN
0x293A0c49...C2a79bE3d
0.05683991 ETH0.002318133.99446468
Buy NF Ts With E...208554302024-09-29 9:34:3516 days ago1727602475IN
0x293A0c49...C2a79bE3d
0.02307944 ETH0.004343177.53548736
Buy NF Ts With E...207835492024-09-19 8:49:1126 days ago1726735751IN
0x293A0c49...C2a79bE3d
0.00141187 ETH0.0154481828.36522138
Sell721206161872024-08-26 23:56:5949 days ago1724716619IN
0x293A0c49...C2a79bE3d
0 ETH0.000429240.74
Swap721205920802024-08-23 15:05:2353 days ago1724425523IN
0x293A0c49...C2a79bE3d
0.00068138 ETH0.002216215.76805263
Buy NF Ts With E...205859582024-08-22 18:32:4753 days ago1724351567IN
0x293A0c49...C2a79bE3d
0.04750572 ETH0.001058311.90347096
Buy NF Ts With E...205750432024-08-21 5:55:5955 days ago1724219759IN
0x293A0c49...C2a79bE3d
0.03460349 ETH0.000345670.64001009
Buy NF Ts With E...205336202024-08-15 11:05:3561 days ago1723719935IN
0x293A0c49...C2a79bE3d
0.11767802 ETH0.00485468.39784227
Sell721205196742024-08-13 12:22:4763 days ago1723551767IN
0x293A0c49...C2a79bE3d
0 ETH0.001421252.50487025
Buy NF Ts With E...204815412024-08-08 4:41:2368 days ago1723092083IN
0x293A0c49...C2a79bE3d
0.00562312 ETH0.000876981.73795144
Sell721204736402024-08-07 2:14:3569 days ago1722996875IN
0x293A0c49...C2a79bE3d
0 ETH0.000794781.4
Buy NF Ts With E...204483112024-08-03 13:27:3573 days ago1722691655IN
0x293A0c49...C2a79bE3d
0.038698 ETH0.001022211.94560764
Buy NF Ts With E...204256302024-07-31 9:26:3576 days ago1722417995IN
0x293A0c49...C2a79bE3d
0.06011549 ETH0.003372785.73904628
Sell721204249372024-07-31 7:07:2376 days ago1722409643IN
0x293A0c49...C2a79bE3d
0 ETH0.004938285.15473296
Sell721203448182024-07-20 2:40:3587 days ago1721443235IN
0x293A0c49...C2a79bE3d
0 ETH0.000670452.3
Sell721203438882024-07-19 23:32:5987 days ago1721431979IN
0x293A0c49...C2a79bE3d
0 ETH0.002781833.3
Buy NF Ts With E...203193702024-07-16 13:28:1191 days ago1721136491IN
0x293A0c49...C2a79bE3d
0.02619186 ETH0.00453639.20114083
Buy NF Ts With E...203138512024-07-15 18:58:3591 days ago1721069915IN
0x293A0c49...C2a79bE3d
0.02011173 ETH0.0079734515.5645787
Sell721202822652024-07-11 9:07:5996 days ago1720688879IN
0x293A0c49...C2a79bE3d
0 ETH0.005840279.34819117
Sell721202708892024-07-09 19:01:2397 days ago1720551683IN
0x293A0c49...C2a79bE3d
0 ETH0.003921776.58972388
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
209539002024-10-13 3:11:112 days ago1728789071
0x293A0c49...C2a79bE3d
0.03765423 ETH
209539002024-10-13 3:11:112 days ago1728789071
0x293A0c49...C2a79bE3d
0.03765423 ETH
209532082024-10-13 0:50:352 days ago1728780635
0x293A0c49...C2a79bE3d
0.00012393 ETH
209532082024-10-13 0:50:352 days ago1728780635
0x293A0c49...C2a79bE3d
0.00012393 ETH
209532082024-10-13 0:50:352 days ago1728780635
0x293A0c49...C2a79bE3d
0.12406134 ETH
209001942024-10-05 15:20:4710 days ago1728141647
0x293A0c49...C2a79bE3d
0.07225409 ETH
209001942024-10-05 15:20:4710 days ago1728141647
0x293A0c49...C2a79bE3d
0.07225409 ETH
209001672024-10-05 15:15:2310 days ago1728141323
0x293A0c49...C2a79bE3d
0.0003832 ETH
209001672024-10-05 15:15:2310 days ago1728141323
0x293A0c49...C2a79bE3d
0.0003832 ETH
209001672024-10-05 15:15:2310 days ago1728141323
0x293A0c49...C2a79bE3d
0.0770238 ETH
208993602024-10-05 12:33:1110 days ago1728131591
0x293A0c49...C2a79bE3d
0.07217621 ETH
208993602024-10-05 12:33:1110 days ago1728131591
0x293A0c49...C2a79bE3d
0.07217621 ETH
208993322024-10-05 12:27:3510 days ago1728131255
0x293A0c49...C2a79bE3d
0.00038282 ETH
208993322024-10-05 12:27:3510 days ago1728131255
0x293A0c49...C2a79bE3d
0.00038282 ETH
208993322024-10-05 12:27:3510 days ago1728131255
0x293A0c49...C2a79bE3d
0.07694822 ETH
208959272024-10-05 1:04:5910 days ago1728090299
0x293A0c49...C2a79bE3d
0.00028278 ETH
208959272024-10-05 1:04:5910 days ago1728090299
0x293A0c49...C2a79bE3d
0.00028278 ETH
208959272024-10-05 1:04:5910 days ago1728090299
0x293A0c49...C2a79bE3d
0.05683991 ETH
208876612024-10-03 21:26:5911 days ago1727990819
0x293A0c49...C2a79bE3d
0.02150321 ETH
208876612024-10-03 21:26:5911 days ago1727990819
0x293A0c49...C2a79bE3d
0.02150321 ETH
208554302024-09-29 9:34:3516 days ago1727602475
0x293A0c49...C2a79bE3d
0.00011482 ETH
208554302024-09-29 9:34:3516 days ago1727602475
0x293A0c49...C2a79bE3d
0.00011482 ETH
208554302024-09-29 9:34:3516 days ago1727602475
0x293A0c49...C2a79bE3d
0.02307944 ETH
207835492024-09-19 8:49:1126 days ago1726735751
0x293A0c49...C2a79bE3d
0.00000702 ETH
207835492024-09-19 8:49:1126 days ago1726735751
0x293A0c49...C2a79bE3d
0.00000702 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MarketplaceUniversalRouterZap

Compiler Version
v0.8.15+commit.e14f2714

Optimization Enabled:
Yes with 800 runs

Other Settings:
london EvmVersion, MIT license
File 1 of 89 : MarketplaceUniversalRouterZap.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";

import {SafeCast} from "@uni-core/libraries/SafeCast.sol";
import {TransferLib} from "@src/lib/TransferLib.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IWETH9} from "@uni-periphery/interfaces/external/IWETH9.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";
import {INFTXVaultV3} from "@src/interfaces/INFTXVaultV3.sol";
import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";
import {INFTXFeeDistributorV3} from "@src/interfaces/INFTXFeeDistributorV3.sol";
import {IPermitAllowanceTransfer} from "@src/interfaces/external/IPermitAllowanceTransfer.sol";

/**
 * @title Marketplace Universal Router Zap
 * @author @apoorvlathey
 *
 * @notice Marketplace Zap that utilizes Universal Router to facilitate the require token swaps
 * @dev This Zap must be excluded from the vault fees, as vault fees handled via custom logic here.
 */

contract MarketplaceUniversalRouterZap is Ownable, ERC721Holder, ERC1155Holder {
    using SafeERC20 for IERC20;

    // =============================================================
    //                           CONSTANTS
    // =============================================================

    IWETH9 public immutable WETH;
    IPermitAllowanceTransfer public immutable PERMIT2;
    INFTXVaultFactoryV3 public immutable nftxVaultFactory;
    address public immutable inventoryStaking;

    bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
    uint256 constant BASE = 10 ** 18;

    // =============================================================
    //                           VARIABLES
    // =============================================================

    address public universalRouter;

    /// @notice Allows zap to be paused
    bool public paused = false;

    /// @notice The vToken threshold below which dust is sent to InventoryStaking, else back to the user
    uint256 public dustThreshold;

    // =============================================================
    //                            EVENTS
    // =============================================================

    /// @param count The number of tokens affected by the event
    /// @param ethReceived The amount of ETH received in the sell
    /// @param to The user affected by the event
    /// @param netRoyaltyAmount The royalty amount sent
    /// @param wethFees Vault fees paid
    event Sell(
        uint256 vaultId,
        uint256 count,
        uint256 ethReceived,
        address to,
        uint256 netRoyaltyAmount,
        uint256 wethFees
    );

    /// @param ethSpent The amount of ETH spent in the swap
    /// @param to The user affected by the event
    event Swap(
        uint256 vaultId,
        uint256[] idsIn,
        uint256[] idsOut,
        uint256 ethSpent,
        address to
    );

    event Swap(
        uint256 vaultId,
        uint256[] idsIn,
        uint256[] amounts,
        uint256[] idsOut,
        uint256 ethSpent,
        address to
    );

    /// @param nftIds The nftIds bought
    /// @param ethSpent The amount of ETH spent in the buy
    /// @param to The user affected by the event
    /// @param netRoyaltyAmount The royalty amount sent
    event Buy(
        uint256 vaultId,
        uint256[] nftIds,
        uint256 ethSpent,
        address to,
        uint256 netRoyaltyAmount
    );

    /// @notice Emitted when dust is returned after a transaction.
    /// @param ethAmount Amount of ETH returned to user
    /// @param vTokenAmount Amount of vToken returned to user
    /// @param to The user affected by the event
    event DustReturned(uint256 ethAmount, uint256 vTokenAmount, address to);

    event Paused(bool status);
    event NewUniversalRouter(address universalRouter);
    event NewDustThreshold(uint256 dustThreshold);

    // =============================================================
    //                            ERRORS
    // =============================================================

    error ZapPaused();
    error SwapFailed();
    error UnableToSendETH();
    error InsufficientWethForVaultFees();
    error WrongVaultType();
    error NotEnoughFundsForRedeem();
    error ZeroAddress();

    // =============================================================
    //                           INIT
    // =============================================================

    constructor(
        INFTXVaultFactoryV3 nftxVaultFactory_,
        address universalRouter_,
        IPermitAllowanceTransfer PERMIT2_,
        address inventoryStaking_,
        IWETH9 WETH_
    ) {
        nftxVaultFactory = nftxVaultFactory_;
        universalRouter = universalRouter_;
        PERMIT2 = PERMIT2_;
        inventoryStaking = inventoryStaking_;
        WETH = WETH_;
    }

    // =============================================================
    //                     PUBLIC / EXTERNAL WRITE
    // =============================================================

    /**
     * @notice Sell idsIn to ETH
     *
     * @dev idsIn --{--mint-> [vault] -> vTokens --sell-> [UniversalRouter] --}-> ETH
     *
     * @param vaultId The ID of the NFTX vault
     * @param idsIn An array of token IDs to be deposited
     * @param executeCallData Encoded calldata for Universal Router's `execute` function
     * @param to The recipient of ETH from the tx
     */
    function sell721(
        uint256 vaultId,
        uint256[] calldata idsIn,
        bytes calldata executeCallData,
        address payable to,
        bool deductRoyalty
    ) external onlyOwnerIfPaused {
        // Mint (vault fees not deducted here, as zap is on exclusion list)
        (address vault, address assetAddress) = _mint721(vaultId, idsIn);

        // swap vTokens to WETH
        (uint256 wethAmount, ) = _swapTokens(
            vault,
            address(WETH),
            executeCallData
        );

        // distributing vault fees with the weth received
        uint256 wethFees = _ethMintFees(INFTXVaultV3(vault), idsIn.length);
        if (wethAmount < wethFees) revert InsufficientWethForVaultFees();
        _distributeVaultFees(vaultId, wethFees, true);

        uint256 netRoyaltyAmount;
        if (deductRoyalty) {
            netRoyaltyAmount = _deductRoyalty(assetAddress, idsIn, wethAmount);
        }

        wethAmount -= (wethFees + netRoyaltyAmount);

        // convert WETH to ETH and send remaining ETH to `to`
        _wethToETHResidue(to, wethAmount);

        // Emit our sale event
        emit Sell(
            vaultId,
            idsIn.length,
            wethAmount,
            to,
            netRoyaltyAmount,
            wethFees
        );
    }

    /**
     * @notice Swap idsIn to idsOut
     * Send ETH along as well (via msg.value) to account for swap fees
     */
    function swap721(
        uint256 vaultId,
        uint256[] calldata idsIn,
        uint256[] calldata idsOut,
        uint256 vTokenPremiumLimit,
        address payable to
    ) external payable onlyOwnerIfPaused {
        // Transfer tokens from the message sender to the vault
        (address vault, ) = _transferSender721ToVault(vaultId, idsIn);

        // Swap our tokens. Forcing to deduct vault fees
        uint256[] memory emptyAmounts;
        uint256 ethFees = INFTXVaultV3(vault).swap{value: msg.value}(
            idsIn,
            emptyAmounts,
            idsOut,
            msg.sender,
            to,
            vTokenPremiumLimit,
            true
        );

        // send back remaining ETH
        _sendETHResidue(to);

        emit Swap(vaultId, idsIn, idsOut, ethFees, to);
    }

    /**
     * @notice Buy idsOut with ETH
     *
     * @dev ETH --{-sell-> [UniversalRouter] -> vTokens + ETH --redeem-> [vault] --}-> idsOut
     *
     * @param vaultId The ID of the NFTX vault
     * @param idsOut An array of any token IDs to be redeemed
     * @param executeCallData Encoded calldata for Universal Router's `execute` function
     * @param to The recipient of the token IDs from the tx
     */
    function buyNFTsWithETH(
        uint256 vaultId,
        uint256[] calldata idsOut,
        bytes calldata executeCallData,
        address payable to,
        uint256 vTokenPremiumLimit,
        bool deductRoyalty
    ) external payable onlyOwnerIfPaused {
        // Wrap ETH into WETH for our contract
        WETH.deposit{value: msg.value}();

        // swap WETH to vTokens
        address vault = nftxVaultFactory.vault(vaultId);
        uint256 wethSpent;
        uint256 vTokenAmount;
        {
            uint256 iniWETHBal = WETH.balanceOf(address(this));
            (vTokenAmount, ) = _swapTokens(
                address(WETH),
                vault,
                executeCallData
            );
            if (vTokenAmount < idsOut.length * BASE)
                revert NotEnoughFundsForRedeem();
            wethSpent = iniWETHBal - WETH.balanceOf(address(this));
        }

        uint256 wethLeft = msg.value - wethSpent;

        // redeem NFTs. Forcing to deduct vault fees
        TransferLib.unSafeMaxApprove(address(WETH), vault, wethLeft);
        uint256 wethFees = INFTXVaultV3(vault).redeem(
            idsOut,
            to,
            wethLeft,
            vTokenPremiumLimit,
            true
        );

        // the (1 - idsOut.length * BASE / vTokenAmount) share of wethSpent is not spend,
        // but swapped to vTokens and returned to the caller via _transferDust() below
        wethSpent = (wethSpent * idsOut.length * BASE) / vTokenAmount;
        uint256 netRoyaltyAmount;
        if (deductRoyalty) {
            address assetAddress = INFTXVaultV3(vault).assetAddress();
            netRoyaltyAmount = _deductRoyalty(assetAddress, idsOut, wethSpent);
        }

        // transfer vToken dust and remaining WETH balance
        _transferDust(vault, true);

        emit Buy(
            vaultId,
            idsOut,
            wethSpent + wethFees + netRoyaltyAmount,
            to,
            netRoyaltyAmount
        );
    }

    struct BuyNFTsWithERC20Params {
        IERC20 tokenIn; // Input ERC20 token
        uint256 amountIn; // Input ERC20 amount
        uint256 vaultId; // The ID of the NFTX vault
        uint256[] idsOut; // An array of any token IDs to be redeemed
        uint256 vTokenPremiumLimit;
        bytes executeToWETHCallData; // Encoded calldata for "ERC20 to WETH swap" for Universal Router's `execute` function
        bytes executeToVTokenCallData; // Encoded calldata for "WETH to vToken swap" for Universal Router's `execute` function
        address payable to; // The recipient of the token IDs from the tx
        bool deductRoyalty;
    }

    /**
     * @notice Buy idsOut with ERC20
     *
     * @dev ERC20 --{-sell-> [UniversalRouter] -> ETH -> [UniversalRouter] -> vTokens + ETH --redeem-> [vault] --}-> idsOut
     */
    function buyNFTsWithERC20(
        BuyNFTsWithERC20Params calldata params
    ) external onlyOwnerIfPaused {
        params.tokenIn.safeTransferFrom(
            msg.sender,
            address(this),
            params.amountIn
        );

        return _buyNFTsWithERC20(params);
    }

    function buyNFTsWithERC20WithPermit2(
        BuyNFTsWithERC20Params calldata params,
        bytes calldata encodedPermit2
    ) external onlyOwnerIfPaused {
        if (encodedPermit2.length > 0) {
            (
                address owner,
                IPermitAllowanceTransfer.PermitSingle memory permitSingle,
                bytes memory signature
            ) = abi.decode(
                    encodedPermit2,
                    (address, IPermitAllowanceTransfer.PermitSingle, bytes)
                );

            PERMIT2.permit(owner, permitSingle, signature);
        }

        PERMIT2.transferFrom(
            msg.sender,
            address(this),
            SafeCast.toUint160(params.amountIn),
            address(params.tokenIn)
        );

        return _buyNFTsWithERC20(params);
    }

    /**
     * @notice Sell idsIn to ETH
     *
     * @dev idsIn --{--mint-> [vault] -> vTokens --sell-> [UniversalRouter] --}-> ETH
     *
     * @param vaultId The ID of the NFTX vault
     * @param idsIn An array of token IDs to be deposited
     * @param executeCallData Encoded calldata for Universal Router's `execute` function
     * @param to The recipient of ETH from the tx
     */
    function sell1155(
        uint256 vaultId,
        uint256[] calldata idsIn,
        uint256[] calldata amounts,
        bytes calldata executeCallData,
        address payable to,
        bool deductRoyalty
    ) external onlyOwnerIfPaused {
        // Mint (vault fees not deducted here, as zap is on exclusion list)
        (address vault, address assetAddress) = _mint1155(
            vaultId,
            idsIn,
            amounts
        );

        uint256 totalAmount = _validate1155Ids(idsIn, amounts);

        // swap vTokens to WETH
        (uint256 wethAmount, ) = _swapTokens(
            vault,
            address(WETH),
            executeCallData
        );

        // distributing vault fees with the weth received
        uint256 wethFees = _ethMintFees(INFTXVaultV3(vault), totalAmount);
        if (wethAmount < wethFees) revert InsufficientWethForVaultFees();
        _distributeVaultFees(vaultId, wethFees, true);

        uint256 netRoyaltyAmount;
        if (deductRoyalty) {
            netRoyaltyAmount = _deductRoyalty1155(
                assetAddress,
                idsIn,
                amounts,
                totalAmount,
                wethAmount
            );
        }

        wethAmount -= (wethFees + netRoyaltyAmount); // if underflow, then revert desired

        // convert WETH to ETH and send remaining ETH to `to`
        _wethToETHResidue(to, wethAmount);

        // Emit our sale event
        emit Sell(
            vaultId,
            totalAmount,
            wethAmount,
            to,
            netRoyaltyAmount,
            wethFees
        );
    }

    /**
     * @notice Swap idsIn to idsOut
     * Send ETH along as well (via msg.value) to account for swap fees
     */
    function swap1155(
        uint256 vaultId,
        uint256[] calldata idsIn,
        uint256[] calldata amounts,
        uint256[] calldata idsOut,
        uint256 vTokenPremiumLimit,
        address payable to
    ) external payable onlyOwnerIfPaused {
        address vault = nftxVaultFactory.vault(vaultId);
        if (!INFTXVaultV3(vault).is1155()) revert WrongVaultType();

        address assetAddress = INFTXVaultV3(vault).assetAddress();
        IERC1155(assetAddress).safeBatchTransferFrom(
            msg.sender,
            address(this),
            idsIn,
            amounts,
            ""
        );

        IERC1155(assetAddress).setApprovalForAll(vault, true);

        // Swap our tokens. Forcing to deduct vault fees
        uint256 ethFees = INFTXVaultV3(vault).swap{value: msg.value}(
            idsIn,
            amounts,
            idsOut,
            msg.sender,
            to,
            vTokenPremiumLimit,
            true
        );

        // send back remaining ETH
        _sendETHResidue(to);

        emit Swap(vaultId, idsIn, amounts, idsOut, ethFees, to);
    }

    // =============================================================
    //                        ONLY OWNER WRITE
    // =============================================================

    /**
     * @notice A modifier that only allows the owner to interact with the function
     * if the contract is paused. If the contract is not paused then anyone can
     * interact with the function.
     */

    modifier onlyOwnerIfPaused() {
        if (paused && msg.sender != owner()) revert ZapPaused();
        _;
    }

    /**
     * @notice Allows our zap to be paused to prevent any processing.
     *
     * @param paused_ New pause state
     */

    function pause(bool paused_) external onlyOwner {
        paused = paused_;
        emit Paused(paused_);
    }

    function setUniversalRouter(address universalRouter_) external onlyOwner {
        universalRouter = universalRouter_;
        emit NewUniversalRouter(universalRouter_);
    }

    function setDustThreshold(uint256 dustThreshold_) external onlyOwner {
        dustThreshold = dustThreshold_;
        emit NewDustThreshold(dustThreshold_);
    }

    function rescueTokens(IERC20 token) external onlyOwner {
        if (address(token) != address(0)) {
            uint256 balance = token.balanceOf(address(this));
            token.safeTransfer(msg.sender, balance);
        } else {
            uint256 balance = address(this).balance;
            TransferLib.transferETH(msg.sender, balance);
        }
    }

    // =============================================================
    //                      INTERNAL / PRIVATE
    // =============================================================

    function _buyNFTsWithERC20(
        BuyNFTsWithERC20Params calldata params
    ) internal {
        // swap tokenIn to WETH
        _swapTokens(
            address(params.tokenIn),
            address(WETH),
            params.executeToWETHCallData
        );

        // swap some WETH to vTokens
        uint256 iniWETHBal = WETH.balanceOf(address(this));
        address vault = nftxVaultFactory.vault(params.vaultId);

        _swapTokens(address(WETH), vault, params.executeToVTokenCallData);

        uint256 wethLeft = WETH.balanceOf(address(this));
        uint256 wethSpent = iniWETHBal - wethLeft;

        // redeem NFTs
        TransferLib.unSafeMaxApprove(address(WETH), vault, wethLeft);
        uint256 wethFees = INFTXVaultV3(vault).redeem(
            params.idsOut,
            params.to,
            wethLeft,
            params.vTokenPremiumLimit,
            true
        );

        uint256 netRoyaltyAmount;
        if (params.deductRoyalty) {
            address assetAddress = INFTXVaultV3(vault).assetAddress();
            netRoyaltyAmount = _deductRoyalty(
                assetAddress,
                params.idsOut,
                wethSpent
            );
        }

        // transfer vToken dust and remaining WETH balance
        _transferDust(vault, true);

        emit Buy(
            params.vaultId,
            params.idsOut,
            wethSpent + wethFees + netRoyaltyAmount,
            params.to,
            netRoyaltyAmount
        );
    }

    /**
     * @param vaultId The ID of the NFTX vault
     * @param ids An array of token IDs to be minted
     */
    function _mint721(
        uint256 vaultId,
        uint256[] calldata ids
    ) internal returns (address vault, address assetAddress) {
        // Transfer tokens from the message sender to the vault
        (vault, assetAddress) = _transferSender721ToVault(vaultId, ids);

        // Mint our tokens from the vault to this contract
        uint256[] memory emptyAmounts;
        INFTXVaultV3(vault).mint(ids, emptyAmounts, msg.sender, address(this));
    }

    function _mint1155(
        uint256 vaultId,
        uint256[] calldata ids,
        uint256[] calldata amounts
    ) internal returns (address vault, address assetAddress) {
        vault = nftxVaultFactory.vault(vaultId);
        if (!INFTXVaultV3(vault).is1155()) revert WrongVaultType();

        assetAddress = INFTXVaultV3(vault).assetAddress();
        IERC1155(assetAddress).safeBatchTransferFrom(
            msg.sender,
            address(this),
            ids,
            amounts,
            ""
        );
        IERC1155(assetAddress).setApprovalForAll(vault, true);

        // Mint our tokens from the vault to this contract
        INFTXVaultV3(vault).mint(ids, amounts, msg.sender, address(this));
    }

    function _validate1155Ids(
        uint256[] calldata ids,
        uint256[] calldata amounts
    ) internal pure returns (uint256 totalAmount) {
        // Sum the amounts for our emitted events
        for (uint i; i < ids.length; ) {
            unchecked {
                // simultaneously verifies that lengths of `ids` and `amounts` match.
                totalAmount += amounts[i];
                ++i;
            }
        }
    }

    function _transferSender721ToVault(
        uint256 vaultId,
        uint256[] calldata ids
    ) internal returns (address vault, address assetAddress) {
        // Get our vault address information
        vault = nftxVaultFactory.vault(vaultId);

        assetAddress = INFTXVaultV3(vault).assetAddress();

        // Transfer tokens from the message sender to the vault
        TransferLib.transferFromERC721(assetAddress, address(vault), ids);
    }

    /**
     * @notice Swaps ERC20->ERC20 tokens using Universal Router.
     *
     * @param executeCallData Encoded calldata for Universal Router's `execute` function
     */
    function _swapTokens(
        address sellToken,
        address buyToken,
        bytes calldata executeCallData
    ) internal returns (uint256 boughtAmount, uint256 finalBuyTokenBalance) {
        // Track our balance of the buyToken to determine how much we've bought.
        uint256 iniBuyTokenBalance = IERC20(buyToken).balanceOf(address(this));

        _permit2ApproveToken(sellToken, address(universalRouter));

        // execute swap
        (bool success, ) = address(universalRouter).call(executeCallData);
        if (!success) revert SwapFailed();

        // Use our current buyToken balance to determine how much we've bought.
        finalBuyTokenBalance = IERC20(buyToken).balanceOf(address(this));
        boughtAmount = finalBuyTokenBalance - iniBuyTokenBalance;
    }

    function _permit2ApproveToken(address token, address spender) internal {
        (uint160 permitAllowance, , ) = PERMIT2.allowance(
            address(this),
            token,
            spender
        );
        if (
            permitAllowance >=
            uint160(0xf000000000000000000000000000000000000000) // sufficiently large value
        ) return;

        IERC20(token).safeApprove(address(PERMIT2), type(uint256).max);
        PERMIT2.approve(token, spender, type(uint160).max, type(uint48).max);
    }

    function _ethMintFees(
        INFTXVaultV3 vToken,
        uint256 nftCount
    ) internal view returns (uint256) {
        (uint256 mintFee, , ) = vToken.vaultFees();

        return vToken.vTokenToETH(mintFee * nftCount);
    }

    function _distributeVaultFees(
        uint256 vaultId,
        uint256 ethAmount,
        bool isWeth
    ) internal {
        if (ethAmount > 0) {
            INFTXFeeDistributorV3 feeDistributor = INFTXFeeDistributorV3(
                nftxVaultFactory.feeDistributor()
            );
            if (!isWeth) {
                WETH.deposit{value: ethAmount}();
            }
            WETH.transfer(address(feeDistributor), ethAmount);
            feeDistributor.distribute(vaultId);
        }
    }

    function _deductRoyalty(
        address nft,
        uint256[] calldata idsIn,
        uint256 netWethAmount
    ) internal returns (uint256 netRoyaltyAmount) {
        bool success = IERC2981(nft).supportsInterface(_INTERFACE_ID_ERC2981);
        if (success) {
            uint256 salePrice = netWethAmount / idsIn.length;

            for (uint256 i; i < idsIn.length; ) {
                (address receiver, uint256 royaltyAmount) = IERC2981(nft)
                    .royaltyInfo(idsIn[i], salePrice);
                netRoyaltyAmount += royaltyAmount;

                if (royaltyAmount > 0) {
                    WETH.transfer(receiver, royaltyAmount);
                }

                unchecked {
                    ++i;
                }
            }
        }
    }

    function _deductRoyalty1155(
        address nft,
        uint256[] calldata idsIn,
        uint256[] calldata amounts,
        uint256 totalAmount,
        uint256 netWethAmount
    ) internal returns (uint256 netRoyaltyAmount) {
        bool success = IERC2981(nft).supportsInterface(_INTERFACE_ID_ERC2981);
        if (success) {
            uint256 salePrice = netWethAmount / totalAmount;

            for (uint256 i; i < idsIn.length; ) {
                (address receiver, uint256 royaltyAmount) = IERC2981(nft)
                    .royaltyInfo(idsIn[i], salePrice);

                uint256 royaltyToPay = royaltyAmount * amounts[i];
                netRoyaltyAmount += royaltyToPay;

                if (royaltyToPay > 0) {
                    WETH.transfer(receiver, royaltyToPay);
                }

                unchecked {
                    ++i;
                }
            }
        }
    }

    function _allWethToETHResidue(
        address to
    ) internal returns (uint256 wethAmount) {
        wethAmount = WETH.balanceOf(address(this));
        _wethToETHResidue(to, wethAmount);
    }

    function _wethToETHResidue(address to, uint256 wethAmount) internal {
        if (wethAmount > 0) {
            // Unwrap our WETH into ETH and transfer it to the recipient
            WETH.withdraw(wethAmount);
        }
        _sendETHResidue(to);
    }

    function _sendETHResidue(address to) internal {
        if (to == address(0)) revert ZeroAddress();
        // sending entire ETH balance (hence accounting for the unused msg.value)
        (bool success, ) = payable(to).call{value: address(this).balance}("");
        if (!success) revert UnableToSendETH();
    }

    /**
     * @notice Transfers remaining ETH to msg.sender.
     * And transfers vault token dust to feeDistributor if below dustThreshold, else to msg.sender
     *
     * @param vault Address of the vault token
     * @param hasWETHDust Checks and transfers WETH dust if boolean is true
     */
    function _transferDust(address vault, bool hasWETHDust) internal {
        uint256 wethRemaining;
        if (hasWETHDust) {
            wethRemaining = _allWethToETHResidue(msg.sender);
        }

        uint256 dustBalance = IERC20(vault).balanceOf(address(this));
        address dustRecipient;
        if (dustBalance > 0) {
            if (dustBalance > dustThreshold) {
                dustRecipient = msg.sender;
            } else {
                dustRecipient = inventoryStaking;
            }

            IERC20(vault).transfer(dustRecipient, dustBalance);
        }

        emit DustReturned(wethRemaining, dustBalance, dustRecipient);
    }

    receive() external payable {}
}

File 2 of 89 : IERC3156FlashBorrowerUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC3156FlashBorrower.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC3156 FlashBorrower, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * _Available since v4.1._
 */
interface IERC3156FlashBorrowerUpgradeable {
    /**
     * @dev Receive a flash loan.
     * @param initiator The initiator of the loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param fee The additional amount of tokens to repay.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     * @return The keccak256 hash of "IERC3156FlashBorrower.onFlashLoan"
     */
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external returns (bytes32);
}

File 3 of 89 : IERC3156FlashLenderUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol)

pragma solidity ^0.8.0;

import "./IERC3156FlashBorrowerUpgradeable.sol";

/**
 * @dev Interface of the ERC3156 FlashLender, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * _Available since v4.1._
 */
interface IERC3156FlashLenderUpgradeable {
    /**
     * @dev The amount of currency available to be lended.
     * @param token The loan currency.
     * @return The amount of `token` that can be borrowed.
     */
    function maxFlashLoan(address token) external view returns (uint256);

    /**
     * @dev The fee to be charged for a given loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @return The amount of `token` to be charged for the loan, on top of the returned principal.
     */
    function flashFee(address token, uint256 amount) external view returns (uint256);

    /**
     * @dev Initiate a flash loan.
     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     */
    function flashLoan(
        IERC3156FlashBorrowerUpgradeable receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
}

File 4 of 89 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

File 5 of 89 : IERC1155Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155Upgradeable is IERC165Upgradeable {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

File 6 of 89 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 7 of 89 : IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

File 8 of 89 : ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
    using AddressUpgradeable for address;
    using StringsUpgradeable for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC721_init_unchained(name_, symbol_);
    }

    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721Upgradeable.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721Upgradeable.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256, /* firstTokenId */
        uint256 batchSize
    ) internal virtual {
        if (batchSize > 1) {
            if (from != address(0)) {
                _balances[from] -= batchSize;
            }
            if (to != address(0)) {
                _balances[to] += batchSize;
            }
        }
    }

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[44] private __gap;
}

File 9 of 89 : IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721ReceiverUpgradeable {
    /**
     * @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);
}

File 10 of 89 : IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721Upgradeable is IERC165Upgradeable {
    /**
     * @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 ERC721 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 ERC721
     * 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 caller.
     *
     * 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 89 : IERC721MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721Upgradeable.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 12 of 89 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 13 of 89 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 14 of 89 : Create2Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Create2.sol)

pragma solidity ^0.8.0;

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2Upgradeable {
    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(
        uint256 amount,
        bytes32 salt,
        bytes memory bytecode
    ) internal returns (address addr) {
        require(address(this).balance >= amount, "Create2: insufficient balance");
        require(bytecode.length != 0, "Create2: bytecode length is zero");
        /// @solidity memory-safe-assembly
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        require(addr != address(0), "Create2: Failed on deploy");
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(
        bytes32 salt,
        bytes32 bytecodeHash,
        address deployer
    ) internal pure returns (address addr) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := keccak256(start, 85)
        }
    }
}

File 15 of 89 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, MathUpgradeable.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

File 16 of 89 : ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 17 of 89 : IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @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[EIP 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);
}

File 18 of 89 : MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

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

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

File 19 of 89 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }
}

File 20 of 89 : IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.0;

import "../utils/introspection/IERC165.sol";

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 *
 * _Available since v4.5._
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice)
        external
        view
        returns (address receiver, uint256 royaltyAmount);
}

File 21 of 89 : IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

File 22 of 89 : IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

File 23 of 89 : ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.0;

import "./ERC1155Receiver.sol";

/**
 * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 *
 * @dev _Available since v3.1._
 */
contract ERC1155Holder is ERC1155Receiver {
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

File 24 of 89 : ERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";

/**
 * @dev _Available since v3.1._
 */
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }
}

File 25 of 89 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

File 26 of 89 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 27 of 89 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @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).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 28 of 89 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 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 ERC721 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * 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 caller.
     *
     * 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 29 of 89 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 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);
}

File 30 of 89 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

File 31 of 89 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 32 of 89 : ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.0;

import "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address,
        address,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

File 33 of 89 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 34 of 89 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

File 35 of 89 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

File 36 of 89 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 37 of 89 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

File 38 of 89 : InventoryStakingDescriptor.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import {Base64} from "base64-sol/base64.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {HexStrings} from "@uni-periphery/libraries/HexStrings.sol";

contract InventoryStakingDescriptor {
    using Strings for uint256;
    using HexStrings for uint256;

    // =============================================================
    //                        CONSTANTS
    // =============================================================

    string internal constant PREFIX = "x";

    // =============================================================
    //                        INTERNAL
    // =============================================================

    function renderSVG(
        uint256 tokenId,
        uint256 vaultId,
        address vToken,
        string calldata vTokenSymbol,
        uint256 vTokenBalance,
        uint256 wethBalance,
        uint256 timelockLeft
    ) public pure returns (string memory) {
        return
            string.concat(
                '<svg width="290" height="500" viewBox="0 0 290 500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">',
                getDefs(
                    tokenToColorHex(uint256(uint160(vToken)), 136),
                    tokenToColorHex(uint256(uint160(vToken)), 100)
                ),
                '<g mask="url(#fade-symbol)">',
                text("32", "70", "200", "32"),
                PREFIX,
                vTokenSymbol,
                "</text>",
                underlyingBalances(vTokenSymbol, vTokenBalance, wethBalance),
                '<rect x="16" y="16" width="258" height="468" rx="26" ry="26" fill="rgba(0,0,0,0)" stroke="rgba(255,255,255,0.2)"/>',
                infoTags(tokenId, vaultId, timelockLeft),
                "</svg>"
            );
    }

    function tokenURI(
        uint256 tokenId,
        uint256 vaultId,
        address vToken,
        string calldata vTokenSymbol,
        uint256 vTokenBalance,
        uint256 wethBalance,
        uint256 timelockedUntil
    ) external view returns (string memory) {
        string memory image = Base64.encode(
            bytes(
                renderSVG(
                    tokenId,
                    vaultId,
                    vToken,
                    vTokenSymbol,
                    vTokenBalance,
                    wethBalance,
                    block.timestamp > timelockedUntil
                        ? 0
                        : timelockedUntil - block.timestamp
                )
            )
        );

        return
            string.concat(
                "data:application/json;base64,",
                Base64.encode(
                    bytes(
                        string.concat(
                            '{"name":"',
                            string.concat(
                                "x",
                                vTokenSymbol,
                                " #",
                                tokenId.toString()
                            ),
                            '", "description":"',
                            "xNFT representing inventory staking position on NFTX",
                            '", "image": "',
                            "data:image/svg+xml;base64,",
                            image,
                            '", "attributes": [{"trait_type": "VaultId", "value": "',
                            vaultId.toString(),
                            '"}]}'
                        )
                    )
                )
            );
    }

    // =============================================================
    //                        PRIVATE
    // =============================================================

    function getDefs(
        string memory color2,
        string memory color3
    ) private pure returns (string memory) {
        return
            string.concat(
                "<defs>",
                '<filter id="f1"><feImage result="p2" xlink:href="data:image/svg+xml;base64,',
                Base64.encode(
                    bytes(
                        string.concat(
                            "<svg width='290' height='500' viewBox='0 0 290 500' xmlns='http://www.w3.org/2000/svg'><circle cx='16' cy='232' r='120px' fill='#",
                            color2,
                            "'/></svg>"
                        )
                    )
                ),
                '"/><feImage result="p3" xlink:href="data:image/svg+xml;base64,',
                Base64.encode(
                    bytes(
                        string.concat(
                            "<svg width='290' height='500' viewBox='0 0 290 500' xmlns='http://www.w3.org/2000/svg'><circle cx='20' cy='100' r='130px' fill='#",
                            color3,
                            "'/></svg>"
                        )
                    )
                ),
                '"/><feBlend mode="exclusion" in2="p2"/><feBlend mode="overlay" in2="p3" result="blendOut"/><feGaussianBlur in="blendOut" stdDeviation="42"/></filter><clipPath id="corners"><rect width="290" height="500" rx="42" ry="42"/></clipPath><filter id="top-region-blur"><feGaussianBlur in="SourceGraphic" stdDeviation="24"/></filter><linearGradient id="grad-symbol"><stop offset="0.7" stop-color="white" stop-opacity="1"/><stop offset=".95" stop-color="white" stop-opacity="0"/></linearGradient><mask id="fade-symbol" maskContentUnits="userSpaceOnUse"><rect width="290px" height="200px" fill="url(#grad-symbol)"/></mask></defs>',
                '<g clip-path="url(#corners)"><rect fill="2c9715" x="0px" y="0px" width="290px" height="500px"/><rect style="filter: url(#f1)" x="0px" y="0px" width="290px" height="500px"/><g style="filter:url(#top-region-blur); transform:scale(1.5); transform-origin:center top;"><rect fill="none" x="0px" y="0px" width="290px" height="500px"/><ellipse cx="50%" cy="0px" rx="180px" ry="120px" fill="#000" opacity="0.85"/></g><rect x="0" y="0" width="290" height="500" rx="42" ry="42" fill="rgba(0,0,0,0)" stroke="rgba(255,255,255,0.2)"/></g>'
            );
    }

    function text(
        string memory x,
        string memory y,
        string memory fontWeight,
        string memory fontSize
    ) private pure returns (string memory) {
        return text(x, y, fontWeight, fontSize, false);
    }

    function text(
        string memory x,
        string memory y,
        string memory fontWeight,
        string memory fontSize,
        bool onlyMonospace
    ) private pure returns (string memory) {
        return
            string.concat(
                '<text y="',
                y,
                'px" x="',
                x,
                'px" fill="white" font-family="',
                !onlyMonospace ? "'Courier New', " : "",
                'monospace" font-weight="',
                fontWeight,
                '" font-size="',
                fontSize,
                'px">'
            );
    }

    function tokenToColorHex(
        uint256 token,
        uint256 offset
    ) private pure returns (string memory str) {
        return string((token >> offset).toHexStringNoPrefix(3));
    }

    function balanceTag(
        string memory y,
        uint256 tokenBalance,
        string memory tokenSymbol
    ) private pure returns (string memory) {
        uint256 beforeDecimal = tokenBalance / 1 ether;
        string memory afterDecimals = getAfterDecimals(tokenBalance);

        uint256 leftPadding = 12;
        uint256 beforeDecimalFontSize = 20;
        uint256 afterDecimalFontSize = 16;

        uint256 width = leftPadding +
            ((getDigitsCount(beforeDecimal) + 1) * beforeDecimalFontSize) /
            2 +
            (bytes(afterDecimals).length * afterDecimalFontSize * 100) /
            100;

        return
            string.concat(
                '<g style="transform:translate(29px, ',
                y,
                'px)"><rect width="',
                width.toString(),
                'px" height="30px" rx="8px" ry="8px" fill="rgba(0,0,0,0.6)"/>',
                text(
                    leftPadding.toString(),
                    "21",
                    "100",
                    beforeDecimalFontSize.toString(),
                    true
                ),
                beforeDecimal.toString(),
                '.<tspan font-size="',
                afterDecimalFontSize.toString(),
                'px">',
                afterDecimals,
                '</tspan> <tspan fill="rgba(255,255,255,0.8)">',
                tokenSymbol,
                "</tspan></text></g>"
            );
    }

    function infoTag(
        string memory y,
        string memory label,
        string memory value
    ) private pure returns (string memory) {
        return
            string.concat(
                '<g style="transform:translate(29px, ',
                y,
                'px)"><rect width="98px" height="26px" rx="8px" ry="8px" fill="rgba(0,0,0,0.6)"/>',
                text("12", "17", "100", "12"),
                '<tspan fill="rgba(255,255,255,0.6)">',
                label,
                ": </tspan>",
                value,
                "</text></g>"
            );
    }

    function underlyingBalances(
        string memory vTokenSymbol,
        uint256 vTokenBalance,
        uint256 wethBalance
    ) private pure returns (string memory) {
        return
            string.concat(
                text("32", "160", "200", "16"),
                "Underlying Balance</text></g>",
                balanceTag("180", vTokenBalance, vTokenSymbol),
                balanceTag("220", wethBalance, "WETH")
            );
    }

    function infoTags(
        uint256 tokenId,
        uint256 vaultId,
        uint256 timelockLeft
    ) private pure returns (string memory) {
        return
            string.concat(
                infoTag("384", "ID", tokenId.toString()),
                infoTag("414", "VaultId", vaultId.toString()),
                infoTag(
                    "444",
                    "Timelock",
                    timelockLeft > 0
                        ? string.concat(timelockLeft.toString(), "s left")
                        : "Unlocked"
                )
            );
    }

    function getDigitsCount(uint256 num) private pure returns (uint256 count) {
        if (num == 0) return 1;

        while (num > 0) {
            ++count;
            num /= 10;
        }
    }

    function getAfterDecimals(
        uint256 tokenBalance
    ) private pure returns (string memory afterDecimals) {
        uint256 afterDecimal = (tokenBalance % 1 ether) / 10 ** (18 - 10); // show 10 decimals

        uint256 leadingZeroes;
        if (afterDecimal == 0) {
            leadingZeroes = 0;
        } else {
            leadingZeroes = 10 - getDigitsCount(afterDecimal);
        }

        afterDecimals = afterDecimal.toString();
        for (uint256 i; i < leadingZeroes; ) {
            afterDecimals = string.concat("0", afterDecimals);

            unchecked {
                ++i;
            }
        }
    }
}

File 39 of 89 : IBeacon.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);

    function upgradeBeaconTo(address newImplementation) external;
}

File 40 of 89 : ERC20FlashMintUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/ERC20FlashMint.sol)

pragma solidity ^0.8.0;

import {Initializable} from "@openzeppelin-upgradeable/contracts/proxy/utils/Initializable.sol";
import {ERC20Upgradeable} from "@src/custom/tokens/ERC20/ERC20Upgradeable.sol";
import {IERC3156FlashLenderUpgradeable} from "@openzeppelin-upgradeable/contracts/interfaces/IERC3156FlashLenderUpgradeable.sol";
import {IERC3156FlashBorrowerUpgradeable} from "@openzeppelin-upgradeable/contracts/interfaces/IERC3156FlashBorrowerUpgradeable.sol";

/**
 * NOTE: #NFTX: Forked from OZ, to use custom ERC20Upgradeable which includes `setMetadata()`
 *
 *
 * @dev Implementation of the ERC3156 Flash loans extension, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * Adds the {flashLoan} method, which provides flash loan support at the token
 * level. By default there is no fee, but this can be changed by overriding {flashFee}.
 *
 * _Available since v4.1._
 */
abstract contract ERC20FlashMintUpgradeable is
    Initializable,
    ERC20Upgradeable,
    IERC3156FlashLenderUpgradeable
{
    // Errors
    error WrongToken();
    error AmountExceedsMaxFlashLoan();
    error InvalidReturnValue();

    function __ERC20FlashMint_init() internal onlyInitializing {}

    function __ERC20FlashMint_init_unchained() internal onlyInitializing {}

    bytes32 private constant _RETURN_VALUE =
        keccak256("ERC3156FlashBorrower.onFlashLoan");

    /**
     * @dev Returns the maximum amount of tokens available for loan.
     * @param token The address of the token that is requested.
     * @return The amount of token that can be loaned.
     */
    function maxFlashLoan(
        address token
    ) public view virtual override returns (uint256) {
        return
            token == address(this)
                ? type(uint256).max - ERC20Upgradeable.totalSupply()
                : 0;
    }

    /**
     * @dev Returns the fee applied when doing flash loans. This function calls
     * the {_flashFee} function which returns the fee applied when doing flash
     * loans.
     * @param token The token to be flash loaned.
     * @param amount The amount of tokens to be loaned.
     * @return The fees applied to the corresponding flash loan.
     */
    function flashFee(
        address token,
        uint256 amount
    ) public view virtual override returns (uint256) {
        if (token != address(this)) revert WrongToken();
        return _flashFee(token, amount);
    }

    /**
     * @dev Returns the fee applied when doing flash loans. By default this
     * implementation has 0 fees. This function can be overloaded to make
     * the flash loan mechanism deflationary.
     * @param token The token to be flash loaned.
     * @param amount The amount of tokens to be loaned.
     * @return The fees applied to the corresponding flash loan.
     */
    function _flashFee(
        address token,
        uint256 amount
    ) internal view virtual returns (uint256) {
        // silence warning about unused variable without the addition of bytecode.
        token;
        amount;
        return 0;
    }

    /**
     * @dev Returns the receiver address of the flash fee. By default this
     * implementation returns the address(0) which means the fee amount will be burnt.
     * This function can be overloaded to change the fee receiver.
     * @return The address for which the flash fee will be sent to.
     */
    function _flashFeeReceiver() internal view virtual returns (address) {
        return address(0);
    }

    /**
     * @dev Performs a flash loan. New tokens are minted and sent to the
     * `receiver`, who is required to implement the {IERC3156FlashBorrower}
     * interface. By the end of the flash loan, the receiver is expected to own
     * amount + fee tokens and have them approved back to the token contract itself so
     * they can be burned.
     * @param receiver The receiver of the flash loan. Should implement the
     * {IERC3156FlashBorrower-onFlashLoan} interface.
     * @param token The token to be flash loaned. Only `address(this)` is
     * supported.
     * @param amount The amount of tokens to be loaned.
     * @param data An arbitrary datafield that is passed to the receiver.
     * @return `true` if the flash loan was successful.
     */
    // This function can reenter, but it doesn't pose a risk because it always preserves the property that the amount
    // minted at the beginning is always recovered and burned at the end, or else the entire function will revert.
    // slither-disable-next-line reentrancy-no-eth
    function flashLoan(
        IERC3156FlashBorrowerUpgradeable receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) public virtual override returns (bool) {
        if (amount > maxFlashLoan(token)) revert AmountExceedsMaxFlashLoan();
        uint256 fee = flashFee(token, amount);
        _mint(address(receiver), amount);

        if (
            receiver.onFlashLoan(msg.sender, token, amount, fee, data) !=
            _RETURN_VALUE
        ) revert InvalidReturnValue();

        address flashFeeReceiver = _flashFeeReceiver();
        _spendAllowance(address(receiver), address(this), amount + fee);
        if (fee == 0 || flashFeeReceiver == address(0)) {
            _burn(address(receiver), amount + fee);
        } else {
            _burn(address(receiver), amount);
            _transfer(address(receiver), flashFeeReceiver, fee);
        }
        return true;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 41 of 89 : ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import {Initializable} from "@openzeppelin-upgradeable/contracts/proxy/utils/Initializable.sol";
import {IERC20Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol";
import {ContextUpgradeable} from "@openzeppelin-upgradeable/contracts/utils/ContextUpgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";

/**
 * NOTE: #NFTX: Forked from OZ, to add `setMetadata()`
 *
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is
    Initializable,
    ContextUpgradeable,
    IERC20Upgradeable,
    IERC20MetadataUpgradeable
{
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    event MetadataUpdated(string name, string symbol);

    error DecreasedAllowanceBelowZero();
    error TransferFromZeroAddress();
    error TransferToZeroAddress();
    error TransferAmountExceedsBalance();
    error MintToZeroAddress();
    error BurnFromZeroAddress();
    error BurnAmountExceedsBalance();
    error ApproveFromZeroAddress();
    error ApproveToZeroAddress();
    error InsufficientAllowance();

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(
        string memory name_,
        string memory symbol_
    ) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(
        string memory name_,
        string memory symbol_
    ) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

    function _setMetadata(string memory name_, string memory symbol_) internal {
        _name = name_;
        _symbol = symbol_;

        emit MetadataUpdated(name_, symbol_);
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(
        address account
    ) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(
        address owner,
        address spender
    ) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(
        address spender,
        uint256 amount
    ) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(
        address spender,
        uint256 addedValue
    ) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(
        address spender,
        uint256 subtractedValue
    ) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < subtractedValue)
            revert DecreasedAllowanceBelowZero();
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        if (from == address(0)) revert TransferFromZeroAddress();
        if (to == address(0)) revert TransferToZeroAddress();

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        if (fromBalance < amount) revert TransferAmountExceedsBalance();
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        if (account == address(0)) revert MintToZeroAddress();

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        if (account == address(0)) revert BurnFromZeroAddress();

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        if (accountBalance < amount) revert BurnAmountExceedsBalance();
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        if (owner == address(0)) revert ApproveFromZeroAddress();
        if (spender == address(0)) revert ApproveToZeroAddress();

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < amount) revert InsufficientAllowance();
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}

File 42 of 89 : INFTXEligibility.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface INFTXEligibility {
    // Read functions.
    function name() external pure returns (string memory);

    function finalized() external view returns (bool);

    function targetAsset() external pure returns (address);

    function checkAllEligible(uint256[] calldata tokenIds)
        external
        view
        returns (bool);

    function checkEligible(uint256[] calldata tokenIds)
        external
        view
        returns (bool[] memory);

    function checkAllIneligible(uint256[] calldata tokenIds)
        external
        view
        returns (bool);

    function checkIsEligible(uint256 tokenId) external view returns (bool);

    // Write functions.
    function __NFTXEligibility_init_bytes(bytes calldata configData) external;

    function beforeMintHook(uint256[] calldata tokenIds) external;

    function afterMintHook(uint256[] calldata tokenIds) external;

    function beforeRedeemHook(uint256[] calldata tokenIds) external;

    function afterRedeemHook(uint256[] calldata tokenIds) external;
}

File 43 of 89 : INFTXFeeDistributorV3.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {INFTXRouter} from "@src/interfaces/INFTXRouter.sol";
import {IUniswapV3Factory} from "@uni-core/interfaces/IUniswapV3Factory.sol";
import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";
import {INFTXInventoryStakingV3} from "@src/interfaces/INFTXInventoryStakingV3.sol";

interface INFTXFeeDistributorV3 {
    enum ReceiverType {
        INVENTORY,
        POOL,
        ADDRESS
    }

    struct FeeReceiver {
        address receiver;
        uint256 allocPoint;
        ReceiverType receiverType; // NOTE: receiver address is ignored for `POOL` type, as each vaultId has different pool address
    }

    // =============================================================
    //                           CONSTANTS
    // =============================================================

    function nftxVaultFactory() external view returns (INFTXVaultFactoryV3);

    function ammFactory() external view returns (IUniswapV3Factory);

    function inventoryStaking() external view returns (INFTXInventoryStakingV3);

    function WETH() external view returns (IERC20);

    // =============================================================
    //                            STORAGE
    // =============================================================

    function rewardFeeTier() external view returns (uint24);

    function nftxRouter() external view returns (INFTXRouter);

    function treasury() external view returns (address);

    function allocTotal() external view returns (uint256);

    function feeReceivers(
        uint256
    )
        external
        view
        returns (
            address receiver,
            uint256 allocPoint,
            ReceiverType receiverType
        );

    function distributionPaused() external view returns (bool);

    // =============================================================
    //                            EVENTS
    // =============================================================

    event UpdateTreasuryAddress(address oldTreasury, address newTreasury);
    event PauseDistribution(bool paused);
    event NewRewardFeeTier(uint24 rewardFeeTier);
    event NewNFTXRouter(address nftxRouter);
    event WethDistributedToInventory(uint256 vaultId, uint256 amount);
    event WethDistributedToPool(uint256 vaultId, uint256 amount);

    // =============================================================
    //                            ERRORS
    // =============================================================

    error IdOutOfBounds();
    error ZeroAddress();
    error SenderNotNFTXRouter();
    error FeeTierNotEnabled();

    // =============================================================
    //                     PUBLIC / EXTERNAL WRITE
    // =============================================================

    /**
     * @notice Distributes current WETH balance with the `feeReceivers` for `vaultId`
     * @dev called by other contracts like NFTXVault, after transferring WETH to distribute in the same tx
     */
    function distribute(uint256 vaultId) external;

    /**
     * @notice Distributes vTokens to NFTX AMM pool, can only be called by NFTXRouter
     * @dev called by NFTXRouter, after it sends the vTokens to this contract
     */
    function distributeVTokensToPool(
        address pool,
        address vToken,
        uint256 vTokenAmount
    ) external;

    // =============================================================
    //                        ONLY OWNER WRITE
    // =============================================================

    function setReceivers(FeeReceiver[] memory feeReceivers_) external;

    /**
     * @notice Updating reward fee tier here won't change cardinality for existing UniV3 pools already deployed with `rewardFeeTier_`. That has to be increased externally for each pool.
     * If the new rewardFeeTier pool doesn't exist for a vToken, then the corresponding vault fees would immediately become 0, till liquidity is provided in the new pool.
     *
     * @param rewardFeeTier_ New reward fee tier
     */
    function changeRewardFeeTier(uint24 rewardFeeTier_) external;

    function setTreasuryAddress(address treasury) external;

    function setNFTXRouter(INFTXRouter nftxRouter) external;

    function pauseFeeDistribution(bool pause) external;

    function rescueTokens(IERC20 token) external;
}

File 44 of 89 : INFTXInventoryStakingV3.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;

import {IWETH9} from "@uni-periphery/interfaces/external/IWETH9.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol";

import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";
import {ITimelockExcludeList} from "@src/interfaces/ITimelockExcludeList.sol";
import {IPermitAllowanceTransfer} from "@src/interfaces/external/IPermitAllowanceTransfer.sol";
import {InventoryStakingDescriptor} from "@src/custom/InventoryStakingDescriptor.sol";

interface INFTXInventoryStakingV3 is IERC721Upgradeable {
    // details about the staking position
    struct Position {
        // the nonce for permits
        uint256 nonce;
        // vaultId corresponding to the vTokens staked in this position
        uint256 vaultId;
        // timestamp at which the timelock expires
        uint256 timelockedUntil;
        // net timelock for position
        uint256 timelock;
        // position timelocked if created with vTokens. Can't early withdraw in this case
        uint256 vTokenTimelockedUntil;
        // shares balance is used to track position's ownership of total vToken balance
        uint256 vTokenShareBalance;
        // used to evaluate weth fees accumulated per vTokenShare since this snapshot
        uint256 wethFeesPerVTokenShareSnapshotX128;
        // owed weth fees, updates when positions merged
        uint256 wethOwed;
    }

    struct VaultGlobal {
        uint256 totalVTokenShares;
        uint256 globalWethFeesPerVTokenShareX128;
    }

    // =============================================================
    //                           CONSTANTS
    // =============================================================

    function MINIMUM_LIQUIDITY() external view returns (uint256);

    function nftxVaultFactory() external view returns (INFTXVaultFactoryV3);

    function timelockExcludeList() external view returns (ITimelockExcludeList);

    function WETH() external view returns (IWETH9);

    function PERMIT2() external returns (IPermitAllowanceTransfer);

    // =============================================================
    //                            STORAGE
    // =============================================================

    function timelock() external view returns (uint256);

    function earlyWithdrawPenaltyInWei() external view returns (uint256);

    function positions(
        uint256 positionId
    )
        external
        view
        returns (
            uint256 nonce,
            uint256 vaultId,
            uint256 timelockedUntil,
            uint256 timelock,
            uint256 vTokenTimelockedUntil,
            uint256 vTokenShareBalance,
            uint256 wethFeesPerVTokenShareSnapshotX128,
            uint256 wethOwed
        );

    function vaultGlobal(
        uint256 vaultId
    )
        external
        view
        returns (
            uint256 totalVTokenShares,
            uint256 globalWethFeesPerVTokenShareX128
        );

    function descriptor() external view returns (InventoryStakingDescriptor);

    // =============================================================
    //                            EVENTS
    // =============================================================

    event Deposit(
        uint256 indexed vaultId,
        uint256 indexed positionId,
        uint256 amount,
        bool forceTimelock
    );
    event DepositWithNFT(
        uint256 indexed vaultId,
        uint256 indexed positionId,
        uint256[] tokenIds,
        uint256[] amounts
    );
    event IncreasePosition(
        uint256 indexed vaultId,
        uint256 indexed positionId,
        uint256 amount
    );
    event CombinePositions(
        uint256 parentPositionId,
        uint256[] childPositionIds
    );
    event CollectWethFees(uint256 indexed positionId, uint256 wethAmount);
    event Withdraw(
        uint256 indexed positionId,
        uint256 vTokenShares,
        uint256 vTokenAmount,
        uint256 wethAmount
    );
    event UpdateTimelock(uint256 newTimelock);
    event UpdateEarlyWithdrawPenalty(uint256 newEarlyWithdrawPenaltyInWei);

    // =============================================================
    //                            ERRORS
    // =============================================================

    error TimelockTooLong();
    error InvalidEarlyWithdrawPenalty();
    error NotPositionOwner();
    error Timelocked();
    error VaultIdMismatch();
    error ParentChildSame();
    error InsufficientVTokens();
    error LiquidityBelowMinimum();
    error ZeroAddress();
    error InsufficientVTokenShares();
    error SenderNotFeeDistributor();
    error PositionNotCreatedWithVTokens();
    error ZeroVTokenShares();

    // =============================================================
    //                           INIT
    // =============================================================

    function __NFTXInventoryStaking_init(
        uint256 timelock_,
        uint256 earlyWithdrawPenaltyInWei_,
        ITimelockExcludeList timelockExcludeList_,
        InventoryStakingDescriptor descriptor_
    ) external;

    // =============================================================
    //                     PUBLIC / EXTERNAL WRITE
    // =============================================================

    /**
     * @notice Deposits vToken to mint inventory staking xNFT position
     *
     * @param vaultId The id of the vault
     * @param amount Vault tokens amount to deposit
     * @param recipient Recipient address for the xNFT
     * @param encodedPermit2 Encoded function params (owner, permitSingle, signature) for `PERMIT2.permit()`
     * @param viaPermit2 If true then vTokens transferred via Permit2 else normal token transferFrom
     * @param forceTimelock Forcefully apply timelock to the position
     *
     * @return positionId The tokenId for the xNFT position
     */
    function deposit(
        uint256 vaultId,
        uint256 amount,
        address recipient,
        bytes calldata encodedPermit2,
        bool viaPermit2,
        bool forceTimelock
    ) external returns (uint256 positionId);

    /**
     * @notice Deposits NFT to mint inventory staking xNFT position
     *
     * @param vaultId The id of the vault corresponding to the NFT
     * @param tokenIds The token ids to deposit
     * @param amounts For ERC1155: quantity corresponding to each tokenId to deposit
     * @param recipient Recipient address for the xNFT
     *
     * @return positionId The tokenId for the xNFT position
     */
    function depositWithNFT(
        uint256 vaultId,
        uint256[] calldata tokenIds,
        uint256[] calldata amounts,
        address recipient
    ) external returns (uint256 positionId);

    /**
     * @notice Add more vTokens to an existing position (the position have been created with just vTokens)
     *
     * @param positionId The position to add vTokens into
     * @param amount Vault tokens amount to deposit
     * @param encodedPermit2 Encoded function params (owner, permitSingle, signature) for `PERMIT2.permit()`
     * @param viaPermit2 If true then vTokens transferred via Permit2 else normal token transferFrom
     * @param forceTimelock Forcefully apply timelock to the position
     */
    function increasePosition(
        uint256 positionId,
        uint256 amount,
        bytes calldata encodedPermit2,
        bool viaPermit2,
        bool forceTimelock
    ) external;

    /**
     * @notice Withdraw vault tokens from the position. Penalty is deducted if position has not finished the timelock.
     *
     * @param positionId The position id to withdraw vault tokens from
     * @param vTokenShares Amount of vault token shares to burn
     * @param nftIds NFT tokenIds to redeem with the vault tokens withdrawn. If array is empty then only vault tokens transferred. Redeem fees (in ETH from msg.value) only paid for positions which were minted with vTokens
     * @param vTokenPremiumLimit The max net premium in vTokens the user is willing to pay to redeem nftIds, else tx reverts
     */
    function withdraw(
        uint256 positionId,
        uint256 vTokenShares,
        uint256[] calldata nftIds,
        uint256 vTokenPremiumLimit
    ) external payable;

    /**
     * @notice Combine underlying vToken and WETH balances from childPositions into parentPosition, if all of their timelocks ended. All positions must be for the same vault id.
     *
     * @param parentPositionId xNFT Position id that will receive the underlying balances from childPositions
     * @param childPositionIds Array of xNFT position ids to be combined
     */
    function combinePositions(
        uint256 parentPositionId,
        uint256[] calldata childPositionIds
    ) external;

    /**
     * @notice Receive WETH fees accumulated by multiple positions
     *
     * @param positionIds The positions to withdraw weth fees from
     */
    function collectWethFees(uint256[] calldata positionIds) external;

    /**
     * @dev Can only be called by feeDistributor. vToken rewards can be directly transferred to this contract without calling this function
     *
     * @param vaultId The vault id that should receive the rewards
     * @param wethAmount Amount of WETH to pull as rewards
     *
     * @return rewardsDistributed Returns false if the `totalVTokenShares` is zero for the given `vaultId`
     */
    function receiveWethRewards(
        uint256 vaultId,
        uint256 wethAmount
    ) external returns (bool rewardsDistributed);

    // =============================================================
    //                        ONLY OWNER WRITE
    // =============================================================

    function setTimelock(uint256 timelock_) external;

    function setEarlyWithdrawPenalty(
        uint256 earlyWithdrawPenaltyInWei_
    ) external;

    function setDescriptor(InventoryStakingDescriptor descriptor_) external;

    // =============================================================
    //                     PUBLIC / EXTERNAL VIEW
    // =============================================================

    /**
     * @notice Returns the worth of 10^18 vTokenShares in terms of the underlying vToken corresponding to the provided `vaultId`
     */
    function pricePerShareVToken(
        uint256 vaultId
    ) external view returns (uint256);

    /**
     * @notice Returns the current WETH balance for a given `positionId`
     */
    function wethBalance(uint256 positionId) external view returns (uint256);
}

File 45 of 89 : INFTXRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;

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

import {INonfungiblePositionManager} from "@uni-periphery/interfaces/INonfungiblePositionManager.sol";
import {SwapRouter} from "@uni-periphery/SwapRouter.sol";
import {IQuoterV2} from "@uni-periphery/interfaces/IQuoterV2.sol";
import {INFTXInventoryStakingV3} from "@src/interfaces/INFTXInventoryStakingV3.sol";
import {IPermitAllowanceTransfer} from "@src/interfaces/external/IPermitAllowanceTransfer.sol";

import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";

interface INFTXRouter {
    // =============================================================
    //                           CONSTANTS
    // =============================================================

    function WETH() external returns (address);

    function PERMIT2() external returns (IPermitAllowanceTransfer);

    function positionManager() external returns (INonfungiblePositionManager);

    function router() external returns (SwapRouter);

    function quoter() external returns (IQuoterV2);

    function nftxVaultFactory() external returns (INFTXVaultFactoryV3);

    function inventoryStaking() external returns (INFTXInventoryStakingV3);

    // =============================================================
    //                           STORAGE
    // =============================================================

    function lpTimelock() external returns (uint256);

    function earlyWithdrawPenaltyInWei() external returns (uint256);

    /// @notice the dust threshold for vTokens above which the additional vTokens minted during add/increase liquidity are put into inventory staking.
    function vTokenDustThreshold() external returns (uint256);

    // =============================================================
    //                            EVENTS
    // =============================================================

    event AddLiquidity(
        uint256 indexed positionId,
        uint256 vaultId,
        uint256 vTokensAmount,
        uint256[] nftIds,
        address pool,
        address recipient
    );

    event RemoveLiquidity(
        uint256 indexed positionId,
        uint256 vaultId,
        uint256 vTokenAmt,
        uint256 wethAmt
    );

    event IncreaseLiquidity(
        uint256 indexed positionId,
        uint256 vaultId,
        uint256 vTokensAmount,
        uint256[] nftIds
    );

    event SellNFTs(uint256 nftCount, uint256 ethReceived);

    event BuyNFTs(uint256 nftCount, uint256 ethSpent);

    // =============================================================
    //                            ERRORS
    // =============================================================

    error InvalidEarlyWithdrawPenalty();
    error InsufficientVTokens();
    error ETHValueLowerThanMin();
    error NoETHFundsNeeded();
    error NotPositionOwner();
    error ZeroLPTimelock();

    // =============================================================
    //                     PUBLIC / EXTERNAL WRITE
    // =============================================================

    struct AddLiquidityParams {
        uint256 vaultId;
        // amount of vTokens to deposit (can be 0)
        uint256 vTokensAmount;
        // array of nft ids to deposit (can be empty)
        uint256[] nftIds;
        // for ERC1155: quantity corresponding to each tokenId to deposit
        uint256[] nftAmounts;
        // ticks range to provide the liquidity into
        int24 tickLower;
        int24 tickUpper;
        // fee tier of the AMM pool
        uint24 fee;
        // the initial sqrt price (as a Q64.96) to set if a new pool is deployed
        uint160 sqrtPriceX96;
        // Minimum amount of vTokens to be provided as liquidity
        uint256 vTokenMin;
        // Minimum amount of Weth to be provided as liquidity
        uint256 wethMin;
        // deadline after which the tx fails
        uint256 deadline;
        // Forcefully apply timelock to the position
        bool forceTimelock;
        // Recipient address that receives the LP NFT
        address recipient;
    }

    /**
     * @notice Adds liquidity to the NFTX AMM. Deploys new AMM pool if doesn't already exist. User can addLiquidity via vTokens, NFTs or both. Timelock is set for the position if NFTs deposited.
     */
    function addLiquidity(
        AddLiquidityParams calldata params
    ) external payable returns (uint256 positionId);

    /**
     * @notice Adds liquidity to the NFTX AMM. Deploys new AMM pool if doesn't already exist. User can deposit via vTokens, NFTs or both. Timelock is set for the position if NFTs deposited.
     *
     * @param encodedPermit2 Encoded function params (owner, permitSingle, signature) for `PERMIT2.permit()` to permit vToken
     */
    function addLiquidityWithPermit2(
        AddLiquidityParams calldata params,
        bytes calldata encodedPermit2
    ) external payable returns (uint256 positionId);

    struct IncreaseLiquidityParams {
        // the liquidity position to update
        uint256 positionId;
        // vault id corresponding to the vTokens in this position
        uint256 vaultId;
        // amount of vTokens to deposit (can be 0)
        uint256 vTokensAmount;
        // array of nft ids to deposit (can be empty)
        uint256[] nftIds;
        // for ERC1155: quantity corresponding to each tokenId to deposit
        uint256[] nftAmounts;
        // Minimum amount of vTokens to be provided as liquidity
        uint256 vTokenMin;
        // Minimum amount of Weth to be provided as liquidity
        uint256 wethMin;
        // deadline after which the tx fails
        uint256 deadline;
        // Forcefully apply timelock to the position
        bool forceTimelock;
    }

    /**
     * @notice Increase liquidity of an existing position. User can deposit via vTokens, NFTs or both. Timelock is updated for the position if NFTs deposited.
     */
    function increaseLiquidity(
        IncreaseLiquidityParams calldata params
    ) external payable;

    /**
     * @notice Increase liquidity of an existing position. User can deposit via vTokens, NFTs or both. Timelock is updated for the position if NFTs deposited.
     *
     * @param encodedPermit2 Encoded function params (owner, permitSingle, signature) for `PERMIT2.permit()` to permit vToken
     */
    function increaseLiquidityWithPermit2(
        IncreaseLiquidityParams calldata params,
        bytes calldata encodedPermit2
    ) external payable;

    struct RemoveLiquidityParams {
        // the position id to withdraw liquidity from
        uint256 positionId;
        // vault id corresponding to the vTokens in this position
        uint256 vaultId;
        // array of nft ids to redeem with the vTokens (can be empty to just receive vTokens)
        uint256[] nftIds;
        // The max net premium in vTokens the user is willing to pay to redeem nftIds, else tx reverts
        uint256 vTokenPremiumLimit;
        // the liquidity amount to burn and withdraw
        uint128 liquidity;
        // Minimum amount of token0 to be withdrawn
        uint256 amount0Min;
        // Minimum amount of token1 to be withdrawn
        uint256 amount1Min;
        // deadline after which the tx fails
        uint256 deadline;
    }

    /**
     * Remove liquidity from position into ETH + vTokens or NFTs or a combination of both. ETH from the withdrawn liquidity and msg.value is used to pay for redeem fees if NFTs withdrawn.
     */
    function removeLiquidity(
        RemoveLiquidityParams calldata params
    ) external payable;

    struct SellNFTsParams {
        // vault id corresponding to the nfts being sold
        uint256 vaultId;
        // array of nft ids to sell
        uint256[] nftIds;
        // for ERC1155: quantity corresponding to each tokenId to sell
        uint256[] nftAmounts;
        // deadline after which the tx fails
        uint256 deadline;
        // the fee tier to execute the swap through
        uint24 fee;
        // minimum amount of ETH to receive after swap (without considering any mint fees)
        uint256 amountOutMinimum;
        // the price limit (as a Q64.96), if reached, to stop swapping
        uint160 sqrtPriceLimitX96;
    }

    /**
     * @notice Sell NFT ids into ETH via the given fee tier pool. Extra ETH sent as msg.value if the received WETH is insufficient to pay for the vault fees.
     */
    function sellNFTs(
        SellNFTsParams calldata params
    ) external payable returns (uint256 ethReceived);

    struct BuyNFTsParams {
        // vault id corresponding to the nfts being bought
        uint256 vaultId;
        // array of nft ids to buy
        uint256[] nftIds;
        // The max net premium in vTokens the user is willing to pay to redeem nftIds, else tx reverts
        uint256 vTokenPremiumLimit;
        // deadline after which the tx fails
        uint256 deadline;
        // the fee tier to execute the swap through
        uint24 fee;
        // the price limit (as a Q64.96), if reached, to stop swapping
        uint160 sqrtPriceLimitX96;
    }

    /**
     * @notice Buy NFT ids with ETH via the given fee tier pool. ETH sent as msg.value includes the amount to swap for vTokens + vault redeem fees (including premiums).
     */
    function buyNFTs(BuyNFTsParams calldata params) external payable;

    // =============================================================
    //                        ONLY OWNER WRITE
    // =============================================================

    /**
     * @param token ERC20 token address or address(0) in case of ETH
     */
    function rescueTokens(IERC20 token) external;

    function setLpTimelock(uint256 lpTimelock_) external;

    function setVTokenDustThreshold(uint256 vTokenDustThreshold_) external;

    function setEarlyWithdrawPenalty(
        uint256 earlyWithdrawPenaltyInWei_
    ) external;

    // =============================================================
    //                     PUBLIC / EXTERNAL VIEW
    // =============================================================

    /**
     * @dev This function is not gas efficient and should _not_ be called on chain.
     */
    function quoteBuyNFTs(
        address vtoken,
        uint256 nftsCount,
        uint24 fee,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 ethRequired);

    /**
     * @notice Get deployed pool address for vaultId. `exists` is false if pool doesn't exist. `vaultId` must be valid.
     */
    function getPoolExists(
        uint256 vaultId,
        uint24 fee
    ) external view returns (address pool, bool exists);

    /**
     * @notice Get deployed pool address for vToken. `exists` is false if pool doesn't exist.
     */
    function getPoolExists(
        address vToken_,
        uint24 fee
    ) external view returns (address pool, bool exists);

    /**
     * @notice Get deployed pool address for vToken. Reverts if pool doesn't exist
     */
    function getPool(
        address vToken_,
        uint24 fee
    ) external view returns (address pool);

    /**
     * @notice Compute the pool address corresponding to vToken
     */
    function computePool(
        address vToken_,
        uint24 fee
    ) external view returns (address);

    /**
     * @notice Checks if vToken is token0 or not
     */
    function isVToken0(address vtoken) external view returns (bool);
}

File 46 of 89 : INFTXVaultFactoryV3.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {IBeacon} from "@src/custom/proxy/IBeacon.sol";

interface INFTXVaultFactoryV3 is IBeacon {
    // =============================================================
    //                            STRUCTS
    // =============================================================

    struct VaultFees {
        bool active;
        uint64 mintFee;
        uint64 redeemFee;
        uint64 swapFee;
    }

    // =============================================================
    //                            VARIABLES
    // =============================================================

    function feeDistributor() external view returns (address);

    function eligibilityManager() external view returns (address);

    function excludedFromFees(address addr) external view returns (bool);

    function factoryMintFee() external view returns (uint64);

    function factoryRedeemFee() external view returns (uint64);

    function factorySwapFee() external view returns (uint64);

    function twapInterval() external view returns (uint32);

    function premiumDuration() external view returns (uint256);

    function premiumMax() external view returns (uint256);

    function depositorPremiumShare() external view returns (uint256);

    // =============================================================
    //                            EVENTS
    // =============================================================

    event NewFeeDistributor(address oldDistributor, address newDistributor);
    event FeeExclusion(address feeExcluded, bool excluded);
    event NewEligibilityManager(address oldEligManager, address newEligManager);
    event NewVault(
        uint256 indexed vaultId,
        address vaultAddress,
        address assetAddress,
        string name,
        string symbol
    );
    event UpdateVaultFees(
        uint256 vaultId,
        uint256 mintFee,
        uint256 redeemFee,
        uint256 swapFee
    );
    event DisableVaultFees(uint256 vaultId);
    event UpdateFactoryFees(
        uint256 mintFee,
        uint256 redeemFee,
        uint256 swapFee
    );
    event NewPremiumMax(uint256 premiumMax);
    event NewPremiumDuration(uint256 premiumDuration);
    event NewDepositorPremiumShare(uint256 depositorPremiumShare);
    event NewTwapInterval(uint32 twapInterval);

    // =============================================================
    //                            ERRORS
    // =============================================================

    error FeeDistributorNotSet();
    error VaultImplementationNotSet();
    error FeeExceedsLimit();
    error CallerIsNotVault();
    error ZeroTwapInterval();
    error DepositorPremiumShareExceedsLimit();
    error ZeroAddress();
    error ZeroAmountRequested();
    error NFTInventoryExceeded();

    // =============================================================
    //                           INIT
    // =============================================================

    function __NFTXVaultFactory_init(
        address vaultImpl,
        uint32 twapInterval_,
        uint256 premiumDuration_,
        uint256 premiumMax_,
        uint256 depositorPremiumShare_
    ) external;

    // =============================================================
    //                     ONLY PRIVILEGED WRITE
    // =============================================================

    function setFactoryFees(
        uint256 mintFee,
        uint256 redeemFee,
        uint256 swapFee
    ) external;

    function setVaultFees(
        uint256 vaultId,
        uint256 mintFee,
        uint256 redeemFee,
        uint256 swapFee
    ) external;

    function disableVaultFees(uint256 vaultId) external;

    function setFeeDistributor(address feeDistributor_) external;

    function setFeeExclusion(address excludedAddr, bool excluded) external;

    function setEligibilityManager(address eligibilityManager_) external;

    function setTwapInterval(uint32 twapInterval_) external;

    function setPremiumDuration(uint256 premiumDuration_) external;

    function setPremiumMax(uint256 premiumMax_) external;

    function setDepositorPremiumShare(uint256 depositorPremiumShare_) external;

    // =============================================================
    //                     PUBLIC / EXTERNAL WRITE
    // =============================================================

    function createVault(
        string calldata name,
        string calldata symbol,
        address assetAddress,
        bool is1155,
        bool allowAllItems
    ) external returns (uint256 vaultId);

    // =============================================================
    //                     PUBLIC / EXTERNAL VIEW
    // =============================================================

    function vaultFees(
        uint256 vaultId
    )
        external
        view
        returns (uint256 mintFee, uint256 redeemFee, uint256 swapFee);

    function isLocked(uint256 id) external view returns (bool);

    function vaultsForAsset(
        address asset
    ) external view returns (address[] memory);

    function allVaults() external view returns (address[] memory);

    function numVaults() external view returns (uint256);

    function vault(uint256 vaultId) external view returns (address);

    function computeVaultAddress(
        address assetAddress,
        string memory name,
        string memory symbol
    ) external view returns (address);

    function getTwapX96(address pool) external view returns (uint256 priceX96);

    /**
     * @notice Get vToken premium corresponding for a tokenId in the vault
     *
     * @param tokenId token id to calculate the premium for
     * @return premium Premium in vTokens
     * @return depositor Depositor that receives a share of this premium
     */
    function getVTokenPremium721(
        uint256 vaultId,
        uint256 tokenId
    ) external view returns (uint256 premium, address depositor);

    /**
     * @notice Get vToken premium corresponding for a tokenId in the vault
     *
     * @param tokenId token id to calculate the premium for
     * @param amount ERC1155 amount of tokenId to redeem
     *
     * @return totalPremium Total premium in vTokens
     * @return premiums Premiums corresponding to each depositor
     * @return depositors Depositors that receive a share from the `premiums`
     */
    function getVTokenPremium1155(
        uint256 vaultId,
        uint256 tokenId,
        uint256 amount
    )
        external
        view
        returns (
            uint256 totalPremium,
            uint256[] memory premiums,
            address[] memory depositors
        );
}

File 47 of 89 : INFTXVaultV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IWETH9} from "@uni-periphery/interfaces/external/IWETH9.sol";
import {INFTXEligibility} from "@src/interfaces/INFTXEligibility.sol";
import {IERC20Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol";
import {IERC721Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC721/IERC721Upgradeable.sol";
import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";
import {IERC1155Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC1155/IERC1155Upgradeable.sol";
import {IERC3156FlashBorrowerUpgradeable} from "@src/custom/tokens/ERC20/ERC20FlashMintUpgradeable.sol";

interface INFTXVaultV3 is IERC20Upgradeable {
    // =============================================================
    //                            STRUCTS
    // =============================================================

    struct TokenDepositInfo {
        uint48 timestamp;
        address depositor;
    }

    struct DepositInfo1155 {
        uint256 qty;
        address depositor;
        uint48 timestamp;
    }

    enum TokenType {
        ERC20,
        ERC721,
        ERC1155
    }

    // =============================================================
    //                           CONSTANTS
    // =============================================================

    function WETH() external view returns (IWETH9);

    // only set during initialization

    function assetAddress() external view returns (address);

    function vaultFactory() external view returns (INFTXVaultFactoryV3);

    function vaultId() external view returns (uint256);

    function is1155() external view returns (bool);

    // =============================================================
    //                          VARIABLES
    // =============================================================

    function manager() external view returns (address);

    function eligibilityStorage() external view returns (INFTXEligibility);

    function allowAllItems() external view returns (bool);

    function enableMint() external view returns (bool);

    function enableRedeem() external view returns (bool);

    function enableSwap() external view returns (bool);

    function tokenDepositInfo(
        uint256 tokenId
    ) external view returns (uint48 timestamp, address depositor);

    function depositInfo1155(
        uint256 tokenId,
        uint256 index
    ) external view returns (uint256 qty, address depositor, uint48 timestamp);

    function pointerIndex1155(uint256 tokenId) external view returns (uint256);

    // =============================================================
    //                            EVENTS
    // =============================================================

    event VaultInit(
        uint256 indexed vaultId,
        address assetAddress,
        bool is1155,
        bool allowAllItems
    );

    event ManagerSet(address manager);
    event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr);

    event EnableMintUpdated(bool enabled);
    event EnableRedeemUpdated(bool enabled);
    event EnableSwapUpdated(bool enabled);

    event Minted(
        uint256[] nftIds,
        uint256[] amounts,
        address to,
        address depositor
    );
    event Redeemed(uint256[] specificIds, address to);
    event Swapped(
        uint256[] nftIds,
        uint256[] amounts,
        uint256[] specificIds,
        address to,
        address depositor
    );
    event PremiumShared(address depositor, uint256 wethPremium);
    event FeesDistributed(uint256 wethFees);
    event VaultShutdown(
        address assetAddress,
        uint256 numItems,
        address recipient
    );

    // =============================================================
    //                            ERRORS
    // =============================================================

    error ZeroAddress();
    error MintingDisabled();
    error RedeemDisabled();
    error SwapDisabled();
    error InsufficientETHSent();
    error TransferAmountIsZero();
    error TokenLengthMismatch();
    error EligibilityAlreadySet();
    error NotEligible();
    error NotNFTOwner();
    error NFTAlreadyOwned();
    error NotOwner();
    error NotManager();
    error Paused();
    error TooManyItems();
    error IdNotFound();
    error HoldingsUpdationFailed();
    error InvalidToken();
    error PremiumLimitExceeded();
    error ETHSent();
    error CantRescueAssetToken();

    // =============================================================
    //                           INIT
    // =============================================================

    function __NFTXVault_init(
        string calldata name_,
        string calldata symbol_,
        address assetAddress_,
        bool is1155_,
        bool allowAllItems_
    ) external;

    // =============================================================
    //                     ONLY PRIVILEGED WRITE
    // =============================================================

    /**
     * @notice Sets manager to zero address
     */
    function finalizeVault() external;

    function setVaultMetadata(
        string memory name_,
        string memory symbol_
    ) external;

    function setVaultFeatures(
        bool enableMint_,
        bool enableRedeem_,
        bool enableSwap_
    ) external;

    function setFees(
        uint256 mintFee_,
        uint256 redeemFee_,
        uint256 swapFee_
    ) external;

    /**
     * @notice Disables custom vault fees. Vault fees reverts back to the global vault fees.
     */
    function disableVaultFees() external;

    /**
     * @notice Allows for an easy setup of any eligibility module contract from the EligibilityManager.
     *
     * @param moduleIndex Index of the module to deploy
     * @param initData ABI encoded parameters for the desired module
     */
    function deployEligibilityStorage(
        uint256 moduleIndex,
        bytes calldata initData
    ) external returns (address);

    /**
     * @notice Set new manager. The manager has control over options like fees and features
     */
    function setManager(address _manager) external;

    // =============================================================
    //                     ONLY OWNER WRITE
    // =============================================================

    function rescueTokens(
        TokenType tt,
        address token,
        uint256[] calldata ids,
        uint256[] calldata amounts
    ) external;

    function shutdown(address recipient, uint256[] calldata tokenIds) external;

    // =============================================================
    //                     PUBLIC / EXTERNAL WRITE
    // =============================================================

    /**
     * @notice Mints vault tokens in exchange for depositing NFTs. Mint fees is paid in ETH (via msg.value)
     *
     * @param tokenIds The token ids to deposit
     * @param amounts For ERC1155: quantity corresponding to each tokenId to deposit
     * @param depositor Depositor address that should receive premiums for the `tokenIds` deposited here
     * @param to Recipient address for the vTokens
     */
    function mint(
        uint256[] calldata tokenIds,
        uint256[] calldata amounts,
        address depositor,
        address to
    ) external payable returns (uint256 vTokensMinted);

    /**
     * @notice Redeem vault tokens for the underlying NFTs. Redeem fees is paid in ETH (via msg.value) or WETH
     *
     * @param idsOut NFT ids to withdraw
     * @param to Recipient address for the NFTs
     * @param wethAmount if vault fees should be deducted in WETH instead of ETH (msg.value should be 0 here)
     * @param vTokenPremiumLimit The max net premium in vTokens the user is willing to pay, else tx reverts
     * @param forceFees forcefully deduct fees even if sender is on the exclude list
     *
     * @return ethFees The ETH fees charged
     */
    function redeem(
        uint256[] calldata idsOut,
        address to,
        uint256 wethAmount,
        uint256 vTokenPremiumLimit,
        bool forceFees
    ) external payable returns (uint256 ethFees);

    /**
     * @notice Swap `idsIn` of NFTs into `idsOut` from the vault. Swap fees is paid in ETH (via msg.value)
     *
     * @param idsIn NFT ids to sell
     * @param amounts For ERC1155: quantity corresponding to each tokenId to sell
     * @param idsOut NFT ids to buy
     * @param depositor Depositor address that should receive premiums for the `idsIn` deposited here
     * @param to Recipient address for the NFTs
     * @param vTokenPremiumLimit The max net premium in vTokens the user is willing to pay, else tx reverts
     * @param forceFees forcefully deduct fees even if sender is on the exclude list
     *
     * @return ethFees The ETH fees charged
     */
    function swap(
        uint256[] calldata idsIn,
        uint256[] calldata amounts,
        uint256[] calldata idsOut,
        address depositor,
        address to,
        uint256 vTokenPremiumLimit,
        bool forceFees
    ) external payable returns (uint256 ethFees);

    /**
     * @notice Performs a flash loan. New tokens are minted and sent to the
     * `receiver`, who is required to implement the {IERC3156FlashBorrower}
     * interface. By the end of the flash loan, the receiver is expected to own
     * amount + fee tokens and have them approved back to the token contract itself so
     * they can be burned.
     *
     * @param receiver The receiver of the flash loan. Should implement the
     * {IERC3156FlashBorrower-onFlashLoan} interface.
     * @param token The token to be flash loaned. Only `address(this)` is
     * supported.
     * @param amount The amount of tokens to be loaned.
     * @param data An arbitrary datafield that is passed to the receiver.
     *
     * @return `true` if the flash loan was successful.
     */
    function flashLoan(
        IERC3156FlashBorrowerUpgradeable receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);

    // =============================================================
    //                     PUBLIC / EXTERNAL VIEW
    // =============================================================

    function nftIdAt(uint256 holdingsIndex) external view returns (uint256);

    function allHoldings() external view returns (uint256[] memory);

    function totalHoldings() external view returns (uint256);

    function holdingsContains(uint256 tokenId) external view returns (bool);

    /**
     * @notice Vault Fees in terms of vault tokens
     */
    function vaultFees()
        external
        view
        returns (uint256 mintFee, uint256 redeemFee, uint256 swapFee);

    function allValidNFTs(
        uint256[] calldata tokenIds
    ) external view returns (bool);

    /**
     * @notice Calculate ETH amount corresponding to a given vToken amount, calculated via TWAP from the NFTX AMM
     */
    function vTokenToETH(uint256 vTokenAmount) external view returns (uint256);

    /**
     * @notice Length of depositInfo1155 array for a given `tokenId`
     */
    function depositInfo1155Length(
        uint256 tokenId
    ) external view returns (uint256);

    function version() external pure returns (string memory);
}

File 48 of 89 : ITimelockExcludeList.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface ITimelockExcludeList {
    function isExcluded(
        address addr,
        uint256 vaultId
    ) external view returns (bool);
}

File 49 of 89 : IPermitAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 50 of 89 : TransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

library TransferLib {
    using SafeERC20 for IERC20;

    address internal constant CRYPTO_PUNKS =
        0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
    address internal constant CRYPTO_KITTIES =
        0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;

    // Errors
    error UnableToSendETH();
    error NotNFTOwner();

    function transferFromERC721(
        address assetAddress,
        address to,
        uint256[] memory nftIds
    ) internal {
        for (uint256 i; i < nftIds.length; ) {
            _transferFromERC721(assetAddress, nftIds[i], to);

            if (assetAddress == CRYPTO_PUNKS) {
                _approveCryptoPunkERC721(nftIds[i], to);
            }

            unchecked {
                ++i;
            }
        }
    }

    /// @dev Setting max allowance to save gas on subsequent calls.
    function maxApprove(
        address token,
        address spender,
        uint256 amount
    ) internal {
        uint256 allowance = IERC20(token).allowance(address(this), spender);

        if (amount > allowance) {
            IERC20(token).safeApprove(spender, type(uint256).max);
        }
    }

    /// @dev Setting max allowance to save gas on subsequent calls without using safeApprove. Use it only where the tokens are known.
    function unSafeMaxApprove(
        address token,
        address spender,
        uint256 amount
    ) internal {
        uint256 allowance = IERC20(token).allowance(address(this), spender);

        if (amount > allowance) {
            // avoids reading allowance again, which is the case with safeApprove
            IERC20(token).approve(spender, type(uint256).max);
        }
    }

    function transferETH(address to, uint256 amount) internal {
        (bool success, ) = payable(to).call{value: amount}("");
        if (!success) revert UnableToSendETH();
    }

    /**
     * @notice Transfers sender's ERC721 tokens to a specified recipient.
     *
     * @param assetAddr Address of the asset being transferred
     * @param tokenId The ID of the token being transferred
     * @param to The address the token is being transferred to
     */

    function _transferFromERC721(
        address assetAddr,
        uint256 tokenId,
        address to
    ) private {
        bytes memory data;

        if (assetAddr != CRYPTO_PUNKS && assetAddr != CRYPTO_KITTIES) {
            // We push to the vault to avoid an unneeded transfer.
            data = abi.encodeWithSignature(
                "safeTransferFrom(address,address,uint256)",
                msg.sender,
                to,
                tokenId
            );
        } else if (assetAddr == CRYPTO_PUNKS) {
            // Fix here for frontrun attack.
            bytes memory punkIndexToAddress = abi.encodeWithSignature(
                "punkIndexToAddress(uint256)",
                tokenId
            );
            (bool checkSuccess, bytes memory result) = CRYPTO_PUNKS.staticcall(
                punkIndexToAddress
            );
            address nftOwner = abi.decode(result, (address));

            if (!checkSuccess || nftOwner != msg.sender) revert NotNFTOwner();
            data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
        } else {
            // CRYPTO_KITTIES
            data = abi.encodeWithSignature(
                "transferFrom(address,address,uint256)",
                msg.sender,
                address(this),
                tokenId
            );
        }

        (bool success, bytes memory resultData) = address(assetAddr).call(data);
        require(success, string(resultData));
    }

    /**
     * @notice Approves our Cryptopunk ERC721 tokens to be transferred.
     *
     * @dev This is only required to provide special logic for Cryptopunks.
     *
     * @param tokenId The ID of the token being transferred
     * @param to The address the token is being transferred to
     */

    function _approveCryptoPunkERC721(uint256 tokenId, address to) private {
        bytes memory data = abi.encodeWithSignature(
            "offerPunkForSaleToAddress(uint256,uint256,address)",
            tokenId,
            0,
            to
        );
        (bool success, bytes memory resultData) = CRYPTO_PUNKS.call(data);
        require(success, string(resultData));
    }
}

File 51 of 89 : IUniswapV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token 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 pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    error InvalidRewardTierCardinality();

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    function feeDistributor() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice The CardinalityNext value to be set for the RewardFeeTier Pools
    function rewardTierCardinality() external view returns (uint16);

    function setFeeDistributor(address feeDistributor_) external;

    function setRewardTierCardinality(uint16 rewardTierCardinality_) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}

File 52 of 89 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IUniswapV3PoolImmutables} from "./pool/IUniswapV3PoolImmutables.sol";
import {IUniswapV3PoolState} from "./pool/IUniswapV3PoolState.sol";
import {IUniswapV3PoolDerivedState} from "./pool/IUniswapV3PoolDerivedState.sol";
import {IUniswapV3PoolActions} from "./pool/IUniswapV3PoolActions.sol";
import {IUniswapV3PoolOwnerActions} from "./pool/IUniswapV3PoolOwnerActions.sol";
import {IUniswapV3PoolErrors} from "./pool/IUniswapV3PoolErrors.sol";
import {IUniswapV3PoolEvents} from "./pool/IUniswapV3PoolEvents.sol";

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap 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 IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolErrors,
    IUniswapV3PoolEvents
{
    function __UniswapV3PoolUpgradeable_init(
        address factory_,
        address token0_,
        address token1_,
        uint24 fee_,
        int24 tickSpacing_,
        uint16 observationCardinalityNext_
    ) external;
}

File 53 of 89 : IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 54 of 89 : IUniswapV3PoolActions.sol
// 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 IUniswapV3PoolActions {
    /// @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
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// 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 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 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 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 Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @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 Distributes the received vault fees among the current LPs, proportional to their liquidity contribution
    /// @dev Can only be called by feeDistributor, after it sends the reward tokens to this pool
    /// @param rewardsAmount The amount of reward tokens to distribute
    /// @param isToken0 If reward token is token0 then true, else false
    function distributeRewards(uint256 rewardsAmount, bool isToken0) external;

    /// @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 IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @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;
}

File 55 of 89 : IUniswapV3PoolDerivedState.sol
// 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 IUniswapV3PoolDerivedState {
    /// @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
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @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.
    /// @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 secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

File 56 of 89 : IUniswapV3PoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
    error LOK();
    error TLU();
    error TLM();
    error TUM();
    error AI();
    error M0();
    error M1();
    error AS();
    error IIA();
    error L();
    error F0();
    error F1();
}

File 57 of 89 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 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 price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 58 of 89 : IUniswapV3PoolImmutables.sol
// 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 IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() 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);
}

File 59 of 89 : IUniswapV3PoolOwnerActions.sol
// 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 IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) 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);
}

File 60 of 89 : IUniswapV3PoolState.sol
// 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 IUniswapV3PoolState {
    /// @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
    /// @return 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.
    /// @return observationIndex The index of the last oracle observation that was written,
    /// @return observationCardinality The current maximum number of observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// @return 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 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
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @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
    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// @return 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,
            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
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

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

File 61 of 89 : SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param y The uint256 to be downcasted
    /// @return z The downcasted integer, now type uint160
    function toUint160(uint256 y) internal pure returns (uint160 z) {
        require((z = uint160(y)) == y);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param y The int256 to be downcasted
    /// @return z The downcasted integer, now type int128
    function toInt128(int256 y) internal pure returns (int128 z) {
        require((z = int128(y)) == y);
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param y The uint256 to be casted
    /// @return z The casted integer, now type int256
    function toInt256(uint256 y) internal pure returns (int256 z) {
        require(y < 2**255);
        z = int256(y);
    }
}

File 62 of 89 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    error T();
    error R();

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert T();

            uint256 ratio = absTick & 0x1 != 0
                ? 0xfffcb933bd6fad37aa2d162d1a594001
                : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

            if (tick > 0) ratio = type(uint256).max / ratio;

            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // second inequality must be < because the price can never reach the price at the max tick
            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
            uint256 ratio = uint256(sqrtPriceX96) << 32;

            uint256 r = ratio;
            uint256 msb = 0;

            assembly {
                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(5, gt(r, 0xFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(4, gt(r, 0xFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(3, gt(r, 0xFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(2, gt(r, 0xF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(1, gt(r, 0x3))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := gt(r, 0x1)
                msb := or(msb, f)
            }

            if (msb >= 128) r = ratio >> (msb - 127);
            else r = ratio << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

File 63 of 89 : SwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/libraries/SafeCast.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

import './interfaces/ISwapRouter.sol';
import './base/PeripheryImmutableState.sol';
import './base/PeripheryValidation.sol';
import './base/PeripheryPaymentsWithFee.sol';
import './base/Multicall.sol';
import './base/SelfPermit.sol';
import './libraries/Path.sol';
import './libraries/PoolAddress.sol';
import './libraries/CallbackValidation.sol';
import './interfaces/external/IWETH9.sol';

/// @title Uniswap V3 Swap Router
/// @notice Router for stateless execution of swaps against Uniswap V3
contract SwapRouter is
    ISwapRouter,
    PeripheryImmutableState,
    PeripheryValidation,
    PeripheryPaymentsWithFee,
    Multicall,
    SelfPermit
{
    using Path for bytes;
    using SafeCast for uint256;

    /// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap
    /// can never actually be this value
    uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max;

    /// @dev Transient storage variable used for returning the computed amount in for an exact output swap.
    uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED;

    constructor(address _factory, address _WETH9) PeripheryImmutableState(_factory, _WETH9) {}

    /// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist.
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) private view returns (IUniswapV3Pool) {
        return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
    }

    struct SwapCallbackData {
        bytes path;
        address payer;
    }

    /// @inheritdoc IUniswapV3SwapCallback
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata _data
    ) external override {
        require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
        SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
        (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
        CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);

        (bool isExactInput, uint256 amountToPay) = amount0Delta > 0
            ? (tokenIn < tokenOut, uint256(amount0Delta))
            : (tokenOut < tokenIn, uint256(amount1Delta));
        if (isExactInput) {
            pay(tokenIn, data.payer, msg.sender, amountToPay);
        } else {
            // either initiate the next swap or pay
            if (data.path.hasMultiplePools()) {
                data.path = data.path.skipToken();
                exactOutputInternal(amountToPay, msg.sender, 0, data);
            } else {
                amountInCached = amountToPay;
                tokenIn = tokenOut; // swap in/out because exact output swaps are reversed
                pay(tokenIn, data.payer, msg.sender, amountToPay);
            }
        }
    }

    /// @dev Performs a single exact input swap
    function exactInputInternal(
        uint256 amountIn,
        address recipient,
        uint160 sqrtPriceLimitX96,
        SwapCallbackData memory data
    ) private returns (uint256 amountOut) {
        // allow swapping to the router address with address 0
        if (recipient == address(0)) recipient = address(this);

        (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();

        bool zeroForOne = tokenIn < tokenOut;

        (int256 amount0, int256 amount1) = getPool(tokenIn, tokenOut, fee).swap(
            recipient,
            zeroForOne,
            amountIn.toInt256(),
            sqrtPriceLimitX96 == 0
                ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
                : sqrtPriceLimitX96,
            abi.encode(data)
        );

        return uint256(-(zeroForOne ? amount1 : amount0));
    }

    /// @inheritdoc ISwapRouter
    function exactInputSingle(ExactInputSingleParams calldata params)
        external
        payable
        override
        checkDeadline(params.deadline)
        returns (uint256 amountOut)
    {
        amountOut = exactInputInternal(
            params.amountIn,
            params.recipient,
            params.sqrtPriceLimitX96,
            SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender})
        );
        require(amountOut >= params.amountOutMinimum, 'Too little received');
    }

    /// @inheritdoc ISwapRouter
    function exactInput(ExactInputParams memory params)
        external
        payable
        override
        checkDeadline(params.deadline)
        returns (uint256 amountOut)
    {
        address payer = msg.sender; // msg.sender pays for the first hop

        while (true) {
            bool hasMultiplePools = params.path.hasMultiplePools();

            // the outputs of prior swaps become the inputs to subsequent ones
            params.amountIn = exactInputInternal(
                params.amountIn,
                hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies
                0,
                SwapCallbackData({
                    path: params.path.getFirstPool(), // only the first pool in the path is necessary
                    payer: payer
                })
            );

            // decide whether to continue or terminate
            if (hasMultiplePools) {
                payer = address(this); // at this point, the caller has paid
                params.path = params.path.skipToken();
            } else {
                amountOut = params.amountIn;
                break;
            }
        }

        require(amountOut >= params.amountOutMinimum, 'Too little received');
    }

    /// @dev Performs a single exact output swap
    function exactOutputInternal(
        uint256 amountOut,
        address recipient,
        uint160 sqrtPriceLimitX96,
        SwapCallbackData memory data
    ) private returns (uint256 amountIn) {
        // allow swapping to the router address with address 0
        if (recipient == address(0)) recipient = address(this);

        (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool();

        bool zeroForOne = tokenIn < tokenOut;

        (int256 amount0Delta, int256 amount1Delta) = getPool(tokenIn, tokenOut, fee).swap(
            recipient,
            zeroForOne,
            -amountOut.toInt256(),
            sqrtPriceLimitX96 == 0
                ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
                : sqrtPriceLimitX96,
            abi.encode(data)
        );

        uint256 amountOutReceived;
        (amountIn, amountOutReceived) = zeroForOne
            ? (uint256(amount0Delta), uint256(-amount1Delta))
            : (uint256(amount1Delta), uint256(-amount0Delta));
        // it's technically possible to not receive the full output amount,
        // so if no price limit has been specified, require this possibility away
        if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut);
    }

    /// @inheritdoc ISwapRouter
    function exactOutputSingle(ExactOutputSingleParams calldata params)
        external
        payable
        override
        checkDeadline(params.deadline)
        returns (uint256 amountIn)
    {
        // avoid an SLOAD by using the swap return data
        amountIn = exactOutputInternal(
            params.amountOut,
            params.recipient,
            params.sqrtPriceLimitX96,
            SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender})
        );

        require(amountIn <= params.amountInMaximum, 'Too much requested');
        // has to be reset even though we don't use it in the single hop case
        amountInCached = DEFAULT_AMOUNT_IN_CACHED;
    }

    /// @inheritdoc ISwapRouter
    function exactOutput(ExactOutputParams calldata params)
        external
        payable
        override
        checkDeadline(params.deadline)
        returns (uint256 amountIn)
    {
        // it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output
        // swap, which happens first, and subsequent swaps are paid for within nested callback frames
        exactOutputInternal(
            params.amountOut,
            params.recipient,
            0,
            SwapCallbackData({path: params.path, payer: msg.sender})
        );

        amountIn = amountInCached;
        require(amountIn <= params.amountInMaximum, 'Too much requested');
        amountInCached = DEFAULT_AMOUNT_IN_CACHED;
    }
}

File 64 of 89 : BlockTimestamp.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

/// @title Function for getting block timestamp
/// @dev Base contract that is overridden for tests
abstract contract BlockTimestamp {
    /// @dev Method that exists purely to be overridden for tests
    /// @return The current block timestamp
    function _blockTimestamp() internal view virtual returns (uint256) {
        return block.timestamp;
    }
}

File 65 of 89 : Multicall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;
pragma abicoder v2;

import '../interfaces/IMulticall.sol';

/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
    /// @inheritdoc IMulticall
    function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            (bool success, bytes memory result) = address(this).delegatecall(data[i]);

            if (!success) {
                // Next 5 lines from https://ethereum.stackexchange.com/a/83577
                if (result.length < 68) revert();
                assembly {
                    result := add(result, 0x04)
                }
                revert(abi.decode(result, (string)));
            }

            results[i] = result;
        }
    }
}

File 66 of 89 : PeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import '../interfaces/IPeripheryImmutableState.sol';

/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract PeripheryImmutableState is IPeripheryImmutableState {
    /// @inheritdoc IPeripheryImmutableState
    address public immutable override factory;
    /// @inheritdoc IPeripheryImmutableState
    address public immutable override WETH9;

    constructor(address _factory, address _WETH9) {
        factory = _factory;
        WETH9 = _WETH9;
    }
}

File 67 of 89 : PeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

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

import '../interfaces/IPeripheryPayments.sol';
import '../interfaces/external/IWETH9.sol';

import '../libraries/TransferHelper.sol';

import './PeripheryImmutableState.sol';

abstract contract PeripheryPayments is IPeripheryPayments, PeripheryImmutableState {
    receive() external payable {
        require(msg.sender == WETH9, 'Not WETH9');
    }

    /// @inheritdoc IPeripheryPayments
    function unwrapWETH9(uint256 amountMinimum, address recipient) public payable override {
        uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
        require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');

        if (balanceWETH9 > 0) {
            IWETH9(WETH9).withdraw(balanceWETH9);
            TransferHelper.safeTransferETH(recipient, balanceWETH9);
        }
    }

    /// @inheritdoc IPeripheryPayments
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) public payable override {
        uint256 balanceToken = IERC20(token).balanceOf(address(this));
        require(balanceToken >= amountMinimum, 'Insufficient token');

        if (balanceToken > 0) {
            TransferHelper.safeTransfer(token, recipient, balanceToken);
        }
    }

    /// @inheritdoc IPeripheryPayments
    function refundETH() external payable override {
        if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
    }

    /// @inheritdoc IPeripheryPayments
    function refundETH(address receiver) external payable override {
        if (address(this).balance > 0) TransferHelper.safeTransferETH(receiver, address(this).balance);
    }

    /// @param token The token to pay
    /// @param payer The entity that must pay
    /// @param recipient The entity that will receive payment
    /// @param value The amount to pay
    function pay(
        address token,
        address payer,
        address recipient,
        uint256 value
    ) internal {
        if (token == WETH9 && address(this).balance >= value) {
            // pay with WETH9
            IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
            IWETH9(WETH9).transfer(recipient, value);
        } else if (payer == address(this)) {
            // pay with tokens already in the contract (for the exact input multihop case)
            TransferHelper.safeTransfer(token, recipient, value);
        } else {
            // pull payment
            TransferHelper.safeTransferFrom(token, payer, recipient, value);
        }
    }
}

File 68 of 89 : PeripheryPaymentsWithFee.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

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

import './PeripheryPayments.sol';
import '../interfaces/IPeripheryPaymentsWithFee.sol';

import '../interfaces/external/IWETH9.sol';
import '../libraries/TransferHelper.sol';

abstract contract PeripheryPaymentsWithFee is PeripheryPayments, IPeripheryPaymentsWithFee {
    /// @inheritdoc IPeripheryPaymentsWithFee
    function unwrapWETH9WithFee(
        uint256 amountMinimum,
        address recipient,
        uint256 feeBips,
        address feeRecipient
    ) public payable override {
        require(feeBips > 0 && feeBips <= 100);

        uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
        require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');

        if (balanceWETH9 > 0) {
            IWETH9(WETH9).withdraw(balanceWETH9);
            uint256 feeAmount = (balanceWETH9 * feeBips) / 10_000;
            if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount);
            TransferHelper.safeTransferETH(recipient, balanceWETH9 - feeAmount);
        }
    }

    /// @inheritdoc IPeripheryPaymentsWithFee
    function sweepTokenWithFee(
        address token,
        uint256 amountMinimum,
        address recipient,
        uint256 feeBips,
        address feeRecipient
    ) public payable override {
        require(feeBips > 0 && feeBips <= 100);

        uint256 balanceToken = IERC20(token).balanceOf(address(this));
        require(balanceToken >= amountMinimum, 'Insufficient token');

        if (balanceToken > 0) {
            uint256 feeAmount = (balanceToken * feeBips) / 10_000;
            if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount);
            TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount);
        }
    }
}

File 69 of 89 : PeripheryValidation.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import './BlockTimestamp.sol';

abstract contract PeripheryValidation is BlockTimestamp {
    modifier checkDeadline(uint256 deadline) {
        require(_blockTimestamp() <= deadline, 'Transaction too old');
        _;
    }
}

File 70 of 89 : SelfPermit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol';

import '../interfaces/ISelfPermit.sol';
import '../interfaces/external/IERC20PermitAllowed.sol';

/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
/// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
/// that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit {
    /// @inheritdoc ISelfPermit
    function selfPermit(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public payable override {
        IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s);
    }

    /// @inheritdoc ISelfPermit
    function selfPermitIfNecessary(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable override {
        if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
    }

    /// @inheritdoc ISelfPermit
    function selfPermitAllowed(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public payable override {
        IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
    }

    /// @inheritdoc ISelfPermit
    function selfPermitAllowedIfNecessary(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable override {
        if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
            selfPermitAllowed(token, nonce, expiry, v, r, s);
    }
}

File 71 of 89 : IERC721Permit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

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

/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
    /// @notice The permit typehash used in the permit signature
    /// @return The typehash for the permit
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /// @notice The domain separator used in the permit signature
    /// @return The domain seperator used in encoding of permit signature
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}

File 72 of 89 : IMulticall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

File 73 of 89 : INonfungiblePositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";

import "./IPoolInitializer.sol";
import "./IERC721Permit.sol";
import "./IPeripheryPayments.sol";
import "./IPeripheryImmutableState.sol";
import "../libraries/PoolAddress.sol";

/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
    IPoolInitializer,
    IPeripheryPayments,
    IPeripheryImmutableState,
    IERC721Metadata,
    IERC721Enumerable,
    IERC721Permit
{
    /// @notice Emitted when liquidity is increased for a position NFT
    /// @dev Also emitted when a token is minted
    /// @param tokenId The ID of the token for which liquidity was increased
    /// @param liquidity The amount by which liquidity for the NFT position was increased
    /// @param amount0 The amount of token0 that was paid for the increase in liquidity
    /// @param amount1 The amount of token1 that was paid for the increase in liquidity
    event IncreaseLiquidity(
        uint256 indexed tokenId,
        uint128 liquidity,
        uint256 amount0,
        uint256 amount1
    );
    /// @notice Emitted when liquidity is decreased for a position NFT
    /// @param tokenId The ID of the token for which liquidity was decreased
    /// @param liquidity The amount by which liquidity for the NFT position was decreased
    /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
    /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
    event DecreaseLiquidity(
        uint256 indexed tokenId,
        uint128 liquidity,
        uint256 amount0,
        uint256 amount1
    );
    /// @notice Emitted when tokens are collected for a position NFT
    /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
    /// @param tokenId The ID of the token for which underlying tokens were collected
    /// @param recipient The address of the account that received the collected tokens
    /// @param amount0 The amount of token0 owed to the position that was collected
    /// @param amount1 The amount of token1 owed to the position that was collected
    event Collect(
        uint256 indexed tokenId,
        address recipient,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Returns the timestamp, till when the position is timelocked for
    function lockedUntil(uint256 tokenId) external view returns (uint256);

    /// @notice Net timelock for position
    function timelock(uint256 tokenId) external view returns (uint256);

    /// @notice Check if a particular address is excluded from timelock and hence can withdraw from the position early
    function timelockExcluded(address addr) external view returns (bool);

    /// @dev Only callable by NFTXRouter
    function setLockedUntil(
        uint256 tokenId,
        uint256 lockedUntil,
        uint256 timelock
    ) external;

    function setTimelockExcluded(address addr, bool isExcluded) external;

    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return nonce The nonce for permits
    /// @return operator The address that is approved for spending
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return fee The fee associated with the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(
        uint256 tokenId
    )
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// @notice Creates a new position wrapped in a NFT
    /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
    /// a method does not exist, i.e. the pool is assumed to be initialized.
    /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
    /// @return tokenId The ID of the token that represents the minted position
    /// @return liquidity The amount of liquidity for this position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mint(
        MintParams calldata params
    )
        external
        payable
        returns (
            uint256 tokenId,
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        );

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
    /// @param params tokenId The ID of the token for which liquidity is being increased,
    /// amount0Desired The desired amount of token0 to be spent,
    /// amount1Desired The desired amount of token1 to be spent,
    /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
    /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return liquidity The new liquidity amount as a result of the increase
    /// @return amount0 The amount of token0 to acheive resulting liquidity
    /// @return amount1 The amount of token1 to acheive resulting liquidity
    function increaseLiquidity(
        IncreaseLiquidityParams calldata params
    )
        external
        payable
        returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Decreases the amount of liquidity in a position and accounts it to the position
    /// @param params tokenId The ID of the token for which liquidity is being decreased,
    /// amount The amount by which liquidity will be decreased,
    /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
    /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return amount0 The amount of token0 accounted to the position's tokens owed
    /// @return amount1 The amount of token1 accounted to the position's tokens owed
    function decreaseLiquidity(
        DecreaseLiquidityParams calldata params
    ) external payable returns (uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
    /// @param params tokenId The ID of the NFT for which tokens are being collected,
    /// recipient The account that should receive the tokens,
    /// amount0Max The maximum amount of token0 to collect,
    /// amount1Max The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        CollectParams calldata params
    ) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
    /// must be collected first.
    /// @param tokenId The ID of the token that is being burned
    function burn(uint256 tokenId) external payable;
}

File 74 of 89 : IPeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
    /// @return Returns the address of the Uniswap V3 factory
    function factory() external view returns (address);

    /// @return Returns the address of WETH9
    function WETH9() external view returns (address);
}

File 75 of 89 : IPeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    /// @param amountMinimum The minimum amount of WETH9 to unwrap
    /// @param recipient The address receiving ETH
    function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;

    /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH() external payable;

    /// @notice Refunds any ETH balance held by this contract to the `receiver`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH(address receiver) external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    /// @param token The contract address of the token which will be transferred to `recipient`
    /// @param amountMinimum The minimum amount of token required for a transfer
    /// @param recipient The destination address of the token
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) external payable;
}

File 76 of 89 : IPeripheryPaymentsWithFee.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

import './IPeripheryPayments.sol';

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPaymentsWithFee is IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between
    /// 0 (exclusive), and 1 (inclusive) going to feeRecipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    function unwrapWETH9WithFee(
        uint256 amountMinimum,
        address recipient,
        uint256 feeBips,
        address feeRecipient
    ) external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between
    /// 0 (exclusive) and 1 (inclusive) going to feeRecipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    function sweepTokenWithFee(
        address token,
        uint256 amountMinimum,
        address recipient,
        uint256 feeBips,
        address feeRecipient
    ) external payable;
}

File 77 of 89 : IPoolInitializer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
    /// @param token0 The contract address of token0 of the pool
    /// @param token1 The contract address of token1 of the pool
    /// @param fee The fee amount of the v3 pool for the specified token pair
    /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
    /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint24 fee,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

File 78 of 89 : IQuoterV2.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title QuoterV2 Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.
/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IQuoterV2 {
    /// @notice Returns the amount out received for a given exact input swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee
    /// @param amountIn The amount of the first token to swap
    /// @return amountOut The amount of the last token that would be received
    /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path
    /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactInput(bytes memory path, uint256 amountIn)
        external
        returns (
            uint256 amountOut,
            uint160[] memory sqrtPriceX96AfterList,
            uint32[] memory initializedTicksCrossedList,
            uint256 gasEstimate
        );

    struct QuoteExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint24 fee;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Returns the amount out received for a given exact input but for a swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`
    /// tokenIn The token being swapped in
    /// tokenOut The token being swapped out
    /// fee The fee of the token pool to consider for the pair
    /// amountIn The desired input amount
    /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountOut The amount of `tokenOut` that would be received
    /// @return sqrtPriceX96After The sqrt price of the pool after the swap
    /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
        external
        returns (
            uint256 amountOut,
            uint160 sqrtPriceX96After,
            uint32 initializedTicksCrossed,
            uint256 gasEstimate
        );

    /// @notice Returns the amount in required for a given exact output swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order
    /// @param amountOut The amount of the last token to receive
    /// @return amountIn The amount of first token required to be paid
    /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path
    /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactOutput(bytes memory path, uint256 amountOut)
        external
        returns (
            uint256 amountIn,
            uint160[] memory sqrtPriceX96AfterList,
            uint32[] memory initializedTicksCrossedList,
            uint256 gasEstimate
        );

    struct QuoteExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint256 amount;
        uint24 fee;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`
    /// tokenIn The token being swapped in
    /// tokenOut The token being swapped out
    /// fee The fee of the token pool to consider for the pair
    /// amountOut The desired output amount
    /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
    /// @return sqrtPriceX96After The sqrt price of the pool after the swap
    /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)
        external
        returns (
            uint256 amountIn,
            uint160 sqrtPriceX96After,
            uint32 initializedTicksCrossed,
            uint256 gasEstimate
        );
}

File 79 of 89 : ISelfPermit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit {
    /// @notice Permits this contract to spend a given token from `msg.sender`
    /// @dev The `owner` is always msg.sender and the `spender` is always address(this).
    /// @param token The address of the token spent
    /// @param value The amount that can be spent of token
    /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermit(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;

    /// @notice Permits this contract to spend a given token from `msg.sender`
    /// @dev The `owner` is always msg.sender and the `spender` is always address(this).
    /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
    /// @param token The address of the token spent
    /// @param value The amount that can be spent of token
    /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermitIfNecessary(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;

    /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
    /// @dev The `owner` is always msg.sender and the `spender` is always address(this)
    /// @param token The address of the token spent
    /// @param nonce The current nonce of the owner
    /// @param expiry The timestamp at which the permit is no longer valid
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermitAllowed(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;

    /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
    /// @dev The `owner` is always msg.sender and the `spender` is always address(this)
    /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
    /// @param token The address of the token spent
    /// @param nonce The current nonce of the owner
    /// @param expiry The timestamp at which the permit is no longer valid
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermitAllowedIfNecessary(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}

File 80 of 89 : ISwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import {IUniswapV3SwapCallback} from '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
import {IPeripheryImmutableState} from "./IPeripheryImmutableState.sol";

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback, IPeripheryImmutableState {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

File 81 of 89 : IERC20PermitAllowed.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Interface for permit
/// @notice Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
    /// @notice Approve the spender to spend some tokens via the holder signature
    /// @dev This is the permit interface used by DAI and CHAI
    /// @param holder The address of the token holder, the token owner
    /// @param spender The address of the token spender
    /// @param nonce The holder's nonce, increases at each call to permit
    /// @param expiry The timestamp at which the permit is no longer valid
    /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address holder,
        address spender,
        uint256 nonce,
        uint256 expiry,
        bool allowed,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

File 82 of 89 : IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

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

/// @title Interface for WETH9
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;
}

File 83 of 89 : BytesLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity >=0.8.0 <0.9.0;

library BytesLib {
    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory) {
        require(_length + 31 >= _length, 'slice_overflow');
        require(_bytes.length >= _start + _length, 'slice_outOfBounds');

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    mstore(mc, mload(cc))
                }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
        require(_start + 3 >= _start, 'toUint24_overflow');
        require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
        uint24 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x3), _start))
        }

        return tempUint;
    }
}

File 84 of 89 : CallbackValidation.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import './PoolAddress.sol';

/// @notice Provides validation for callbacks from Uniswap V3 Pools
library CallbackValidation {
    /// @notice Returns the address of a valid Uniswap V3 Pool
    /// @param factory The contract address of the Uniswap V3 factory
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The V3 pool contract address
    function verifyCallback(
        address factory,
        address tokenA,
        address tokenB,
        uint24 fee
    ) internal view returns (IUniswapV3Pool pool) {
        return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));
    }

    /// @notice Returns the address of a valid Uniswap V3 Pool
    /// @param factory The contract address of the Uniswap V3 factory
    /// @param poolKey The identifying key of the V3 pool
    /// @return pool The V3 pool contract address
    function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)
        internal
        view
        returns (IUniswapV3Pool pool)
    {
        pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
        require(msg.sender == address(pool));
    }
}

File 85 of 89 : HexStrings.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library HexStrings {
    bytes16 internal constant ALPHABET = '0123456789abcdef';

    /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
    /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = '0';
        buffer[1] = 'x';
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = ALPHABET[value & 0xf];
            value >>= 4;
        }
        require(value == 0, 'Strings: hex length insufficient');
        return string(buffer);
    }

    function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length);
        for (uint256 i = buffer.length; i > 0; i--) {
            buffer[i - 1] = ALPHABET[value & 0xf];
            value >>= 4;
        }
        return string(buffer);
    }
}

File 86 of 89 : Path.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import './BytesLib.sol';

/// @title Functions for manipulating path data for multihop swaps
library Path {
    using BytesLib for bytes;

    /// @dev The length of the bytes encoded address
    uint256 private constant ADDR_SIZE = 20;
    /// @dev The length of the bytes encoded fee
    uint256 private constant FEE_SIZE = 3;

    /// @dev The offset of a single token address and pool fee
    uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
    /// @dev The offset of an encoded pool key
    uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
    /// @dev The minimum length of an encoding that contains 2 or more pools
    uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;

    /// @notice Returns true iff the path contains two or more pools
    /// @param path The encoded swap path
    /// @return True if path contains two or more pools, otherwise false
    function hasMultiplePools(bytes memory path) internal pure returns (bool) {
        return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
    }

    /// @notice Returns the number of pools in the path
    /// @param path The encoded swap path
    /// @return The number of pools in the path
    function numPools(bytes memory path) internal pure returns (uint256) {
        // Ignore the first token address. From then on every fee and token offset indicates a pool.
        return ((path.length - ADDR_SIZE) / NEXT_OFFSET);
    }

    /// @notice Decodes the first pool in path
    /// @param path The bytes encoded swap path
    /// @return tokenA The first token of the given pool
    /// @return tokenB The second token of the given pool
    /// @return fee The fee level of the pool
    function decodeFirstPool(bytes memory path)
        internal
        pure
        returns (
            address tokenA,
            address tokenB,
            uint24 fee
        )
    {
        tokenA = path.toAddress(0);
        fee = path.toUint24(ADDR_SIZE);
        tokenB = path.toAddress(NEXT_OFFSET);
    }

    /// @notice Gets the segment corresponding to the first pool in the path
    /// @param path The bytes encoded swap path
    /// @return The segment containing all data necessary to target the first pool in the path
    function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
        return path.slice(0, POP_OFFSET);
    }

    /// @notice Skips a token + fee element from the buffer and returns the remainder
    /// @param path The swap path
    /// @return The remaining token + fee elements in the path
    function skipToken(bytes memory path) internal pure returns (bytes memory) {
        return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
    }
}

File 87 of 89 : PoolAddress.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {Create2Upgradeable} from "@openzeppelin-upgradeable/contracts/utils/Create2Upgradeable.sol";

/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
    // NOTE: Ensure this value is latest & corresponds to current Create2BeaconProxy code
    // keccak256(type(Create2BeaconProxy).creationCode);
    bytes32 internal constant BEACON_CODE_HASH =
        0x7700ec83d0dc69c0a1e228138168ca93778a8d2f0fe9a0afb44901e1d5142d48;

    /// @notice The identifying key of the pool
    struct PoolKey {
        address token0;
        address token1;
        uint24 fee;
    }

    /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
    /// @param tokenA The first token of a pool, unsorted
    /// @param tokenB The second token of a pool, unsorted
    /// @param fee The fee level of the pool
    /// @return Poolkey The pool details with ordered token0 and token1 assignments
    function getPoolKey(
        address tokenA,
        address tokenB,
        uint24 fee
    ) internal pure returns (PoolKey memory) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
    }

    /// @notice Deterministically computes the pool address given the factory and PoolKey
    /// @param factory The Uniswap V3 factory contract address
    /// @param key The PoolKey
    /// @return pool The contract address of the V3 pool
    function computeAddress(
        address factory,
        PoolKey memory key
    ) internal pure returns (address pool) {
        require(key.token0 < key.token1);
        pool = Create2Upgradeable.computeAddress(
            keccak256(abi.encode(key.token0, key.token1, key.fee)),
            BEACON_CODE_HASH,
            factory
        );
    }
}

File 88 of 89 : TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

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

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)
        );
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}

File 89 of 89 : base64.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;

/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
    string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    bytes  internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
                                            hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
                                            hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
                                            hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";

    function encode(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return '';

        // load the table into memory
        string memory table = TABLE_ENCODE;

        // multiply by 4/3 rounded up
        uint256 encodedLen = 4 * ((data.length + 2) / 3);

        // add some extra buffer at the end required for the writing
        string memory result = new string(encodedLen + 32);

        assembly {
            // set the actual output length
            mstore(result, encodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 3 bytes at a time
            for {} lt(dataPtr, endPtr) {}
            {
                // read 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // write 4 characters
                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(        input,  0x3F))))
                resultPtr := add(resultPtr, 1)
            }

            // padding with '='
            switch mod(mload(data), 3)
            case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
            case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
        }

        return result;
    }

    function decode(string memory _data) internal pure returns (bytes memory) {
        bytes memory data = bytes(_data);

        if (data.length == 0) return new bytes(0);
        require(data.length % 4 == 0, "invalid base64 decoder input");

        // load the table into memory
        bytes memory table = TABLE_DECODE;

        // every 4 characters represent 3 bytes
        uint256 decodedLen = (data.length / 4) * 3;

        // add some extra buffer at the end required for the writing
        bytes memory result = new bytes(decodedLen + 32);

        assembly {
            // padding with '='
            let lastBytes := mload(add(data, mload(data)))
            if eq(and(lastBytes, 0xFF), 0x3d) {
                decodedLen := sub(decodedLen, 1)
                if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
                    decodedLen := sub(decodedLen, 1)
                }
            }

            // set the actual output length
            mstore(result, decodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 4 characters at a time
            for {} lt(dataPtr, endPtr) {}
            {
               // read 4 characters
               dataPtr := add(dataPtr, 4)
               let input := mload(dataPtr)

               // write 3 bytes
               let output := add(
                   add(
                       shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
                       shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
                   add(
                       shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
                               and(mload(add(tablePtr, and(        input , 0xFF))), 0xFF)
                    )
                )
                mstore(resultPtr, shl(232, output))
                resultPtr := add(resultPtr, 3)
            }
        }

        return result;
    }
}

Settings
{
  "evmVersion": "london",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "none",
    "useLiteralContent": true
  },
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "remappings": [
    ":@mocks/=src/mocks/",
    ":@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    ":@openzeppelin/=lib/openzeppelin-contracts/",
    ":@permit2/=lib/permit2/src/",
    ":@src/=src/",
    ":@test/=test/",
    ":@uni-core/=src/uniswap/v3-core/",
    ":@uni-periphery/=src/uniswap/v3-periphery/",
    ":@uniswap/lib/=lib/solidity-lib/",
    ":@uniswap/v2-core/=lib/v2-core/",
    ":@uniswap/v3-core/contracts/=src/uniswap/v3-core/",
    ":base64-sol/=src/uniswap/v3-periphery/libraries/",
    ":ds-test/=lib/forge-std/lib/ds-test/src/",
    ":forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    ":forge-std/=lib/forge-std/src/",
    ":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/",
    ":permit2/=lib/permit2/",
    ":solidity-lib/=lib/solidity-lib/contracts/",
    ":solmate/=lib/permit2/lib/solmate/",
    ":v2-core/=lib/v2-core/contracts/"
  ],
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract INFTXVaultFactoryV3","name":"nftxVaultFactory_","type":"address"},{"internalType":"address","name":"universalRouter_","type":"address"},{"internalType":"contract IPermitAllowanceTransfer","name":"PERMIT2_","type":"address"},{"internalType":"address","name":"inventoryStaking_","type":"address"},{"internalType":"contract IWETH9","name":"WETH_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InsufficientWethForVaultFees","type":"error"},{"inputs":[],"name":"NotEnoughFundsForRedeem","type":"error"},{"inputs":[],"name":"NotNFTOwner","type":"error"},{"inputs":[],"name":"SwapFailed","type":"error"},{"inputs":[],"name":"UnableToSendETH","type":"error"},{"inputs":[],"name":"UnableToSendETH","type":"error"},{"inputs":[],"name":"WrongVaultType","type":"error"},{"inputs":[],"name":"ZapPaused","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"vaultId","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"nftIds","type":"uint256[]"},{"indexed":false,"internalType":"uint256","name":"ethSpent","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"netRoyaltyAmount","type":"uint256"}],"name":"Buy","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ethAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"vTokenAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"}],"name":"DustReturned","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"dustThreshold","type":"uint256"}],"name":"NewDustThreshold","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"universalRouter","type":"address"}],"name":"NewUniversalRouter","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"status","type":"bool"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"vaultId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"count","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ethReceived","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"netRoyaltyAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"wethFees","type":"uint256"}],"name":"Sell","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"vaultId","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"idsIn","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"indexed":false,"internalType":"uint256","name":"ethSpent","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"vaultId","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"idsIn","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"indexed":false,"internalType":"uint256","name":"ethSpent","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"inputs":[],"name":"PERMIT2","outputs":[{"internalType":"contract IPermitAllowanceTransfer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"contract IWETH9","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"internalType":"uint256","name":"vTokenPremiumLimit","type":"uint256"},{"internalType":"bytes","name":"executeToWETHCallData","type":"bytes"},{"internalType":"bytes","name":"executeToVTokenCallData","type":"bytes"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"bool","name":"deductRoyalty","type":"bool"}],"internalType":"struct MarketplaceUniversalRouterZap.BuyNFTsWithERC20Params","name":"params","type":"tuple"}],"name":"buyNFTsWithERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"internalType":"uint256","name":"vTokenPremiumLimit","type":"uint256"},{"internalType":"bytes","name":"executeToWETHCallData","type":"bytes"},{"internalType":"bytes","name":"executeToVTokenCallData","type":"bytes"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"bool","name":"deductRoyalty","type":"bool"}],"internalType":"struct MarketplaceUniversalRouterZap.BuyNFTsWithERC20Params","name":"params","type":"tuple"},{"internalType":"bytes","name":"encodedPermit2","type":"bytes"}],"name":"buyNFTsWithERC20WithPermit2","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"internalType":"bytes","name":"executeCallData","type":"bytes"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"vTokenPremiumLimit","type":"uint256"},{"internalType":"bool","name":"deductRoyalty","type":"bool"}],"name":"buyNFTsWithETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"dustThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"inventoryStaking","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nftxVaultFactory","outputs":[{"internalType":"contract INFTXVaultFactoryV3","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","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":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"paused_","type":"bool"}],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"}],"name":"rescueTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsIn","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes","name":"executeCallData","type":"bytes"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"bool","name":"deductRoyalty","type":"bool"}],"name":"sell1155","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsIn","type":"uint256[]"},{"internalType":"bytes","name":"executeCallData","type":"bytes"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"bool","name":"deductRoyalty","type":"bool"}],"name":"sell721","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"dustThreshold_","type":"uint256"}],"name":"setDustThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"universalRouter_","type":"address"}],"name":"setUniversalRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsIn","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"internalType":"uint256","name":"vTokenPremiumLimit","type":"uint256"},{"internalType":"address payable","name":"to","type":"address"}],"name":"swap1155","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"vaultId","type":"uint256"},{"internalType":"uint256[]","name":"idsIn","type":"uint256[]"},{"internalType":"uint256[]","name":"idsOut","type":"uint256[]"},{"internalType":"uint256","name":"vTokenPremiumLimit","type":"uint256"},{"internalType":"address payable","name":"to","type":"address"}],"name":"swap721","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"universalRouter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

6101006040526001805460ff60a01b191690553480156200001f57600080fd5b5060405162004b3638038062004b368339810160408190526200004291620000f1565b6200004d3362000088565b6001600160a01b0394851660c052600180546001600160a01b0319169486169490941790935590831660a052821660e0521660805262000171565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b0381168114620000ee57600080fd5b50565b600080600080600060a086880312156200010a57600080fd5b85516200011781620000d8565b60208701519095506200012a81620000d8565b60408701519094506200013d81620000d8565b60608701519093506200015081620000d8565b60808701519092506200016381620000d8565b809150509295509295909350565b60805160a05160c05160e0516148b96200027d600039600081816103ce0152612dac0152600081816102dd015281816107b10152818161135f01528181611c990152818161220e0152818161255701526126ee01526000818161038501528181610c6d01528181610cf301528181612fa50152818161304f01526130b001526000818161044001528181610b1701528181611075015281816112d6015281816113fb0152818161146d015281816114de0152818161157201528181611d2201528181611dbb01528181611fed0152818161208e015281816121290152818161217401528181612280015281816122c70152818161234f01528181612b4c01526131a901526148b96000f3fe6080604052600436106101995760003560e01c80636afdd850116100e1578063ad7e55ba1161008a578063e107518a11610064578063e107518a146104ce578063e8462e8f146104e1578063f23a6e6114610505578063f2fde38b1461053157600080fd5b8063ad7e55ba14610462578063bc197c8114610482578063c6f2de95146104ae57600080fd5b80638bfb2a06116100bb5780638bfb2a06146103f05780638da5cb5b14610410578063ad5c46481461042e57600080fd5b80636afdd85014610373578063715018a6146103a757806374a1b0b0146103bc57600080fd5b806335a9e4df11610143578063462812e21161011d578063462812e21461031f5780635c975abb14610332578063628a4b2f1461035357600080fd5b806335a9e4df146102935780633801daf1146102cb5780633eef1f5d146102ff57600080fd5b8063150b7a0211610174578063150b7a021461021c578063153379e01461026057806332a7cc6a1461027357600080fd5b8062ae3bf8146101a557806301ffc9a7146101c757806302329a29146101fc57600080fd5b366101a057005b600080fd5b3480156101b157600080fd5b506101c56101c03660046138aa565b610551565b005b3480156101d357600080fd5b506101e76101e23660046138c7565b610652565b60405190151581526020015b60405180910390f35b34801561020857600080fd5b506101c56102173660046138ff565b610689565b34801561022857600080fd5b50610247610237366004613a2a565b630a85bd0160e11b949350505050565b6040516001600160e01b031990911681526020016101f3565b6101c561026e366004613ae2565b610756565b34801561027f57600080fd5b506101c561028e366004613be4565b610abb565b34801561029f57600080fd5b506001546102b3906001600160a01b031681565b6040516001600160a01b0390911681526020016101f3565b3480156102d757600080fd5b506102b37f000000000000000000000000000000000000000000000000000000000000000081565b34801561030b57600080fd5b506101c561031a366004613c9d565b610c0d565b6101c561032d366004613d06565b610dbb565b34801561033e57600080fd5b506001546101e790600160a01b900460ff1681565b34801561035f57600080fd5b506101c561036e3660046138aa565b610eec565b34801561037f57600080fd5b506102b37f000000000000000000000000000000000000000000000000000000000000000081565b3480156103b357600080fd5b506101c5610fa1565b3480156103c857600080fd5b506102b37f000000000000000000000000000000000000000000000000000000000000000081565b3480156103fc57600080fd5b506101c561040b366004613d8d565b611007565b34801561041c57600080fd5b506000546001600160a01b03166102b3565b34801561043a57600080fd5b506102b37f000000000000000000000000000000000000000000000000000000000000000081565b34801561046e57600080fd5b506101c561047d366004613e45565b611191565b34801561048e57600080fd5b5061024761049d366004613ed3565b63bc197c8160e01b95945050505050565b3480156104ba57600080fd5b506101c56104c9366004613f81565b611220565b6101c56104dc366004613fb6565b611292565b3480156104ed57600080fd5b506104f760025481565b6040519081526020016101f3565b34801561051157600080fd5b5061024761052036600461405f565b63f23a6e6160e01b95945050505050565b34801561053d57600080fd5b506101c561054c3660046138aa565b61172f565b6000546001600160a01b031633146105b05760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b6001600160a01b03811615610644576040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa158015610606573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061062a91906140c8565b90506106406001600160a01b038316338361180e565b5050565b476106403382611871565b50565b60006001600160e01b03198216630271189760e51b148061068357506301ffc9a760e01b6001600160e01b03198316145b92915050565b6000546001600160a01b031633146106e35760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b60018054821515600160a01b027fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff9091161790556040517f0e2fb031ee032dc02d8011dc50b816eb450cf856abd8261680dac74f72165bd29061074b90831515815260200190565b60405180910390a150565b600154600160a01b900460ff16801561077a57506000546001600160a01b03163314155b1561079857604051632ac76fcf60e21b815260040160405180910390fd5b6040516340d1b7db60e11b8152600481018a90526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906381a36fb690602401602060405180830381865afa158015610800573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061082491906140e1565b9050806001600160a01b03166306f26dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610864573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061088891906140fe565b6108a557604051630f87f71360e31b815260040160405180910390fd5b6000816001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108e5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061090991906140e1565b604051631759616b60e11b81529091506001600160a01b03821690632eb2c2d69061094290339030908f908f908f908f9060040161416a565b600060405180830381600087803b15801561095c57600080fd5b505af1158015610970573d6000803e3d6000fd5b505060405163a22cb46560e01b81526001600160a01b038581166004830152600160248301528416925063a22cb4659150604401600060405180830381600087803b1580156109be57600080fd5b505af11580156109d2573d6000803e3d6000fd5b505050506000826001600160a01b031663b6c958b0348d8d8d8d8d8d338d8f60016040518c63ffffffff1660e01b8152600401610a189a999897969594939291906141c9565b60206040518083038185885af1158015610a36573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610a5b91906140c8565b9050610a66846118e5565b7f1b449cc3f7099b879bbc0f00308aa1214fc73cd8cfb77408001b2a17e7eabb008c8c8c8c8c8c8c888c604051610aa59998979695949392919061423a565b60405180910390a1505050505050505050505050565b600154600160a01b900460ff168015610adf57506000546001600160a01b03163314155b15610afd57604051632ac76fcf60e21b815260040160405180910390fd5b600080610b0b898989611980565b915091506000610b3d837f00000000000000000000000000000000000000000000000000000000000000008989611a17565b5090506000610b4c848a611ba5565b905080821015610b6f576040516333ebabf760e01b815260040160405180910390fd5b610b7b8b826001611c8f565b60008515610b9257610b8f848c8c86611e89565b90505b610b9c81836142b8565b610ba690846142d0565b9250610bb28784612072565b604080518d8152602081018c90529081018490526001600160a01b03881660608201526080810182905260a081018390527f9af014271d6e0a4ddb4fc79025d8a27025ea290b30dfc788a79aa055e2b5a2a79060c001610aa5565b600154600160a01b900460ff168015610c3157506000546001600160a01b03163314155b15610c4f57604051632ac76fcf60e21b815260040160405180910390fd5b8015610cf15760008080610c65848601866142fb565b9250925092507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316632b67b5708484846040518463ffffffff1660e01b8152600401610cbb93929190614443565b600060405180830381600087803b158015610cd557600080fd5b505af1158015610ce9573d6000803e3d6000fd5b505050505050505b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166336c785163330610d2f87602001356120fc565b610d3c60208901896138aa565b60405160e086901b6001600160e01b03191681526001600160a01b039485166004820152928416602484015290831660448301529091166064820152608401600060405180830381600087803b158015610d9557600080fd5b505af1158015610da9573d6000803e3d6000fd5b50505050610db683612117565b505050565b600154600160a01b900460ff168015610ddf57506000546001600160a01b03163314155b15610dfd57604051632ac76fcf60e21b815260040160405180910390fd5b6000610e0a888888612534565b50905060606000826001600160a01b031663b6c958b0348b8b868c8c338c8e60016040518b63ffffffff1660e01b8152600401610e4f999897969594939291906144fd565b60206040518083038185885af1158015610e6d573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610e9291906140c8565b9050610e9d846118e5565b7fda75130c11e2803fc0c6a1650388bb059fc4bec5f4714f07e300491568d8cae28a8a8a8a8a868a604051610ed8979695949392919061456c565b60405180910390a150505050505050505050565b6000546001600160a01b03163314610f465760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b6001805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040519081527f10ee97236663d47ca19791254e43c5503a628b168573ac298f4d6cc5ef853ddc9060200161074b565b6000546001600160a01b03163314610ffb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b611005600061266e565b565b600154600160a01b900460ff16801561102b57506000546001600160a01b03163314155b1561104957604051632ac76fcf60e21b815260040160405180910390fd5b6000806110598b8b8b8b8b6126cb565b91509150600061106b8b8b8b8b61298d565b9050600061109b847f00000000000000000000000000000000000000000000000000000000000000008a8a611a17565b50905060006110aa8584611ba5565b9050808210156110cd576040516333ebabf760e01b815260040160405180910390fd5b6110d98e826001611c8f565b600086156110f3576110f0858f8f8f8f89896129c1565b90505b6110fd81836142b8565b61110790846142d0565b92506111138884612072565b7f9af014271d6e0a4ddb4fc79025d8a27025ea290b30dfc788a79aa055e2b5a2a78f85858b858760405161117896959493929190958652602086019490945260408501929092526001600160a01b03166060840152608083015260a082015260c00190565b60405180910390a1505050505050505050505050505050565b6000546001600160a01b031633146111eb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b60028190556040518181527ff3a0ef1c6d5f308cc6362416c0c32bb75d56f985671d438858daf25edd5b73a29060200161074b565b600154600160a01b900460ff16801561124457506000546001600160a01b03163314155b1561126257604051632ac76fcf60e21b815260040160405180910390fd5b61128933306020840180359061127890866138aa565b6001600160a01b0316929190612bd8565b61064f81612117565b600154600160a01b900460ff1680156112b657506000546001600160a01b03163314155b156112d457604051632ac76fcf60e21b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561132f57600080fd5b505af1158015611343573d6000803e3d6000fd5b50506040516340d1b7db60e11b8152600481018c9052600093507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031692506381a36fb69150602401602060405180830381865afa1580156113b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d491906140e1565b6040516370a0823160e01b8152306004820152909150600090819081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190602401602060405180830381865afa158015611442573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146691906140c8565b90506114947f0000000000000000000000000000000000000000000000000000000000000000858b8b611a17565b5091506114a9670de0b6b3a76400008b6145bd565b8210156114c95760405163c70e7fcd60e01b815260040160405180910390fd5b6040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa15801561152d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061155191906140c8565b61155b90826142d0565b92506000905061156b83346142d0565b90506115987f00000000000000000000000000000000000000000000000000000000000000008583612c16565b6040516314b7e24f60e11b81526000906001600160a01b0386169063296fc49e906115d2908f908f908d9088908e906001906004016145dc565b6020604051808303816000875af11580156115f1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061161591906140c8565b905082670de0b6b3a764000061162b8d876145bd565b61163591906145bd565b61163f9190614620565b9350600086156116bf576000866001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611689573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116ad91906140e1565b90506116bb818f8f89611e89565b9150505b6116ca866001612d0f565b7f1bee93f76102c6aca0e829ff7984261cfcb8480b2308d5f92bfa2b82f99ae9d68e8e8e846116f9878b6142b8565b61170391906142b8565b8d8660405161171796959493929190614642565b60405180910390a15050505050505050505050505050565b6000546001600160a01b031633146117895760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b6001600160a01b0381166118055760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f646472657373000000000000000000000000000000000000000000000000000060648201526084016105a7565b61064f8161266e565b6040516001600160a01b038316602482015260448101829052610db690849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612e90565b6000826001600160a01b03168260405160006040518083038185875af1925050503d80600081146118be576040519150601f19603f3d011682016040523d82523d6000602084013e6118c3565b606091505b5050905080610db65760405163260e7d5b60e11b815260040160405180910390fd5b6001600160a01b03811661190c5760405163d92e233d60e01b815260040160405180910390fd5b6000816001600160a01b03164760405160006040518083038185875af1925050503d8060008114611959576040519150601f19603f3d011682016040523d82523d6000602084013e61195e565b606091505b50509050806106405760405163260e7d5b60e11b815260040160405180910390fd5b60008061198e858585612534565b604051630cb343fd60e31b815291935091506060906001600160a01b0384169063659a1fe8906119ca9088908890869033903090600401614683565b6020604051808303816000875af11580156119e9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a0d91906140c8565b5050935093915050565b6040516370a0823160e01b8152306004820152600090819081906001600160a01b038716906370a0823190602401602060405180830381865afa158015611a62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a8691906140c8565b600154909150611aa09088906001600160a01b0316612f75565b6001546040516000916001600160a01b031690611ac090889088906146cf565b6000604051808303816000865af19150503d8060008114611afd576040519150601f19603f3d011682016040523d82523d6000602084013e611b02565b606091505b5050905080611b245760405163081ceff360e41b815260040160405180910390fd5b6040516370a0823160e01b81523060048201526001600160a01b038816906370a0823190602401602060405180830381865afa158015611b68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b8c91906140c8565b9250611b9882846142d0565b9350505094509492505050565b600080836001600160a01b03166372188e3f6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611be6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c0a91906146df565b50909150506001600160a01b03841663b8517b78611c2885846145bd565b6040518263ffffffff1660e01b8152600401611c4691815260200190565b602060405180830381865afa158015611c63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c8791906140c8565b949350505050565b8115610db65760007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316630d43e8ad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cf5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d1991906140e1565b905081611d95577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004016000604051808303818588803b158015611d7b57600080fd5b505af1158015611d8f573d6000803e3d6000fd5b50505050505b60405163a9059cbb60e01b81526001600160a01b038281166004830152602482018590527f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb906044016020604051808303816000875af1158015611e04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e2891906140fe565b506040516391c05b0b60e01b8152600481018590526001600160a01b038216906391c05b0b90602401600060405180830381600087803b158015611e6b57600080fd5b505af1158015611e7f573d6000803e3d6000fd5b5050505050505050565b6040516301ffc9a760e01b815263152a902d60e11b600482015260009081906001600160a01b038716906301ffc9a790602401602060405180830381865afa158015611ed9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611efd91906140fe565b90508015612069576000611f118585614620565b905060005b8581101561206657600080896001600160a01b0316632a55205a8a8a86818110611f4257611f4261470d565b90506020020135866040518363ffffffff1660e01b8152600401611f70929190918252602082015260400190565b6040805180830381865afa158015611f8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fb09190614723565b9092509050611fbf81876142b8565b9550801561205c5760405163a9059cbb60e01b81526001600160a01b038381166004830152602482018390527f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb906044016020604051808303816000875af1158015612036573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205a91906140fe565b505b5050600101611f16565b50505b50949350505050565b80156120f357604051632e1a7d4d60e01b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d90602401600060405180830381600087803b1580156120da57600080fd5b505af11580156120ee573d6000803e3d6000fd5b505050505b610640826118e5565b806001600160a01b038116811461211257600080fd5b919050565b61215a61212760208301836138aa565b7f000000000000000000000000000000000000000000000000000000000000000061215560a0850185614751565b611a17565b50506040516370a0823160e01b81523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa1580156121c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e791906140c8565b604080516340d1b7db60e11b81529084013560048201529091506000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906381a36fb690602401602060405180830381865afa158015612255573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061227991906140e1565b90506122ad7f00000000000000000000000000000000000000000000000000000000000000008261215560c0870187614751565b50506040516370a0823160e01b81523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015612316573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061233a91906140c8565b9050600061234882856142d0565b90506123757f00000000000000000000000000000000000000000000000000000000000000008484612c16565b60006001600160a01b03841663296fc49e6123936060890189614798565b6123a46101008b0160e08c016138aa565b878b6080013560016040518763ffffffff1660e01b81526004016123cd969594939291906145dc565b6020604051808303816000875af11580156123ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061241091906140c8565b90506000612426610120880161010089016138ff565b156124ac576000856001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561246b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061248f91906140e1565b90506124a8816124a260608b018b614798565b87611e89565b9150505b6124b7856001612d0f565b7f1bee93f76102c6aca0e829ff7984261cfcb8480b2308d5f92bfa2b82f99ae9d660408801356124ea60608a018a614798565b846124f587896142b8565b6124ff91906142b8565b6125106101008d0160e08e016138aa565b8660405161252396959493929190614642565b60405180910390a150505050505050565b6040516340d1b7db60e11b81526004810184905260009081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906381a36fb690602401602060405180830381865afa15801561259e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125c291906140e1565b9150816001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612602573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061262691906140e1565b9050612666818386868080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061311192505050565b935093915050565b600080546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040516340d1b7db60e11b81526004810186905260009081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906381a36fb690602401602060405180830381865afa158015612735573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061275991906140e1565b9150816001600160a01b03166306f26dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015612799573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127bd91906140fe565b6127da57604051630f87f71360e31b815260040160405180910390fd5b816001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612818573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061283c91906140e1565b604051631759616b60e11b81529091506001600160a01b03821690632eb2c2d69061287590339030908b908b908b908b9060040161416a565b600060405180830381600087803b15801561288f57600080fd5b505af11580156128a3573d6000803e3d6000fd5b505060405163a22cb46560e01b81526001600160a01b038581166004830152600160248301528416925063a22cb4659150604401600060405180830381600087803b1580156128f157600080fd5b505af1158015612905573d6000803e3d6000fd5b5050604051630cb343fd60e31b81526001600160a01b038516925063659a1fe8915061293f908990899089908990339030906004016147e2565b6020604051808303816000875af115801561295e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061298291906140c8565b509550959350505050565b6000805b84811015612069578383828181106129ab576129ab61470d565b9050602002013582019150806001019050612991565b6040516301ffc9a760e01b815263152a902d60e11b600482015260009081906001600160a01b038a16906301ffc9a790602401602060405180830381865afa158015612a11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a3591906140fe565b90508015612bcc576000612a498585614620565b905060005b88811015612bc9576000808c6001600160a01b0316632a55205a8d8d86818110612a7a57612a7a61470d565b90506020020135866040518363ffffffff1660e01b8152600401612aa8929190918252602082015260400190565b6040805180830381865afa158015612ac4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ae89190614723565b9150915060008a8a85818110612b0057612b0061470d565b9050602002013582612b1291906145bd565b9050612b1e81886142b8565b96508015612bbb5760405163a9059cbb60e01b81526001600160a01b038481166004830152602482018390527f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb906044016020604051808303816000875af1158015612b95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bb991906140fe565b505b836001019350505050612a4e565b50505b50979650505050505050565b6040516001600160a01b0380851660248301528316604482015260648101829052612c109085906323b872dd60e01b9060840161183a565b50505050565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015612c66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c8a91906140c8565b905080821115612c105760405163095ea7b360e01b81526001600160a01b038481166004830152600019602483015285169063095ea7b3906044016020604051808303816000875af1158015612ce4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d0891906140fe565b5050505050565b60008115612d2357612d2033613191565b90505b6040516370a0823160e01b81523060048201526000906001600160a01b038516906370a0823190602401602060405180830381865afa158015612d6a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d8e91906140c8565b905060008115612e4157600254821115612da9575033612dcc565b507f00000000000000000000000000000000000000000000000000000000000000005b60405163a9059cbb60e01b81526001600160a01b0382811660048301526024820184905286169063a9059cbb906044016020604051808303816000875af1158015612e1b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e3f91906140fe565b505b60408051848152602081018490526001600160a01b0383168183015290517fd9b066a634638844b3b4701f7bfb9d8791265979e46666f7d7bc04cf4c06c9709181900360600190a15050505050565b6000612ee5826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166132289092919063ffffffff16565b805190915015610db65780806020019051810190612f0391906140fe565b610db65760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f7420737563636565640000000000000000000000000000000000000000000060648201526084016105a7565b60405163927da10560e01b81523060048201526001600160a01b03838116602483015282811660448301526000917f00000000000000000000000000000000000000000000000000000000000000009091169063927da10590606401606060405180830381865afa158015612fee573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130129190614830565b509091505073f0000000000000000000000000000000000000006001600160a01b0382161061304057505050565b6130766001600160a01b0384167f0000000000000000000000000000000000000000000000000000000000000000600019613241565b6040516387517c4560e01b81526001600160a01b03848116600483015283811660248301526044820181905265ffffffffffff60648301527f000000000000000000000000000000000000000000000000000000000000000016906387517c4590608401600060405180830381600087803b1580156130f457600080fd5b505af1158015613108573d6000803e3d6000fd5b50505050505050565b60005b8151811015612c1057613141848383815181106131335761313361470d565b60200260200101518561335d565b73b47e3cd837ddf8e4c57f05d70ab865de6e193bba196001600160a01b038516016131895761318982828151811061317b5761317b61470d565b60200260200101518461362b565b600101613114565b6040516370a0823160e01b81523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa1580156131f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061321c91906140c8565b90506121128282612072565b60606132378484600085613714565b90505b9392505050565b8015806132bb5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015613295573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132b991906140c8565b155b61332d5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527f20746f206e6f6e2d7a65726f20616c6c6f77616e63650000000000000000000060648201526084016105a7565b6040516001600160a01b038316602482015260448101829052610db690849063095ea7b360e01b9060640161183a565b60606001600160a01b03841673b47e3cd837ddf8e4c57f05d70ab865de6e193bbb148015906133a957506001600160a01b0384167306012c8cf97bead5deae237070f9587f8e7a266d14155b15613401576040513360248201526001600160a01b03831660448201526064810184905260840160408051601f198184030181529190526020810180516001600160e01b0316632142170760e11b17905290506135a9565b73b47e3cd837ddf8e4c57f05d70ab865de6e193bba196001600160a01b038516016135635760008360405160240161343b91815260200190565b60408051601f198184030181529181526020820180516001600160e01b0316630b02f02d60e31b17905251909150600090819073b47e3cd837ddf8e4c57f05d70ab865de6e193bbb9061348f90859061487d565b600060405180830381855afa9150503d80600081146134ca576040519150601f19603f3d011682016040523d82523d6000602084013e6134cf565b606091505b50915091506000818060200190518101906134ea91906140e1565b905082158061350257506001600160a01b0381163314155b1561352057604051631022318760e21b815260040160405180910390fd5b6040516024810188905260440160408051601f198184030181529190526020810180516001600160e01b031663104c9fd360e31b17905294506135a99350505050565b6040513360248201523060448201526064810184905260840160408051601f198184030181529190526020810180516001600160e01b03166323b872dd60e01b17905290505b600080856001600160a01b0316836040516135c4919061487d565b6000604051808303816000865af19150503d8060008114613601576040519150601f19603f3d011682016040523d82523d6000602084013e613606565b606091505b50915091508181906131085760405162461bcd60e51b81526004016105a79190614899565b604051602481018390526000604482018190526001600160a01b03831660648301529060840160408051601f198184030181529181526020820180516001600160e01b031663bf31196f60e01b17905251909150600090819073b47e3cd837ddf8e4c57f05d70ab865de6e193bbb906136a590859061487d565b6000604051808303816000865af19150503d80600081146136e2576040519150601f19603f3d011682016040523d82523d6000602084013e6136e7565b606091505b509150915081819061370c5760405162461bcd60e51b81526004016105a79190614899565b505050505050565b60608247101561378c5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f60448201527f722063616c6c000000000000000000000000000000000000000000000000000060648201526084016105a7565b6001600160a01b0385163b6137e35760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016105a7565b600080866001600160a01b031685876040516137ff919061487d565b60006040518083038185875af1925050503d806000811461383c576040519150601f19603f3d011682016040523d82523d6000602084013e613841565b606091505b509150915061385182828661385c565b979650505050505050565b6060831561386b57508161323a565b82511561387b5782518084602001fd5b8160405162461bcd60e51b81526004016105a79190614899565b6001600160a01b038116811461064f57600080fd5b6000602082840312156138bc57600080fd5b813561323a81613895565b6000602082840312156138d957600080fd5b81356001600160e01b03198116811461323a57600080fd5b801515811461064f57600080fd5b60006020828403121561391157600080fd5b813561323a816138f1565b803561211281613895565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff8111828210171561396057613960613927565b60405290565b6040516080810167ffffffffffffffff8111828210171561396057613960613927565b604051601f8201601f1916810167ffffffffffffffff811182821017156139b2576139b2613927565b604052919050565b600082601f8301126139cb57600080fd5b813567ffffffffffffffff8111156139e5576139e5613927565b6139f8601f8201601f1916602001613989565b818152846020838601011115613a0d57600080fd5b816020850160208301376000918101602001919091529392505050565b60008060008060808587031215613a4057600080fd5b8435613a4b81613895565b93506020850135613a5b81613895565b925060408501359150606085013567ffffffffffffffff811115613a7e57600080fd5b613a8a878288016139ba565b91505092959194509250565b60008083601f840112613aa857600080fd5b50813567ffffffffffffffff811115613ac057600080fd5b6020830191508360208260051b8501011115613adb57600080fd5b9250929050565b600080600080600080600080600060c08a8c031215613b0057600080fd5b8935985060208a013567ffffffffffffffff80821115613b1f57600080fd5b613b2b8d838e01613a96565b909a50985060408c0135915080821115613b4457600080fd5b613b508d838e01613a96565b909850965060608c0135915080821115613b6957600080fd5b50613b768c828d01613a96565b90955093505060808a0135915060a08a0135613b9181613895565b809150509295985092959850929598565b60008083601f840112613bb457600080fd5b50813567ffffffffffffffff811115613bcc57600080fd5b602083019150836020828501011115613adb57600080fd5b600080600080600080600060a0888a031215613bff57600080fd5b87359650602088013567ffffffffffffffff80821115613c1e57600080fd5b613c2a8b838c01613a96565b909850965060408a0135915080821115613c4357600080fd5b50613c508a828b01613ba2565b9095509350506060880135613c6481613895565b91506080880135613c74816138f1565b8091505092959891949750929550565b60006101208284031215613c9757600080fd5b50919050565b600080600060408486031215613cb257600080fd5b833567ffffffffffffffff80821115613cca57600080fd5b613cd687838801613c84565b94506020860135915080821115613cec57600080fd5b50613cf986828701613ba2565b9497909650939450505050565b600080600080600080600060a0888a031215613d2157600080fd5b87359650602088013567ffffffffffffffff80821115613d4057600080fd5b613d4c8b838c01613a96565b909850965060408a0135915080821115613d6557600080fd5b50613d728a828b01613a96565b909550935050606088013591506080880135613c7481613895565b600080600080600080600080600060c08a8c031215613dab57600080fd5b8935985060208a013567ffffffffffffffff80821115613dca57600080fd5b613dd68d838e01613a96565b909a50985060408c0135915080821115613def57600080fd5b613dfb8d838e01613a96565b909850965060608c0135915080821115613e1457600080fd5b50613e218c828d01613ba2565b90955093505060808a0135613e3581613895565b915060a08a0135613b91816138f1565b600060208284031215613e5757600080fd5b5035919050565b600082601f830112613e6f57600080fd5b8135602067ffffffffffffffff821115613e8b57613e8b613927565b8160051b613e9a828201613989565b9283528481018201928281019087851115613eb457600080fd5b83870192505b8483101561385157823582529183019190830190613eba565b600080600080600060a08688031215613eeb57600080fd5b8535613ef681613895565b94506020860135613f0681613895565b9350604086013567ffffffffffffffff80821115613f2357600080fd5b613f2f89838a01613e5e565b94506060880135915080821115613f4557600080fd5b613f5189838a01613e5e565b93506080880135915080821115613f6757600080fd5b50613f74888289016139ba565b9150509295509295909350565b600060208284031215613f9357600080fd5b813567ffffffffffffffff811115613faa57600080fd5b611c8784828501613c84565b60008060008060008060008060c0898b031215613fd257600080fd5b88359750602089013567ffffffffffffffff80821115613ff157600080fd5b613ffd8c838d01613a96565b909950975060408b013591508082111561401657600080fd5b506140238b828c01613ba2565b909650945050606089013561403781613895565b92506080890135915060a089013561404e816138f1565b809150509295985092959890939650565b600080600080600060a0868803121561407757600080fd5b853561408281613895565b9450602086013561409281613895565b93506040860135925060608601359150608086013567ffffffffffffffff8111156140bc57600080fd5b613f74888289016139ba565b6000602082840312156140da57600080fd5b5051919050565b6000602082840312156140f357600080fd5b815161323a81613895565b60006020828403121561411057600080fd5b815161323a816138f1565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561414d57600080fd5b8260051b8083602087013760009401602001938452509192915050565b60006001600160a01b03808916835280881660208401525060a0604083015261419760a08301868861411b565b82810360608401526141aa81858761411b565b8381036080909401939093525050600081526020019695505050505050565b60e0815260006141dd60e083018c8e61411b565b82810360208401526141f0818b8d61411b565b9050828103604084015261420581898b61411b565b6001600160a01b0397881660608501529590961660808301525060a0810192909252151560c090910152979650505050505050565b89815260c06020820152600061425460c083018a8c61411b565b828103604084015261426781898b61411b565b9050828103606084015261427c81878961411b565b9150508360808301526001600160a01b03831660a08301529a9950505050505050505050565b634e487b7160e01b600052601160045260246000fd5b600082198211156142cb576142cb6142a2565b500190565b6000828210156142e2576142e26142a2565b500390565b65ffffffffffff8116811461064f57600080fd5b600080600083850361010081121561431257600080fd5b843561431d81613895565b9350601f190160c081121561433157600080fd5b61433961393d565b608082121561434757600080fd5b61434f613966565b9150602086013561435f81613895565b8252604086013561436f81613895565b60208301526060860135614382816142e7565b60408301526080860135614395816142e7565b60608301528181526143a960a0870161391c565b602082015260c0860135604082015292505060e084013567ffffffffffffffff8111156143d557600080fd5b6143e1868287016139ba565b9150509250925092565b60005b838110156144065781810151838201526020016143ee565b83811115612c105750506000910152565b6000815180845261442f8160208601602086016143eb565b601f01601f19169290920160200192915050565b60006101006001600160a01b0380871684528551818151166020860152816020820151166040860152604081015165ffffffffffff80821660608801528060608401511660808801525050508060208701511660a085015250604085015160c08401528060e08401526144b881840185614417565b9695505050505050565b600081518084526020808501945080840160005b838110156144f2578151875295820195908201906001016144d6565b509495945050505050565b60e08152600061451160e083018b8d61411b565b8281036020840152614523818b6144c2565b9050828103604084015261453881898b61411b565b6001600160a01b0397881660608501529590961660808301525060a0810192909252151560c0909101529695505050505050565b87815260a06020820152600061458660a08301888a61411b565b828103604084015261459981878961411b565b9150508360608301526001600160a01b038316608083015298975050505050505050565b60008160001904831182151516156145d7576145d76142a2565b500290565b60a0815260006145f060a08301888a61411b565b90506001600160a01b03861660208301528460408301528360608301528215156080830152979650505050505050565b60008261463d57634e487b7160e01b600052601260045260246000fd5b500490565b86815260a06020820152600061465c60a08301878961411b565b6040830195909552506001600160a01b039290921660608301526080909101529392505050565b60808152600061469760808301878961411b565b82810360208401526146a981876144c2565b9150506001600160a01b0380851660408401528084166060840152509695505050505050565b8183823760009101908152919050565b6000806000606084860312156146f457600080fd5b8351925060208401519150604084015190509250925092565b634e487b7160e01b600052603260045260246000fd5b6000806040838503121561473657600080fd5b825161474181613895565b6020939093015192949293505050565b6000808335601e1984360301811261476857600080fd5b83018035915067ffffffffffffffff82111561478357600080fd5b602001915036819003821315613adb57600080fd5b6000808335601e198436030181126147af57600080fd5b83018035915067ffffffffffffffff8211156147ca57600080fd5b6020019150600581901b3603821315613adb57600080fd5b6080815260006147f660808301888a61411b565b828103602084015261480981878961411b565b9150506001600160a01b038085166040840152808416606084015250979650505050505050565b60008060006060848603121561484557600080fd5b835161485081613895565b6020850151909350614861816142e7565b6040850151909250614872816142e7565b809150509250925092565b6000825161488f8184602087016143eb565b9190910192915050565b60208152600061323a602083018461441756fea164736f6c634300080f000a000000000000000000000000c255335bc5abd6928063f5788a5e420554858f01000000000000000000000000250d62a67254a46c0de472d2c9215e1d890cc90f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3000000000000000000000000889f313e2a3fdc1c9a45bc6020a8a18749cd6152000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2

Deployed Bytecode

0x6080604052600436106101995760003560e01c80636afdd850116100e1578063ad7e55ba1161008a578063e107518a11610064578063e107518a146104ce578063e8462e8f146104e1578063f23a6e6114610505578063f2fde38b1461053157600080fd5b8063ad7e55ba14610462578063bc197c8114610482578063c6f2de95146104ae57600080fd5b80638bfb2a06116100bb5780638bfb2a06146103f05780638da5cb5b14610410578063ad5c46481461042e57600080fd5b80636afdd85014610373578063715018a6146103a757806374a1b0b0146103bc57600080fd5b806335a9e4df11610143578063462812e21161011d578063462812e21461031f5780635c975abb14610332578063628a4b2f1461035357600080fd5b806335a9e4df146102935780633801daf1146102cb5780633eef1f5d146102ff57600080fd5b8063150b7a0211610174578063150b7a021461021c578063153379e01461026057806332a7cc6a1461027357600080fd5b8062ae3bf8146101a557806301ffc9a7146101c757806302329a29146101fc57600080fd5b366101a057005b600080fd5b3480156101b157600080fd5b506101c56101c03660046138aa565b610551565b005b3480156101d357600080fd5b506101e76101e23660046138c7565b610652565b60405190151581526020015b60405180910390f35b34801561020857600080fd5b506101c56102173660046138ff565b610689565b34801561022857600080fd5b50610247610237366004613a2a565b630a85bd0160e11b949350505050565b6040516001600160e01b031990911681526020016101f3565b6101c561026e366004613ae2565b610756565b34801561027f57600080fd5b506101c561028e366004613be4565b610abb565b34801561029f57600080fd5b506001546102b3906001600160a01b031681565b6040516001600160a01b0390911681526020016101f3565b3480156102d757600080fd5b506102b37f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f0181565b34801561030b57600080fd5b506101c561031a366004613c9d565b610c0d565b6101c561032d366004613d06565b610dbb565b34801561033e57600080fd5b506001546101e790600160a01b900460ff1681565b34801561035f57600080fd5b506101c561036e3660046138aa565b610eec565b34801561037f57600080fd5b506102b37f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba381565b3480156103b357600080fd5b506101c5610fa1565b3480156103c857600080fd5b506102b37f000000000000000000000000889f313e2a3fdc1c9a45bc6020a8a18749cd615281565b3480156103fc57600080fd5b506101c561040b366004613d8d565b611007565b34801561041c57600080fd5b506000546001600160a01b03166102b3565b34801561043a57600080fd5b506102b37f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b34801561046e57600080fd5b506101c561047d366004613e45565b611191565b34801561048e57600080fd5b5061024761049d366004613ed3565b63bc197c8160e01b95945050505050565b3480156104ba57600080fd5b506101c56104c9366004613f81565b611220565b6101c56104dc366004613fb6565b611292565b3480156104ed57600080fd5b506104f760025481565b6040519081526020016101f3565b34801561051157600080fd5b5061024761052036600461405f565b63f23a6e6160e01b95945050505050565b34801561053d57600080fd5b506101c561054c3660046138aa565b61172f565b6000546001600160a01b031633146105b05760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b6001600160a01b03811615610644576040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa158015610606573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061062a91906140c8565b90506106406001600160a01b038316338361180e565b5050565b476106403382611871565b50565b60006001600160e01b03198216630271189760e51b148061068357506301ffc9a760e01b6001600160e01b03198316145b92915050565b6000546001600160a01b031633146106e35760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b60018054821515600160a01b027fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff9091161790556040517f0e2fb031ee032dc02d8011dc50b816eb450cf856abd8261680dac74f72165bd29061074b90831515815260200190565b60405180910390a150565b600154600160a01b900460ff16801561077a57506000546001600160a01b03163314155b1561079857604051632ac76fcf60e21b815260040160405180910390fd5b6040516340d1b7db60e11b8152600481018a90526000907f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f016001600160a01b0316906381a36fb690602401602060405180830381865afa158015610800573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061082491906140e1565b9050806001600160a01b03166306f26dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610864573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061088891906140fe565b6108a557604051630f87f71360e31b815260040160405180910390fd5b6000816001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108e5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061090991906140e1565b604051631759616b60e11b81529091506001600160a01b03821690632eb2c2d69061094290339030908f908f908f908f9060040161416a565b600060405180830381600087803b15801561095c57600080fd5b505af1158015610970573d6000803e3d6000fd5b505060405163a22cb46560e01b81526001600160a01b038581166004830152600160248301528416925063a22cb4659150604401600060405180830381600087803b1580156109be57600080fd5b505af11580156109d2573d6000803e3d6000fd5b505050506000826001600160a01b031663b6c958b0348d8d8d8d8d8d338d8f60016040518c63ffffffff1660e01b8152600401610a189a999897969594939291906141c9565b60206040518083038185885af1158015610a36573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610a5b91906140c8565b9050610a66846118e5565b7f1b449cc3f7099b879bbc0f00308aa1214fc73cd8cfb77408001b2a17e7eabb008c8c8c8c8c8c8c888c604051610aa59998979695949392919061423a565b60405180910390a1505050505050505050505050565b600154600160a01b900460ff168015610adf57506000546001600160a01b03163314155b15610afd57604051632ac76fcf60e21b815260040160405180910390fd5b600080610b0b898989611980565b915091506000610b3d837f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28989611a17565b5090506000610b4c848a611ba5565b905080821015610b6f576040516333ebabf760e01b815260040160405180910390fd5b610b7b8b826001611c8f565b60008515610b9257610b8f848c8c86611e89565b90505b610b9c81836142b8565b610ba690846142d0565b9250610bb28784612072565b604080518d8152602081018c90529081018490526001600160a01b03881660608201526080810182905260a081018390527f9af014271d6e0a4ddb4fc79025d8a27025ea290b30dfc788a79aa055e2b5a2a79060c001610aa5565b600154600160a01b900460ff168015610c3157506000546001600160a01b03163314155b15610c4f57604051632ac76fcf60e21b815260040160405180910390fd5b8015610cf15760008080610c65848601866142fb565b9250925092507f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba36001600160a01b0316632b67b5708484846040518463ffffffff1660e01b8152600401610cbb93929190614443565b600060405180830381600087803b158015610cd557600080fd5b505af1158015610ce9573d6000803e3d6000fd5b505050505050505b7f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba36001600160a01b03166336c785163330610d2f87602001356120fc565b610d3c60208901896138aa565b60405160e086901b6001600160e01b03191681526001600160a01b039485166004820152928416602484015290831660448301529091166064820152608401600060405180830381600087803b158015610d9557600080fd5b505af1158015610da9573d6000803e3d6000fd5b50505050610db683612117565b505050565b600154600160a01b900460ff168015610ddf57506000546001600160a01b03163314155b15610dfd57604051632ac76fcf60e21b815260040160405180910390fd5b6000610e0a888888612534565b50905060606000826001600160a01b031663b6c958b0348b8b868c8c338c8e60016040518b63ffffffff1660e01b8152600401610e4f999897969594939291906144fd565b60206040518083038185885af1158015610e6d573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610e9291906140c8565b9050610e9d846118e5565b7fda75130c11e2803fc0c6a1650388bb059fc4bec5f4714f07e300491568d8cae28a8a8a8a8a868a604051610ed8979695949392919061456c565b60405180910390a150505050505050505050565b6000546001600160a01b03163314610f465760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b6001805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040519081527f10ee97236663d47ca19791254e43c5503a628b168573ac298f4d6cc5ef853ddc9060200161074b565b6000546001600160a01b03163314610ffb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b611005600061266e565b565b600154600160a01b900460ff16801561102b57506000546001600160a01b03163314155b1561104957604051632ac76fcf60e21b815260040160405180910390fd5b6000806110598b8b8b8b8b6126cb565b91509150600061106b8b8b8b8b61298d565b9050600061109b847f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28a8a611a17565b50905060006110aa8584611ba5565b9050808210156110cd576040516333ebabf760e01b815260040160405180910390fd5b6110d98e826001611c8f565b600086156110f3576110f0858f8f8f8f89896129c1565b90505b6110fd81836142b8565b61110790846142d0565b92506111138884612072565b7f9af014271d6e0a4ddb4fc79025d8a27025ea290b30dfc788a79aa055e2b5a2a78f85858b858760405161117896959493929190958652602086019490945260408501929092526001600160a01b03166060840152608083015260a082015260c00190565b60405180910390a1505050505050505050505050505050565b6000546001600160a01b031633146111eb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b60028190556040518181527ff3a0ef1c6d5f308cc6362416c0c32bb75d56f985671d438858daf25edd5b73a29060200161074b565b600154600160a01b900460ff16801561124457506000546001600160a01b03163314155b1561126257604051632ac76fcf60e21b815260040160405180910390fd5b61128933306020840180359061127890866138aa565b6001600160a01b0316929190612bd8565b61064f81612117565b600154600160a01b900460ff1680156112b657506000546001600160a01b03163314155b156112d457604051632ac76fcf60e21b815260040160405180910390fd5b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561132f57600080fd5b505af1158015611343573d6000803e3d6000fd5b50506040516340d1b7db60e11b8152600481018c9052600093507f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f016001600160a01b031692506381a36fb69150602401602060405180830381865afa1580156113b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d491906140e1565b6040516370a0823160e01b8152306004820152909150600090819081906001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216906370a0823190602401602060405180830381865afa158015611442573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146691906140c8565b90506114947f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2858b8b611a17565b5091506114a9670de0b6b3a76400008b6145bd565b8210156114c95760405163c70e7fcd60e01b815260040160405180910390fd5b6040516370a0823160e01b81523060048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa15801561152d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061155191906140c8565b61155b90826142d0565b92506000905061156b83346142d0565b90506115987f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28583612c16565b6040516314b7e24f60e11b81526000906001600160a01b0386169063296fc49e906115d2908f908f908d9088908e906001906004016145dc565b6020604051808303816000875af11580156115f1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061161591906140c8565b905082670de0b6b3a764000061162b8d876145bd565b61163591906145bd565b61163f9190614620565b9350600086156116bf576000866001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611689573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116ad91906140e1565b90506116bb818f8f89611e89565b9150505b6116ca866001612d0f565b7f1bee93f76102c6aca0e829ff7984261cfcb8480b2308d5f92bfa2b82f99ae9d68e8e8e846116f9878b6142b8565b61170391906142b8565b8d8660405161171796959493929190614642565b60405180910390a15050505050505050505050505050565b6000546001600160a01b031633146117895760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105a7565b6001600160a01b0381166118055760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f646472657373000000000000000000000000000000000000000000000000000060648201526084016105a7565b61064f8161266e565b6040516001600160a01b038316602482015260448101829052610db690849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612e90565b6000826001600160a01b03168260405160006040518083038185875af1925050503d80600081146118be576040519150601f19603f3d011682016040523d82523d6000602084013e6118c3565b606091505b5050905080610db65760405163260e7d5b60e11b815260040160405180910390fd5b6001600160a01b03811661190c5760405163d92e233d60e01b815260040160405180910390fd5b6000816001600160a01b03164760405160006040518083038185875af1925050503d8060008114611959576040519150601f19603f3d011682016040523d82523d6000602084013e61195e565b606091505b50509050806106405760405163260e7d5b60e11b815260040160405180910390fd5b60008061198e858585612534565b604051630cb343fd60e31b815291935091506060906001600160a01b0384169063659a1fe8906119ca9088908890869033903090600401614683565b6020604051808303816000875af11580156119e9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a0d91906140c8565b5050935093915050565b6040516370a0823160e01b8152306004820152600090819081906001600160a01b038716906370a0823190602401602060405180830381865afa158015611a62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a8691906140c8565b600154909150611aa09088906001600160a01b0316612f75565b6001546040516000916001600160a01b031690611ac090889088906146cf565b6000604051808303816000865af19150503d8060008114611afd576040519150601f19603f3d011682016040523d82523d6000602084013e611b02565b606091505b5050905080611b245760405163081ceff360e41b815260040160405180910390fd5b6040516370a0823160e01b81523060048201526001600160a01b038816906370a0823190602401602060405180830381865afa158015611b68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b8c91906140c8565b9250611b9882846142d0565b9350505094509492505050565b600080836001600160a01b03166372188e3f6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611be6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c0a91906146df565b50909150506001600160a01b03841663b8517b78611c2885846145bd565b6040518263ffffffff1660e01b8152600401611c4691815260200190565b602060405180830381865afa158015611c63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c8791906140c8565b949350505050565b8115610db65760007f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f016001600160a01b0316630d43e8ad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cf5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d1991906140e1565b905081611d95577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004016000604051808303818588803b158015611d7b57600080fd5b505af1158015611d8f573d6000803e3d6000fd5b50505050505b60405163a9059cbb60e01b81526001600160a01b038281166004830152602482018590527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2169063a9059cbb906044016020604051808303816000875af1158015611e04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e2891906140fe565b506040516391c05b0b60e01b8152600481018590526001600160a01b038216906391c05b0b90602401600060405180830381600087803b158015611e6b57600080fd5b505af1158015611e7f573d6000803e3d6000fd5b5050505050505050565b6040516301ffc9a760e01b815263152a902d60e11b600482015260009081906001600160a01b038716906301ffc9a790602401602060405180830381865afa158015611ed9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611efd91906140fe565b90508015612069576000611f118585614620565b905060005b8581101561206657600080896001600160a01b0316632a55205a8a8a86818110611f4257611f4261470d565b90506020020135866040518363ffffffff1660e01b8152600401611f70929190918252602082015260400190565b6040805180830381865afa158015611f8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fb09190614723565b9092509050611fbf81876142b8565b9550801561205c5760405163a9059cbb60e01b81526001600160a01b038381166004830152602482018390527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2169063a9059cbb906044016020604051808303816000875af1158015612036573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205a91906140fe565b505b5050600101611f16565b50505b50949350505050565b80156120f357604051632e1a7d4d60e01b8152600481018290527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031690632e1a7d4d90602401600060405180830381600087803b1580156120da57600080fd5b505af11580156120ee573d6000803e3d6000fd5b505050505b610640826118e5565b806001600160a01b038116811461211257600080fd5b919050565b61215a61212760208301836138aa565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc261215560a0850185614751565b611a17565b50506040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa1580156121c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e791906140c8565b604080516340d1b7db60e11b81529084013560048201529091506000906001600160a01b037f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f0116906381a36fb690602401602060405180830381865afa158015612255573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061227991906140e1565b90506122ad7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28261215560c0870187614751565b50506040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa158015612316573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061233a91906140c8565b9050600061234882856142d0565b90506123757f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28484612c16565b60006001600160a01b03841663296fc49e6123936060890189614798565b6123a46101008b0160e08c016138aa565b878b6080013560016040518763ffffffff1660e01b81526004016123cd969594939291906145dc565b6020604051808303816000875af11580156123ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061241091906140c8565b90506000612426610120880161010089016138ff565b156124ac576000856001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561246b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061248f91906140e1565b90506124a8816124a260608b018b614798565b87611e89565b9150505b6124b7856001612d0f565b7f1bee93f76102c6aca0e829ff7984261cfcb8480b2308d5f92bfa2b82f99ae9d660408801356124ea60608a018a614798565b846124f587896142b8565b6124ff91906142b8565b6125106101008d0160e08e016138aa565b8660405161252396959493929190614642565b60405180910390a150505050505050565b6040516340d1b7db60e11b81526004810184905260009081906001600160a01b037f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f0116906381a36fb690602401602060405180830381865afa15801561259e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125c291906140e1565b9150816001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612602573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061262691906140e1565b9050612666818386868080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061311192505050565b935093915050565b600080546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040516340d1b7db60e11b81526004810186905260009081906001600160a01b037f000000000000000000000000c255335bc5abd6928063f5788a5e420554858f0116906381a36fb690602401602060405180830381865afa158015612735573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061275991906140e1565b9150816001600160a01b03166306f26dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015612799573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127bd91906140fe565b6127da57604051630f87f71360e31b815260040160405180910390fd5b816001600160a01b0316631ba46cfd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612818573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061283c91906140e1565b604051631759616b60e11b81529091506001600160a01b03821690632eb2c2d69061287590339030908b908b908b908b9060040161416a565b600060405180830381600087803b15801561288f57600080fd5b505af11580156128a3573d6000803e3d6000fd5b505060405163a22cb46560e01b81526001600160a01b038581166004830152600160248301528416925063a22cb4659150604401600060405180830381600087803b1580156128f157600080fd5b505af1158015612905573d6000803e3d6000fd5b5050604051630cb343fd60e31b81526001600160a01b038516925063659a1fe8915061293f908990899089908990339030906004016147e2565b6020604051808303816000875af115801561295e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061298291906140c8565b509550959350505050565b6000805b84811015612069578383828181106129ab576129ab61470d565b9050602002013582019150806001019050612991565b6040516301ffc9a760e01b815263152a902d60e11b600482015260009081906001600160a01b038a16906301ffc9a790602401602060405180830381865afa158015612a11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a3591906140fe565b90508015612bcc576000612a498585614620565b905060005b88811015612bc9576000808c6001600160a01b0316632a55205a8d8d86818110612a7a57612a7a61470d565b90506020020135866040518363ffffffff1660e01b8152600401612aa8929190918252602082015260400190565b6040805180830381865afa158015612ac4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ae89190614723565b9150915060008a8a85818110612b0057612b0061470d565b9050602002013582612b1291906145bd565b9050612b1e81886142b8565b96508015612bbb5760405163a9059cbb60e01b81526001600160a01b038481166004830152602482018390527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2169063a9059cbb906044016020604051808303816000875af1158015612b95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bb991906140fe565b505b836001019350505050612a4e565b50505b50979650505050505050565b6040516001600160a01b0380851660248301528316604482015260648101829052612c109085906323b872dd60e01b9060840161183a565b50505050565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015612c66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c8a91906140c8565b905080821115612c105760405163095ea7b360e01b81526001600160a01b038481166004830152600019602483015285169063095ea7b3906044016020604051808303816000875af1158015612ce4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d0891906140fe565b5050505050565b60008115612d2357612d2033613191565b90505b6040516370a0823160e01b81523060048201526000906001600160a01b038516906370a0823190602401602060405180830381865afa158015612d6a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d8e91906140c8565b905060008115612e4157600254821115612da9575033612dcc565b507f000000000000000000000000889f313e2a3fdc1c9a45bc6020a8a18749cd61525b60405163a9059cbb60e01b81526001600160a01b0382811660048301526024820184905286169063a9059cbb906044016020604051808303816000875af1158015612e1b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e3f91906140fe565b505b60408051848152602081018490526001600160a01b0383168183015290517fd9b066a634638844b3b4701f7bfb9d8791265979e46666f7d7bc04cf4c06c9709181900360600190a15050505050565b6000612ee5826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166132289092919063ffffffff16565b805190915015610db65780806020019051810190612f0391906140fe565b610db65760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f7420737563636565640000000000000000000000000000000000000000000060648201526084016105a7565b60405163927da10560e01b81523060048201526001600160a01b03838116602483015282811660448301526000917f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba39091169063927da10590606401606060405180830381865afa158015612fee573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130129190614830565b509091505073f0000000000000000000000000000000000000006001600160a01b0382161061304057505050565b6130766001600160a01b0384167f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3600019613241565b6040516387517c4560e01b81526001600160a01b03848116600483015283811660248301526044820181905265ffffffffffff60648301527f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba316906387517c4590608401600060405180830381600087803b1580156130f457600080fd5b505af1158015613108573d6000803e3d6000fd5b50505050505050565b60005b8151811015612c1057613141848383815181106131335761313361470d565b60200260200101518561335d565b73b47e3cd837ddf8e4c57f05d70ab865de6e193bba196001600160a01b038516016131895761318982828151811061317b5761317b61470d565b60200260200101518461362b565b600101613114565b6040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa1580156131f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061321c91906140c8565b90506121128282612072565b60606132378484600085613714565b90505b9392505050565b8015806132bb5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015613295573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132b991906140c8565b155b61332d5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527f20746f206e6f6e2d7a65726f20616c6c6f77616e63650000000000000000000060648201526084016105a7565b6040516001600160a01b038316602482015260448101829052610db690849063095ea7b360e01b9060640161183a565b60606001600160a01b03841673b47e3cd837ddf8e4c57f05d70ab865de6e193bbb148015906133a957506001600160a01b0384167306012c8cf97bead5deae237070f9587f8e7a266d14155b15613401576040513360248201526001600160a01b03831660448201526064810184905260840160408051601f198184030181529190526020810180516001600160e01b0316632142170760e11b17905290506135a9565b73b47e3cd837ddf8e4c57f05d70ab865de6e193bba196001600160a01b038516016135635760008360405160240161343b91815260200190565b60408051601f198184030181529181526020820180516001600160e01b0316630b02f02d60e31b17905251909150600090819073b47e3cd837ddf8e4c57f05d70ab865de6e193bbb9061348f90859061487d565b600060405180830381855afa9150503d80600081146134ca576040519150601f19603f3d011682016040523d82523d6000602084013e6134cf565b606091505b50915091506000818060200190518101906134ea91906140e1565b905082158061350257506001600160a01b0381163314155b1561352057604051631022318760e21b815260040160405180910390fd5b6040516024810188905260440160408051601f198184030181529190526020810180516001600160e01b031663104c9fd360e31b17905294506135a99350505050565b6040513360248201523060448201526064810184905260840160408051601f198184030181529190526020810180516001600160e01b03166323b872dd60e01b17905290505b600080856001600160a01b0316836040516135c4919061487d565b6000604051808303816000865af19150503d8060008114613601576040519150601f19603f3d011682016040523d82523d6000602084013e613606565b606091505b50915091508181906131085760405162461bcd60e51b81526004016105a79190614899565b604051602481018390526000604482018190526001600160a01b03831660648301529060840160408051601f198184030181529181526020820180516001600160e01b031663bf31196f60e01b17905251909150600090819073b47e3cd837ddf8e4c57f05d70ab865de6e193bbb906136a590859061487d565b6000604051808303816000865af19150503d80600081146136e2576040519150601f19603f3d011682016040523d82523d6000602084013e6136e7565b606091505b509150915081819061370c5760405162461bcd60e51b81526004016105a79190614899565b505050505050565b60608247101561378c5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f60448201527f722063616c6c000000000000000000000000000000000000000000000000000060648201526084016105a7565b6001600160a01b0385163b6137e35760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016105a7565b600080866001600160a01b031685876040516137ff919061487d565b60006040518083038185875af1925050503d806000811461383c576040519150601f19603f3d011682016040523d82523d6000602084013e613841565b606091505b509150915061385182828661385c565b979650505050505050565b6060831561386b57508161323a565b82511561387b5782518084602001fd5b8160405162461bcd60e51b81526004016105a79190614899565b6001600160a01b038116811461064f57600080fd5b6000602082840312156138bc57600080fd5b813561323a81613895565b6000602082840312156138d957600080fd5b81356001600160e01b03198116811461323a57600080fd5b801515811461064f57600080fd5b60006020828403121561391157600080fd5b813561323a816138f1565b803561211281613895565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff8111828210171561396057613960613927565b60405290565b6040516080810167ffffffffffffffff8111828210171561396057613960613927565b604051601f8201601f1916810167ffffffffffffffff811182821017156139b2576139b2613927565b604052919050565b600082601f8301126139cb57600080fd5b813567ffffffffffffffff8111156139e5576139e5613927565b6139f8601f8201601f1916602001613989565b818152846020838601011115613a0d57600080fd5b816020850160208301376000918101602001919091529392505050565b60008060008060808587031215613a4057600080fd5b8435613a4b81613895565b93506020850135613a5b81613895565b925060408501359150606085013567ffffffffffffffff811115613a7e57600080fd5b613a8a878288016139ba565b91505092959194509250565b60008083601f840112613aa857600080fd5b50813567ffffffffffffffff811115613ac057600080fd5b6020830191508360208260051b8501011115613adb57600080fd5b9250929050565b600080600080600080600080600060c08a8c031215613b0057600080fd5b8935985060208a013567ffffffffffffffff80821115613b1f57600080fd5b613b2b8d838e01613a96565b909a50985060408c0135915080821115613b4457600080fd5b613b508d838e01613a96565b909850965060608c0135915080821115613b6957600080fd5b50613b768c828d01613a96565b90955093505060808a0135915060a08a0135613b9181613895565b809150509295985092959850929598565b60008083601f840112613bb457600080fd5b50813567ffffffffffffffff811115613bcc57600080fd5b602083019150836020828501011115613adb57600080fd5b600080600080600080600060a0888a031215613bff57600080fd5b87359650602088013567ffffffffffffffff80821115613c1e57600080fd5b613c2a8b838c01613a96565b909850965060408a0135915080821115613c4357600080fd5b50613c508a828b01613ba2565b9095509350506060880135613c6481613895565b91506080880135613c74816138f1565b8091505092959891949750929550565b60006101208284031215613c9757600080fd5b50919050565b600080600060408486031215613cb257600080fd5b833567ffffffffffffffff80821115613cca57600080fd5b613cd687838801613c84565b94506020860135915080821115613cec57600080fd5b50613cf986828701613ba2565b9497909650939450505050565b600080600080600080600060a0888a031215613d2157600080fd5b87359650602088013567ffffffffffffffff80821115613d4057600080fd5b613d4c8b838c01613a96565b909850965060408a0135915080821115613d6557600080fd5b50613d728a828b01613a96565b909550935050606088013591506080880135613c7481613895565b600080600080600080600080600060c08a8c031215613dab57600080fd5b8935985060208a013567ffffffffffffffff80821115613dca57600080fd5b613dd68d838e01613a96565b909a50985060408c0135915080821115613def57600080fd5b613dfb8d838e01613a96565b909850965060608c0135915080821115613e1457600080fd5b50613e218c828d01613ba2565b90955093505060808a0135613e3581613895565b915060a08a0135613b91816138f1565b600060208284031215613e5757600080fd5b5035919050565b600082601f830112613e6f57600080fd5b8135602067ffffffffffffffff821115613e8b57613e8b613927565b8160051b613e9a828201613989565b9283528481018201928281019087851115613eb457600080fd5b83870192505b8483101561385157823582529183019190830190613eba565b600080600080600060a08688031215613eeb57600080fd5b8535613ef681613895565b94506020860135613f0681613895565b9350604086013567ffffffffffffffff80821115613f2357600080fd5b613f2f89838a01613e5e565b94506060880135915080821115613f4557600080fd5b613f5189838a01613e5e565b93506080880135915080821115613f6757600080fd5b50613f74888289016139ba565b9150509295509295909350565b600060208284031215613f9357600080fd5b813567ffffffffffffffff811115613faa57600080fd5b611c8784828501613c84565b60008060008060008060008060c0898b031215613fd257600080fd5b88359750602089013567ffffffffffffffff80821115613ff157600080fd5b613ffd8c838d01613a96565b909950975060408b013591508082111561401657600080fd5b506140238b828c01613ba2565b909650945050606089013561403781613895565b92506080890135915060a089013561404e816138f1565b809150509295985092959890939650565b600080600080600060a0868803121561407757600080fd5b853561408281613895565b9450602086013561409281613895565b93506040860135925060608601359150608086013567ffffffffffffffff8111156140bc57600080fd5b613f74888289016139ba565b6000602082840312156140da57600080fd5b5051919050565b6000602082840312156140f357600080fd5b815161323a81613895565b60006020828403121561411057600080fd5b815161323a816138f1565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561414d57600080fd5b8260051b8083602087013760009401602001938452509192915050565b60006001600160a01b03808916835280881660208401525060a0604083015261419760a08301868861411b565b82810360608401526141aa81858761411b565b8381036080909401939093525050600081526020019695505050505050565b60e0815260006141dd60e083018c8e61411b565b82810360208401526141f0818b8d61411b565b9050828103604084015261420581898b61411b565b6001600160a01b0397881660608501529590961660808301525060a0810192909252151560c090910152979650505050505050565b89815260c06020820152600061425460c083018a8c61411b565b828103604084015261426781898b61411b565b9050828103606084015261427c81878961411b565b9150508360808301526001600160a01b03831660a08301529a9950505050505050505050565b634e487b7160e01b600052601160045260246000fd5b600082198211156142cb576142cb6142a2565b500190565b6000828210156142e2576142e26142a2565b500390565b65ffffffffffff8116811461064f57600080fd5b600080600083850361010081121561431257600080fd5b843561431d81613895565b9350601f190160c081121561433157600080fd5b61433961393d565b608082121561434757600080fd5b61434f613966565b9150602086013561435f81613895565b8252604086013561436f81613895565b60208301526060860135614382816142e7565b60408301526080860135614395816142e7565b60608301528181526143a960a0870161391c565b602082015260c0860135604082015292505060e084013567ffffffffffffffff8111156143d557600080fd5b6143e1868287016139ba565b9150509250925092565b60005b838110156144065781810151838201526020016143ee565b83811115612c105750506000910152565b6000815180845261442f8160208601602086016143eb565b601f01601f19169290920160200192915050565b60006101006001600160a01b0380871684528551818151166020860152816020820151166040860152604081015165ffffffffffff80821660608801528060608401511660808801525050508060208701511660a085015250604085015160c08401528060e08401526144b881840185614417565b9695505050505050565b600081518084526020808501945080840160005b838110156144f2578151875295820195908201906001016144d6565b509495945050505050565b60e08152600061451160e083018b8d61411b565b8281036020840152614523818b6144c2565b9050828103604084015261453881898b61411b565b6001600160a01b0397881660608501529590961660808301525060a0810192909252151560c0909101529695505050505050565b87815260a06020820152600061458660a08301888a61411b565b828103604084015261459981878961411b565b9150508360608301526001600160a01b038316608083015298975050505050505050565b60008160001904831182151516156145d7576145d76142a2565b500290565b60a0815260006145f060a08301888a61411b565b90506001600160a01b03861660208301528460408301528360608301528215156080830152979650505050505050565b60008261463d57634e487b7160e01b600052601260045260246000fd5b500490565b86815260a06020820152600061465c60a08301878961411b565b6040830195909552506001600160a01b039290921660608301526080909101529392505050565b60808152600061469760808301878961411b565b82810360208401526146a981876144c2565b9150506001600160a01b0380851660408401528084166060840152509695505050505050565b8183823760009101908152919050565b6000806000606084860312156146f457600080fd5b8351925060208401519150604084015190509250925092565b634e487b7160e01b600052603260045260246000fd5b6000806040838503121561473657600080fd5b825161474181613895565b6020939093015192949293505050565b6000808335601e1984360301811261476857600080fd5b83018035915067ffffffffffffffff82111561478357600080fd5b602001915036819003821315613adb57600080fd5b6000808335601e198436030181126147af57600080fd5b83018035915067ffffffffffffffff8211156147ca57600080fd5b6020019150600581901b3603821315613adb57600080fd5b6080815260006147f660808301888a61411b565b828103602084015261480981878961411b565b9150506001600160a01b038085166040840152808416606084015250979650505050505050565b60008060006060848603121561484557600080fd5b835161485081613895565b6020850151909350614861816142e7565b6040850151909250614872816142e7565b809150509250925092565b6000825161488f8184602087016143eb565b9190910192915050565b60208152600061323a602083018461441756fea164736f6c634300080f000a

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

000000000000000000000000c255335bc5abd6928063f5788a5e420554858f01000000000000000000000000250d62a67254a46c0de472d2c9215e1d890cc90f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3000000000000000000000000889f313e2a3fdc1c9a45bc6020a8a18749cd6152000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2

-----Decoded View---------------
Arg [0] : nftxVaultFactory_ (address): 0xC255335bc5aBd6928063F5788a5E420554858f01
Arg [1] : universalRouter_ (address): 0x250d62a67254A46c0De472d2c9215E1d890cC90f
Arg [2] : PERMIT2_ (address): 0x000000000022D473030F116dDEE9F6B43aC78BA3
Arg [3] : inventoryStaking_ (address): 0x889f313e2a3FDC1c9a45bC6020A8a18749CD6152
Arg [4] : WETH_ (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 000000000000000000000000c255335bc5abd6928063f5788a5e420554858f01
Arg [1] : 000000000000000000000000250d62a67254a46c0de472d2c9215e1d890cc90f
Arg [2] : 000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3
Arg [3] : 000000000000000000000000889f313e2a3fdc1c9a45bc6020a8a18749cd6152
Arg [4] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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