ETH Price: $1,915.06 (+0.19%)

Transaction Decoder

Block:
15664912 at Oct-03-2022 03:22:11 AM +UTC
Transaction Fee:
0.001360432542920186 ETH $2.61
Gas Used:
166,561 Gas / 8.167773626 Gwei

Emitted Events:

99 LSSVMPairEnumerableETH.SpotPriceUpdate( newSpotPrice=73134328358208960 )
100 poobs.Approval( owner=LSSVMPairEnumerableETH, approved=0x00000000...000000000, tokenId=1521 )
101 poobs.Transfer( from=LSSVMPairEnumerableETH, to=[Sender] 0xca27da7eb4c208653847a0255b2589f1929fb66c, tokenId=1521 )
102 LSSVMPairEnumerableETH.SwapNFTOutPair( )

Account State Difference:

  Address   Before After State Difference Code
0x0bf3cf79...F8D4fbca4
0x1f4493c6...183BFe20f
0x3FB65FEE...97a35C8D4 6.437023344171122087 Eth6.510157672529331047 Eth0.07313432835820896
0xb16c1342...DB289c0A4
(sudoswap: Pair Factory)
172.02944205797719218 Eth172.029807729618983224 Eth0.000365671641791044
0xCA27DA7e...1929FB66c
0.08537505049821028 Eth
Nonce: 101
0.01051461795529009 Eth
Nonce: 102
0.07486043254292019
(bloXroute: Max Profit Builder)
1.516834314448884226 Eth1.517084155948884226 Eth0.0002498415

Execution Trace

ETH 0.073500000000000004 GemSwap.batchBuyWithETH( tradeDetails= )
  • MarketRegistry.markets( 20 ) => ( proxy=0x0e813d5b67AD3F228856EA86AB09900baA0D8841, isLib=True, isActive=True )
  • ETH 0.073500000000000004 0x0e813d5b67ad3f228856ea86ab09900baa0d8841.41ad2980( )
    • ETH 0.073500000000000004 LSSVMRouter.swapETHForSpecificNFTs( swapList=, ethRecipient=0xCA27DA7eB4c208653847A0255B2589F1929FB66c, nftRecipient=0xCA27DA7eB4c208653847A0255B2589F1929FB66c, deadline=1664767931 ) => ( remainingValue=0 )
      • LSSVMPairEnumerableETH.getBuyNFTQuote( numNFTs=1 ) => ( error=0, newSpotPrice=73134328358208960, newDelta=4500000000000000, inputAmount=73500000000000004, protocolFee=365671641791044 )
        • LSSVMPairEnumerableETH.getBuyNFTQuote( numNFTs=1 ) => ( error=0, newSpotPrice=73134328358208960, newDelta=4500000000000000, inputAmount=73500000000000004, protocolFee=365671641791044 )
          • LSSVMPairFactory.STATICCALL( )
          • LinearCurve.getBuyInfo( spotPrice=68634328358208960, delta=4500000000000000, numItems=1, feeMultiplier=0, protocolFeeMultiplier=5000000000000000 ) => ( error=0, newSpotPrice=73134328358208960, newDelta=4500000000000000, inputValue=73500000000000004, protocolFee=365671641791044 )
          • ETH 0.073500000000000004 LSSVMPairEnumerableETH.swapTokenForSpecificNFTs( nftIds=[1521], maxExpectedTokenInput=73500000000000004, nftRecipient=0xCA27DA7eB4c208653847A0255B2589F1929FB66c, isRouter=True, routerCaller=0x83C8F28c26bF6aaca652Df1DbBE0e1b56F8baBa2 ) => ( inputAmount=73500000000000004 )
            • ETH 0.073500000000000004 LSSVMPairEnumerableETH.swapTokenForSpecificNFTs( nftIds=[1521], maxExpectedTokenInput=73500000000000004, nftRecipient=0xCA27DA7eB4c208653847A0255B2589F1929FB66c, isRouter=True, routerCaller=0x83C8F28c26bF6aaca652Df1DbBE0e1b56F8baBa2 ) => ( inputAmount=73500000000000004 )
              • LSSVMPairFactory.STATICCALL( )
              • LinearCurve.getBuyInfo( spotPrice=68634328358208960, delta=4500000000000000, numItems=1, feeMultiplier=0, protocolFeeMultiplier=5000000000000000 ) => ( error=0, newSpotPrice=73134328358208960, newDelta=4500000000000000, inputValue=73500000000000004, protocolFee=365671641791044 )
              • ETH 0.07313432835820896 0x3fb65feeab83bf60b0d1ffbc4217d2d97a35c8d4.CALL( )
              • ETH 0.000365671641791044 LSSVMPairFactory.CALL( )
              • poobs.safeTransferFrom( from=0x1f4493c6b41bE9d85C22bD091E6d199183BFe20f, to=0xCA27DA7eB4c208653847A0255B2589F1929FB66c, tokenId=1521 )
                File 1 of 8: GemSwap
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                import "@openzeppelin/contracts/access/Ownable.sol";
                import "./utils/ReentrancyGuard.sol";
                import "./markets/MarketRegistry.sol";
                import "./SpecialTransferHelper.sol";
                import "../../interfaces/markets/tokens/IERC20.sol";
                import "../../interfaces/markets/tokens/IERC721.sol";
                import "../../interfaces/markets/tokens/IERC1155.sol";
                contract GemSwap is SpecialTransferHelper, Ownable, ReentrancyGuard {
                    struct OpenseaTrades {
                        uint256 value;
                        bytes tradeData;
                    }
                    struct ERC20Details {
                        address[] tokenAddrs;
                        uint256[] amounts;
                    }
                    struct ERC1155Details {
                        address tokenAddr;
                        uint256[] ids;
                        uint256[] amounts;
                    }
                    struct ConverstionDetails {
                        bytes conversionData;
                    }
                    struct AffiliateDetails {
                        address affiliate;
                        bool isActive;
                    }
                    struct SponsoredMarket {
                        uint256 marketId;
                        bool isActive;
                    }
                    address public constant GOV = 0x83d841bC0450D5Ac35DCAd8d05Db53EbA29978c2;
                    address public guardian;
                    address public converter;
                    address public punkProxy;
                    uint256 public baseFees;
                    bool public openForTrades;
                    bool public openForFreeTrades;
                    MarketRegistry public marketRegistry;
                    AffiliateDetails[] public affiliates;
                    SponsoredMarket[] public sponsoredMarkets;
                    modifier isOpenForTrades() {
                        require(openForTrades, "trades not allowed");
                        _;
                    }
                    modifier isOpenForFreeTrades() {
                        require(openForFreeTrades, "free trades not allowed");
                        _;
                    }
                    constructor(address _marketRegistry, address _converter, address _guardian) {
                        marketRegistry = MarketRegistry(_marketRegistry);
                        converter = _converter;
                        guardian = _guardian;
                        baseFees = 0;
                        openForTrades = true;
                        openForFreeTrades = true;
                        affiliates.push(AffiliateDetails(GOV, true));
                    }
                    function setUp() external onlyOwner {
                        // Create CryptoPunk Proxy
                        IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).registerProxy();
                        punkProxy = IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).proxyInfo(address(this));
                        // approve wrapped mooncats rescue to Acclimated​MoonCats contract
                        IERC721(0x7C40c393DC0f283F318791d746d894DdD3693572).setApprovalForAll(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, true);
                    }
                    // @audit This function is used to approve specific tokens to specific market contracts with high volume.
                    // This is done in very rare cases for the gas optimization purposes. 
                    function setOneTimeApproval(IERC20 token, address operator, uint256 amount) external onlyOwner {
                        token.approve(operator, amount);
                    }
                    function updateGuardian(address _guardian) external onlyOwner {
                        guardian = _guardian;
                    }
                    function addAffiliate(address _affiliate) external onlyOwner {
                        affiliates.push(AffiliateDetails(_affiliate, true));
                    }
                    function updateAffiliate(uint256 _affiliateIndex, address _affiliate, bool _IsActive) external onlyOwner {
                        affiliates[_affiliateIndex] = AffiliateDetails(_affiliate, _IsActive);
                    }
                    function addSponsoredMarket(uint256 _marketId) external onlyOwner {
                        sponsoredMarkets.push(SponsoredMarket(_marketId, true));
                    }
                    function updateSponsoredMarket(uint256 _marketIndex, uint256 _marketId, bool _isActive) external onlyOwner {
                        sponsoredMarkets[_marketIndex] = SponsoredMarket(_marketId, _isActive);
                    }
                    function setBaseFees(uint256 _baseFees) external onlyOwner {
                        baseFees = _baseFees;
                    }
                    function setOpenForTrades(bool _openForTrades) external onlyOwner {
                        openForTrades = _openForTrades;
                    }
                    function setOpenForFreeTrades(bool _openForFreeTrades) external onlyOwner {
                        openForFreeTrades = _openForFreeTrades;
                    }
                    // @audit we will setup a system that will monitor the contract for any leftover
                    // assets. In case any asset is leftover, the system should be able to trigger this
                    // function to close all the trades until the leftover assets are rescued.
                    function closeAllTrades() external {
                        require(_msgSender() == guardian);
                        openForTrades = false;
                        openForFreeTrades = false;
                    }
                    function setConverter(address _converter) external onlyOwner {
                        converter = _converter;
                    }
                    function setMarketRegistry(MarketRegistry _marketRegistry) external onlyOwner {
                        marketRegistry = _marketRegistry;
                    }
                    function _transferEth(address _to, uint256 _amount) internal {
                        bool callStatus;
                        assembly {
                            // Transfer the ETH and store if it succeeded or not.
                            callStatus := call(gas(), _to, _amount, 0, 0, 0, 0)
                        }
                        require(callStatus, "_transferEth: Eth transfer failed");
                    }
                    function _collectFee(uint256[2] memory feeDetails) internal {
                        require(feeDetails[1] >= baseFees, "Insufficient fee");
                        if (feeDetails[1] > 0) {
                            AffiliateDetails memory affiliateDetails = affiliates[feeDetails[0]];
                            affiliateDetails.isActive
                                ? _transferEth(affiliateDetails.affiliate, feeDetails[1])
                                : _transferEth(GOV, feeDetails[1]);
                        }
                    }
                    function _checkCallResult(bool _success) internal pure {
                        if (!_success) {
                            // Copy revert reason from call
                            assembly {
                                returndatacopy(0, 0, returndatasize())
                                revert(0, returndatasize())
                            }
                        }
                    }
                    function _transferFromHelper(
                        ERC20Details memory erc20Details,
                        SpecialTransferHelper.ERC721Details[] memory erc721Details,
                        ERC1155Details[] memory erc1155Details
                    ) internal {
                        // transfer ERC20 tokens from the sender to this contract
                        for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
                            erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i]));
                        }
                        // transfer ERC721 tokens from the sender to this contract
                        for (uint256 i = 0; i < erc721Details.length; i++) {
                            // accept CryptoPunks
                            if (erc721Details[i].tokenAddr == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB) {
                                _acceptCryptoPunk(erc721Details[i]);
                            }
                            // accept Mooncat
                            else if (erc721Details[i].tokenAddr == 0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6) {
                                _acceptMoonCat(erc721Details[i]);
                            }
                            // default
                            else {
                                for (uint256 j = 0; j < erc721Details[i].ids.length; j++) {
                                    IERC721(erc721Details[i].tokenAddr).transferFrom(
                                        _msgSender(),
                                        address(this),
                                        erc721Details[i].ids[j]
                                    );
                                }
                            }
                        }
                        // transfer ERC1155 tokens from the sender to this contract
                        for (uint256 i = 0; i < erc1155Details.length; i++) {
                            IERC1155(erc1155Details[i].tokenAddr).safeBatchTransferFrom(
                                _msgSender(),
                                address(this),
                                erc1155Details[i].ids,
                                erc1155Details[i].amounts,
                                ""
                            );
                        }
                    }
                    function _conversionHelper(
                        ConverstionDetails[] memory _converstionDetails
                    ) internal {
                        for (uint256 i = 0; i < _converstionDetails.length; i++) {
                            // convert to desired asset
                            (bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData);
                            // check if the call passed successfully
                            _checkCallResult(success);
                        }
                    }
                    function _trade(
                        MarketRegistry.TradeDetails[] memory _tradeDetails
                    ) internal {
                        for (uint256 i = 0; i < _tradeDetails.length; i++) {
                            // get market details
                            (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
                            // market should be active
                            require(_isActive, "_trade: InActive Market");
                            // execute trade
                            if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b || _proxy == 0x7f268357A8c2552623316e2562D90e642bB538E5) {
                                _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
                            } else {
                                (bool success, ) = _isLib
                                    ? _proxy.delegatecall(_tradeDetails[i].tradeData)
                                    : _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
                                // check if the call passed successfully
                                _checkCallResult(success);
                            }
                        }
                    }
                    // function _tradeSponsored(
                    //     MarketRegistry.TradeDetails[] memory _tradeDetails,
                    //     uint256 sponsoredMarketId
                    // ) internal returns (bool isSponsored) {
                    //     for (uint256 i = 0; i < _tradeDetails.length; i++) {
                    //         // check if the trade is for the sponsored market
                    //         if (_tradeDetails[i].marketId == sponsoredMarketId) {
                    //             isSponsored = true;
                    //         }
                    //         // get market details
                    //         (address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
                    //         // market should be active
                    //         require(_isActive, "_trade: InActive Market");
                    //         // execute trade
                    //         if (_proxy == 0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b) {
                    //             _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
                    //         } else {
                    //             (bool success, ) = _isLib
                    //                 ? _proxy.delegatecall(_tradeDetails[i].tradeData)
                    //                 : _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
                    //             // check if the call passed successfully
                    //             _checkCallResult(success);
                    //         }
                    //     }
                    // }
                    function _returnDust(address[] memory _tokens) internal {
                        // return remaining ETH (if any)
                        assembly {
                            if gt(selfbalance(), 0) {
                                let callStatus := call(
                                    gas(),
                                    caller(),
                                    selfbalance(),
                                    0,
                                    0,
                                    0,
                                    0
                                )
                            }
                        }
                        // return remaining tokens (if any)
                        for (uint256 i = 0; i < _tokens.length; i++) {
                            if (IERC20(_tokens[i]).balanceOf(address(this)) > 0) {
                                _tokens[i].call(abi.encodeWithSelector(0xa9059cbb, msg.sender, IERC20(_tokens[i]).balanceOf(address(this))));
                            }
                        }
                    }
                    function batchBuyFromOpenSea(
                        OpenseaTrades[] memory openseaTrades
                    ) payable external nonReentrant {
                        // execute trades
                        for (uint256 i = 0; i < openseaTrades.length; i++) {
                            // execute trade
                            address(0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b).call{value:openseaTrades[i].value}(openseaTrades[i].tradeData);
                        }
                        // return remaining ETH (if any)
                        assembly {
                            if gt(selfbalance(), 0) {
                                let callStatus := call(
                                    gas(),
                                    caller(),
                                    selfbalance(),
                                    0,
                                    0,
                                    0,
                                    0
                                )
                            }
                        }
                    }
                    
                    function batchBuyWithETH(
                        MarketRegistry.TradeDetails[] memory tradeDetails
                    ) payable external nonReentrant {
                        // execute trades
                        _trade(tradeDetails);
                        // return remaining ETH (if any)
                        assembly {
                            if gt(selfbalance(), 0) {
                                let callStatus := call(
                                    gas(),
                                    caller(),
                                    selfbalance(),
                                    0,
                                    0,
                                    0,
                                    0
                                )
                            }
                        }
                    }
                    function batchBuyWithERC20s(
                        ERC20Details memory erc20Details,
                        MarketRegistry.TradeDetails[] memory tradeDetails,
                        ConverstionDetails[] memory converstionDetails,
                        address[] memory dustTokens
                    ) payable external nonReentrant {
                        // transfer ERC20 tokens from the sender to this contract
                        for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
                            erc20Details.tokenAddrs[i].call(abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), erc20Details.amounts[i]));
                        }
                        // Convert any assets if needed
                        _conversionHelper(converstionDetails);
                        // execute trades
                        _trade(tradeDetails);
                        // return dust tokens (if any)
                        _returnDust(dustTokens);
                    }
                    // swaps any combination of ERC-20/721/1155
                    // User needs to approve assets before invoking swap
                    // WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
                    function multiAssetSwap(
                        ERC20Details memory erc20Details,
                        SpecialTransferHelper.ERC721Details[] memory erc721Details,
                        ERC1155Details[] memory erc1155Details,
                        ConverstionDetails[] memory converstionDetails,
                        MarketRegistry.TradeDetails[] memory tradeDetails,
                        address[] memory dustTokens,
                        uint256[2] memory feeDetails    // [affiliateIndex, ETH fee in Wei]
                    ) payable external isOpenForTrades nonReentrant {
                        // collect fees
                        _collectFee(feeDetails);
                        // transfer all tokens
                        _transferFromHelper(
                            erc20Details,
                            erc721Details,
                            erc1155Details
                        );
                        // Convert any assets if needed
                        _conversionHelper(converstionDetails);
                        // execute trades
                        _trade(tradeDetails);
                        // return dust tokens (if any)
                        _returnDust(dustTokens);
                    }
                    // Utility function that is used for free swaps for sponsored markets
                    // WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! 
                    // function multiAssetSwapWithoutFee(
                    //     ERC20Details memory erc20Details,
                    //     SpecialTransferHelper.ERC721Details[] memory erc721Details,
                    //     ERC1155Details[] memory erc1155Details,
                    //     ConverstionDetails[] memory converstionDetails,
                    //     MarketRegistry.TradeDetails[] memory tradeDetails,
                    //     address[] memory dustTokens,
                    //     uint256 sponsoredMarketIndex
                    // ) payable external isOpenForFreeTrades nonReentrant {
                    //     // fetch the marketId of the sponsored market
                    //     SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex];
                    //     // check if the market is active
                    //     require(sponsoredMarket.isActive, "multiAssetSwapWithoutFee: InActive sponsored market");
                // 
                    //     // transfer all tokens
                    //     _transferFromHelper(
                    //         erc20Details,
                    //         erc721Details,
                    //         erc1155Details
                    //     );
                // 
                    //     // Convert any assets if needed
                    //     _conversionHelper(converstionDetails);
                // 
                    //     // execute trades
                    //     bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId);
                // 
                    //     // check if the trades include the sponsored market
                    //     require(isSponsored, "multiAssetSwapWithoutFee: trades do not include sponsored market");
                // 
                    //     // return dust tokens (if any)
                    //     _returnDust(dustTokens);
                    // }
                    function onERC1155Received(
                        address,
                        address,
                        uint256,
                        uint256,
                        bytes calldata
                    ) public virtual returns (bytes4) {
                        return this.onERC1155Received.selector;
                    }
                    function onERC1155BatchReceived(
                        address,
                        address,
                        uint256[] calldata,
                        uint256[] calldata,
                        bytes calldata
                    ) public virtual returns (bytes4) {
                        return this.onERC1155BatchReceived.selector;
                    }
                    function onERC721Received(
                        address,
                        address,
                        uint256,
                        bytes calldata
                    ) external virtual returns (bytes4) {
                        return 0x150b7a02;
                    }
                    // Used by ERC721BasicToken.sol
                    function onERC721Received(
                        address,
                        uint256,
                        bytes calldata
                    ) external virtual returns (bytes4) {
                        return 0xf0b9e5ba;
                    }
                    function supportsInterface(bytes4 interfaceId)
                        external
                        virtual
                        view
                        returns (bool)
                    {
                        return interfaceId == this.supportsInterface.selector;
                    }
                    receive() external payable {}
                    // Emergency function: In case any ETH get stuck in the contract unintentionally
                    // Only owner can retrieve the asset balance to a recipient address
                    function rescueETH(address recipient) onlyOwner external {
                        _transferEth(recipient, address(this).balance);
                    }
                    // Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally
                    // Only owner can retrieve the asset balance to a recipient address
                    function rescueERC20(address asset, address recipient) onlyOwner external { 
                        asset.call(abi.encodeWithSelector(0xa9059cbb, recipient, IERC20(asset).balanceOf(address(this))));
                    }
                    // Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally
                    // Only owner can retrieve the asset balance to a recipient address
                    function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external {
                        for (uint256 i = 0; i < ids.length; i++) {
                            IERC721(asset).transferFrom(address(this), recipient, ids[i]);
                        }
                    }
                    // Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally
                    // Only owner can retrieve the asset balance to a recipient address
                    function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external {
                        for (uint256 i = 0; i < ids.length; i++) {
                            IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], "");
                        }
                    }
                }// SPDX-License-Identifier: MIT
                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() {
                        _setOwner(_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 {
                        _setOwner(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");
                        _setOwner(newOwner);
                    }
                    function _setOwner(address newOwner) private {
                        address oldOwner = _owner;
                        _owner = newOwner;
                        emit OwnershipTransferred(oldOwner, newOwner);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                /// @notice Gas optimized reentrancy protection for smart contracts.
                /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
                abstract contract ReentrancyGuard {
                    uint256 private reentrancyStatus = 1;
                    modifier nonReentrant() {
                        require(reentrancyStatus == 1, "REENTRANCY");
                        reentrancyStatus = 2;
                        _;
                        reentrancyStatus = 1;
                    }
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                import "@openzeppelin/contracts/access/Ownable.sol";
                contract MarketRegistry is Ownable {
                    struct TradeDetails {
                        uint256 marketId;
                        uint256 value;
                        bytes tradeData;
                    }
                    struct Market {
                        address proxy;
                        bool isLib;
                        bool isActive;
                    }
                    Market[] public markets;
                    constructor(address[] memory proxies, bool[] memory isLibs) {
                        for (uint256 i = 0; i < proxies.length; i++) {
                            markets.push(Market(proxies[i], isLibs[i], true));
                        }
                    }
                    function addMarket(address proxy, bool isLib) external onlyOwner {
                        markets.push(Market(proxy, isLib, true));
                    }
                    function setMarketStatus(uint256 marketId, bool newStatus) external onlyOwner {
                        Market storage market = markets[marketId];
                        market.isActive = newStatus;
                    }
                    function setMarketProxy(uint256 marketId, address newProxy, bool isLib) external onlyOwner {
                        Market storage market = markets[marketId];
                        market.proxy = newProxy;
                        market.isLib = isLib;
                    }
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                import "@openzeppelin/contracts/utils/Context.sol";
                import "../../interfaces/punks/ICryptoPunks.sol";
                import "../../interfaces/punks/IWrappedPunk.sol";
                import "../../interfaces/mooncats/IMoonCatsRescue.sol";
                contract SpecialTransferHelper is Context {
                    struct ERC721Details {
                        address tokenAddr;
                        address[] to;
                        uint256[] ids;
                    }
                    function _uintToBytes5(uint256 id)
                        internal
                        pure
                        returns (bytes5 slicedDataBytes5)
                    {
                        bytes memory _bytes = new bytes(32);
                        assembly {
                            mstore(add(_bytes, 32), id)
                        }
                        bytes memory tempBytes;
                        assembly {
                            // 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(5, 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, 5)
                            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))), 27)
                            } lt(mc, end) {
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                mstore(mc, mload(cc))
                            }
                            mstore(tempBytes, 5)
                            //update free-memory pointer
                            //allocating the array padded to 32 bytes like the compiler does now
                            mstore(0x40, and(add(mc, 31), not(31)))
                        }
                        assembly {
                            slicedDataBytes5 := mload(add(tempBytes, 32))
                        }
                    }
                    function _acceptMoonCat(ERC721Details memory erc721Details) internal {
                        for (uint256 i = 0; i < erc721Details.ids.length; i++) {
                            bytes5 catId = _uintToBytes5(erc721Details.ids[i]);
                            address owner = IMoonCatsRescue(erc721Details.tokenAddr).catOwners(catId);
                            require(owner == _msgSender(), "_acceptMoonCat: invalid mooncat owner");
                            IMoonCatsRescue(erc721Details.tokenAddr).acceptAdoptionOffer(catId);
                        }
                    }
                    function _transferMoonCat(ERC721Details memory erc721Details) internal {
                        for (uint256 i = 0; i < erc721Details.ids.length; i++) {
                            IMoonCatsRescue(erc721Details.tokenAddr).giveCat(_uintToBytes5(erc721Details.ids[i]), erc721Details.to[i]);
                        }
                    }
                    function _acceptCryptoPunk(ERC721Details memory erc721Details) internal {
                        for (uint256 i = 0; i < erc721Details.ids.length; i++) {    
                            address owner = ICryptoPunks(erc721Details.tokenAddr).punkIndexToAddress(erc721Details.ids[i]);
                            require(owner == _msgSender(), "_acceptCryptoPunk: invalid punk owner");
                            ICryptoPunks(erc721Details.tokenAddr).buyPunk(erc721Details.ids[i]);
                        }
                    }
                    function _transferCryptoPunk(ERC721Details memory erc721Details) internal {
                        for (uint256 i = 0; i < erc721Details.ids.length; i++) {
                            ICryptoPunks(erc721Details.tokenAddr).transferPunk(erc721Details.to[i], erc721Details.ids[i]);
                        }
                    }
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                interface IERC20 {
                    /**
                        * @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 `recipient`.
                        *
                        * Returns a boolean value indicating whether the operation succeeded.
                        *
                        * Emits a {Transfer} event.
                        */
                    function transfer(address recipient, uint256 amount) external returns (bool);
                    /**
                     * @dev Moves `amount` tokens from `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);
                    /**
                     * @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 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);
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                interface IERC721 {
                    /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
                    ///  TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
                    ///  THEY MAY BE PERMANENTLY LOST
                    /// @dev Throws unless `msg.sender` is the current owner, an authorized
                    ///  operator, or the approved address for this NFT. Throws if `_from` is
                    ///  not the current owner. Throws if `_to` is the zero address. Throws if
                    ///  `_tokenId` is not a valid NFT.
                    /// @param _from The current owner of the NFT
                    /// @param _to The new owner
                    /// @param _tokenId The NFT to transfer
                    function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
                    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external;
                    
                    function setApprovalForAll(address operator, bool approved) external;
                    function approve(address to, uint256 tokenId) external;
                    
                    function isApprovedForAll(address owner, address operator) external view returns (bool);
                    function balanceOf(address _owner) external view returns (uint256);
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                interface IERC1155 {
                    function safeTransferFrom(
                        address from,
                        address to,
                        uint256 id,
                        uint256 amount,
                        bytes memory data
                    ) external;
                    function safeBatchTransferFrom(
                        address from,
                        address to,
                        uint256[] memory ids,
                        uint256[] memory amounts,
                        bytes memory data
                    ) external;
                    function balanceOf(address _owner, uint256 _id) external view returns (uint256);
                }// SPDX-License-Identifier: MIT
                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;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                interface ICryptoPunks {
                    function punkIndexToAddress(uint index) external view returns(address owner);
                    function offerPunkForSaleToAddress(uint punkIndex, uint minSalePriceInWei, address toAddress) external;
                    function buyPunk(uint punkIndex) external payable;
                    function transferPunk(address to, uint punkIndex) external;
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                interface IWrappedPunk {
                    /**
                     * @dev Mints a wrapped punk
                     */
                    function mint(uint256 punkIndex) external;
                    /**
                     * @dev Burns a specific wrapped punk
                     */
                    function burn(uint256 punkIndex) external;
                    
                    /**
                     * @dev Registers proxy
                     */
                    function registerProxy() external;
                    /**
                     * @dev Gets proxy address
                     */
                    function proxyInfo(address user) external view returns (address);
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.11;
                interface IMoonCatsRescue {
                    function acceptAdoptionOffer(bytes5 catId) payable external;
                    function makeAdoptionOfferToAddress(bytes5 catId, uint price, address to) external;
                    function giveCat(bytes5 catId, address to) external;
                    function catOwners(bytes5 catId) external view returns(address);
                    function rescueOrder(uint256 rescueIndex) external view returns(bytes5 catId);
                }

                File 2 of 8: LSSVMPairEnumerableETH
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMPairETH} from "./LSSVMPairETH.sol";
                import {LSSVMPairEnumerable} from "./LSSVMPairEnumerable.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair where the NFT implements ERC721Enumerable, and the token is ETH
                    @author boredGenius and 0xmons
                 */
                contract LSSVMPairEnumerableETH is LSSVMPairEnumerable, LSSVMPairETH {
                    /**
                        @notice Returns the LSSVMPair type
                     */
                    function pairVariant()
                        public
                        pure
                        override
                        returns (ILSSVMPairFactoryLike.PairVariant)
                    {
                        return ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ETH;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports//IERC721.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                /**
                    @title An NFT/Token pair where the token is ETH
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairETH is LSSVMPair {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    uint256 internal constant IMMUTABLE_PARAMS_LENGTH = 61;
                    /// @inheritdoc LSSVMPair
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool, /*isRouter*/
                        address, /*routerCaller*/
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        require(msg.value >= inputAmount, "Sent too little ETH");
                        // Transfer inputAmount ETH to assetRecipient if it's been set
                        address payable _assetRecipient = getAssetRecipient();
                        if (_assetRecipient != address(this)) {
                            _assetRecipient.safeTransferETH(inputAmount - protocolFee);
                        }
                        // Take protocol fee
                        if (protocolFee > 0) {
                            // Round down to the actual ETH balance if there are numerical stability issues with the bonding curve calculations
                            if (protocolFee > address(this).balance) {
                                protocolFee = address(this).balance;
                            }
                            if (protocolFee > 0) {
                                payable(address(_factory)).safeTransferETH(protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _refundTokenToSender(uint256 inputAmount) internal override {
                        // Give excess ETH back to caller
                        if (msg.value > inputAmount) {
                            payable(msg.sender).safeTransferETH(msg.value - inputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        // Take protocol fee
                        if (protocolFee > 0) {
                            // Round down to the actual ETH balance if there are numerical stability issues with the bonding curve calculations
                            if (protocolFee > address(this).balance) {
                                protocolFee = address(this).balance;
                            }
                            if (protocolFee > 0) {
                                payable(address(_factory)).safeTransferETH(protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal override {
                        // Send ETH to caller
                        if (outputAmount > 0) {
                            tokenRecipient.safeTransferETH(outputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    // @dev see LSSVMPairCloner for params length calculation
                    function _immutableParamsLength() internal pure override returns (uint256) {
                        return IMMUTABLE_PARAMS_LENGTH;
                    }
                    /**
                        @notice Withdraws all token owned by the pair to the owner address.
                        @dev Only callable by the owner.
                     */
                    function withdrawAllETH() external onlyOwner {
                        withdrawETH(address(this).balance);
                    }
                    /**
                        @notice Withdraws a specified amount of token owned by the pair to the owner address.
                        @dev Only callable by the owner.
                        @param amount The amount of token to send to the owner. If the pair's balance is less than
                        this value, the transaction will be reverted.
                     */
                    function withdrawETH(uint256 amount) public onlyOwner {
                        payable(owner()).safeTransferETH(amount);
                        // emit event since ETH is the pair token
                        emit TokenWithdrawal(amount);
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC20(ERC20 a, uint256 amount)
                        external
                        override
                        onlyOwner
                    {
                        a.safeTransfer(msg.sender, amount);
                    }
                    /**
                        @dev All ETH transfers into the pair are accepted. This is the main method
                        for the owner to top up the pair's token reserves.
                     */
                    receive() external payable {
                        emit TokenDeposit(msg.value);
                    }
                    /**
                        @dev All ETH transfers into the pair are accepted. This is the main method
                        for the owner to top up the pair's token reserves.
                     */
                    fallback() external payable {
                        // Only allow calls without function selector
                        require(msg.data.length == _immutableParamsLength());
                        emit TokenDeposit(msg.value);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                abstract contract ERC20 {
                    /*///////////////////////////////////////////////////////////////
                                                  EVENTS
                    //////////////////////////////////////////////////////////////*/
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 amount
                    );
                    /*///////////////////////////////////////////////////////////////
                                             METADATA STORAGE
                    //////////////////////////////////////////////////////////////*/
                    string public name;
                    string public symbol;
                    uint8 public immutable decimals;
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    uint256 public totalSupply;
                    mapping(address => uint256) public balanceOf;
                    mapping(address => mapping(address => uint256)) public allowance;
                    /*///////////////////////////////////////////////////////////////
                                           EIP-2612 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    bytes32 public constant PERMIT_TYPEHASH =
                        keccak256(
                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                        );
                    uint256 internal immutable INITIAL_CHAIN_ID;
                    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                    mapping(address => uint256) public nonces;
                    /*///////////////////////////////////////////////////////////////
                                               CONSTRUCTOR
                    //////////////////////////////////////////////////////////////*/
                    constructor(
                        string memory _name,
                        string memory _symbol,
                        uint8 _decimals
                    ) {
                        name = _name;
                        symbol = _symbol;
                        decimals = _decimals;
                        INITIAL_CHAIN_ID = block.chainid;
                        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                    }
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function approve(address spender, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        allowance[msg.sender][spender] = amount;
                        emit Approval(msg.sender, spender, amount);
                        return true;
                    }
                    function transfer(address to, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        balanceOf[msg.sender] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(msg.sender, to, amount);
                        return true;
                    }
                    function transferFrom(
                        address from,
                        address to,
                        uint256 amount
                    ) public virtual returns (bool) {
                        if (allowance[from][msg.sender] != type(uint256).max) {
                            allowance[from][msg.sender] -= amount;
                        }
                        balanceOf[from] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        return true;
                    }
                    /*///////////////////////////////////////////////////////////////
                                              EIP-2612 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public virtual {
                        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                        // Unchecked because the only math done is incrementing
                        // the owner's nonce which cannot realistically overflow.
                        unchecked {
                            bytes32 digest = keccak256(
                                abi.encodePacked(
                                    "\\x19\\x01",
                                    DOMAIN_SEPARATOR(),
                                    keccak256(
                                        abi.encode(
                                            PERMIT_TYPEHASH,
                                            owner,
                                            spender,
                                            value,
                                            nonces[owner]++,
                                            deadline
                                        )
                                    )
                                )
                            );
                            address recoveredAddress = ecrecover(digest, v, r, s);
                            require(
                                recoveredAddress != address(0) && recoveredAddress == owner,
                                "INVALID_PERMIT_SIGNATURE"
                            );
                            allowance[recoveredAddress][spender] = value;
                        }
                        emit Approval(owner, spender, value);
                    }
                    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                        return
                            block.chainid == INITIAL_CHAIN_ID
                                ? INITIAL_DOMAIN_SEPARATOR
                                : computeDomainSeparator();
                    }
                    function computeDomainSeparator() internal view virtual returns (bytes32) {
                        return
                            keccak256(
                                abi.encode(
                                    keccak256(
                                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                                    ),
                                    keccak256(bytes(name)),
                                    keccak256(bytes("1")),
                                    block.chainid,
                                    address(this)
                                )
                            );
                    }
                    /*///////////////////////////////////////////////////////////////
                                       INTERNAL MINT/BURN LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function _mint(address to, uint256 amount) internal virtual {
                        totalSupply += amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(address(0), to, amount);
                    }
                    function _burn(address from, uint256 amount) internal virtual {
                        balanceOf[from] -= amount;
                        // Cannot underflow because a user's balance
                        // will never be larger than the total supply.
                        unchecked {
                            totalSupply -= amount;
                        }
                        emit Transfer(from, address(0), amount);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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`, 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 Returns the account approved for `tokenId` token.
                     *
                     * Requirements:
                     *
                     * - `tokenId` must exist.
                     */
                    function getApproved(uint256 tokenId)
                        external
                        view
                        returns (address operator);
                    /**
                     * @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 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);
                    /**
                     * @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;
                }
                // SPDX-License-Identifier: MIT
                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);
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                import {ERC20} from "./ERC20.sol";
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
                /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                library SafeTransferLib {
                    /*///////////////////////////////////////////////////////////////
                                            ETH OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferETH(address to, uint256 amount) internal {
                        bool callStatus;
                        assembly {
                            // Transfer the ETH and store if it succeeded or not.
                            callStatus := call(gas(), to, amount, 0, 0, 0, 0)
                        }
                        require(callStatus, "ETH_TRANSFER_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                           ERC20 OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferFrom(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x23b872dd00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(from, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "from" argument.
                            mstore(
                                add(freeMemoryPointer, 36),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 100 because the calldata length is 4 + 32 * 3.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FROM_FAILED"
                        );
                    }
                    function safeTransfer(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0xa9059cbb00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FAILED"
                        );
                    }
                    function safeApprove(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x095ea7b300000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                         INTERNAL HELPER LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function didLastOptionalReturnCallSucceed(bool callStatus)
                        private
                        pure
                        returns (bool success)
                    {
                        assembly {
                            // Get how many bytes the call returned.
                            let returnDataSize := returndatasize()
                            // If the call reverted:
                            if iszero(callStatus) {
                                // Copy the revert message into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Revert with the same message.
                                revert(0, returnDataSize)
                            }
                            switch returnDataSize
                            case 32 {
                                // Copy the return data into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Set success to whether it returned true.
                                success := iszero(iszero(mload(0)))
                            }
                            case 0 {
                                // There was no return data.
                                success := 1
                            }
                            default {
                                // It returned some malformed input.
                                success := 0
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {OwnableWithTransferCallback} from "./lib/OwnableWithTransferCallback.sol";
                import {ReentrancyGuard} from "./lib/ReentrancyGuard.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                import {IERC1155} from "./imports/IERC1155.sol";
                import {ERC1155Holder} from "./imports/ERC1155Holder.sol";
                /// @title The base contract for an NFT/TOKEN AMM pair
                /// @author boredGenius and 0xmons
                /// @notice This implements the core swap logic from NFT to TOKEN
                abstract contract LSSVMPair is
                    OwnableWithTransferCallback,
                    ReentrancyGuard,
                    ERC1155Holder
                {
                    enum PoolType {
                        TOKEN,
                        NFT,
                        TRADE
                    }
                    // 90%, must <= 1 - MAX_PROTOCOL_FEE (set in LSSVMPairFactory)
                    uint256 internal constant MAX_FEE = 0.90e18;
                    // The current price of the NFT
                    // @dev This is generally used to mean the immediate sell price for the next marginal NFT.
                    // However, this should NOT be assumed, as future bonding curves may use spotPrice in different ways.
                    // Use getBuyNFTQuote and getSellNFTQuote for accurate pricing info.
                    uint128 public spotPrice;
                    // The parameter for the pair's bonding curve.
                    // Units and meaning are bonding curve dependent.
                    uint128 public delta;
                    // The spread between buy and sell prices, set to be a multiplier we apply to the buy price
                    // Fee is only relevant for TRADE pools
                    // Units are in base 1e18
                    uint96 public fee;
                    // If set to 0, NFTs/tokens sent by traders during trades will be sent to the pair.
                    // Otherwise, assets will be sent to the set address. Not available for TRADE pools.
                    address payable public assetRecipient;
                    // Events
                    event SwapNFTInPair();
                    event SwapNFTOutPair();
                    event SpotPriceUpdate(uint128 newSpotPrice);
                    event TokenDeposit(uint256 amount);
                    event TokenWithdrawal(uint256 amount);
                    event NFTWithdrawal();
                    event DeltaUpdate(uint128 newDelta);
                    event FeeUpdate(uint96 newFee);
                    event AssetRecipientChange(address a);
                    // Parameterized Errors
                    error BondingCurveError(CurveErrorCodes.Error error);
                    /**
                      @notice Called during pair creation to set initial parameters
                      @dev Only called once by factory to initialize.
                      We verify this by making sure that the current owner is address(0). 
                      The Ownable library we use disallows setting the owner to be address(0), so this condition
                      should only be valid before the first initialize call. 
                      @param _owner The owner of the pair
                      @param _assetRecipient The address that will receive the TOKEN or NFT sent to this pair during swaps. NOTE: If set to address(0), they will go to the pair itself.
                      @param _delta The initial delta of the bonding curve
                      @param _fee The initial % fee taken, if this is a trade pair 
                      @param _spotPrice The initial price to sell an asset into the pair
                     */
                    function initialize(
                        address _owner,
                        address payable _assetRecipient,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice
                    ) external payable {
                        require(owner() == address(0), "Initialized");
                        __Ownable_init(_owner);
                        __ReentrancyGuard_init();
                        ICurve _bondingCurve = bondingCurve();
                        PoolType _poolType = poolType();
                        if ((_poolType == PoolType.TOKEN) || (_poolType == PoolType.NFT)) {
                            require(_fee == 0, "Only Trade Pools can have nonzero fee");
                            assetRecipient = _assetRecipient;
                        } else if (_poolType == PoolType.TRADE) {
                            require(_fee < MAX_FEE, "Trade fee must be less than 90%");
                            require(
                                _assetRecipient == address(0),
                                "Trade pools can't set asset recipient"
                            );
                            fee = _fee;
                        }
                        require(_bondingCurve.validateDelta(_delta), "Invalid delta for curve");
                        require(
                            _bondingCurve.validateSpotPrice(_spotPrice),
                            "Invalid new spot price for curve"
                        );
                        delta = _delta;
                        spotPrice = _spotPrice;
                    }
                    /**
                     * External state-changing functions
                     */
                    /**
                        @notice Sends token to the pair in exchange for any `numNFTs` NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo.
                        This swap function is meant for users who are ID agnostic
                        @param numNFTs The number of NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForAnyNFTs(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        IERC721 _nft = nft();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(
                                (numNFTs > 0) && (numNFTs <= _nft.balanceOf(address(this))),
                                "Ask for > 0 and <= balanceOf NFTs"
                            );
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            numNFTs,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendAnyNFTsToRecipient(_nft, nftRecipient, numNFTs);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends token to the pair in exchange for a specific set of NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo
                        This swap is meant for users who want specific IDs. Also higher chance of
                        reverting if some of the specified IDs leave the pool before the swap goes through.
                        @param nftIds The list of IDs of the NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForSpecificNFTs(
                        uint256[] calldata nftIds,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require((nftIds.length > 0), "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            nftIds.length,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendSpecificNFTsToRecipient(nft(), nftRecipient, nftIds);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends a set of NFTs to the pair in exchange for token
                        @dev To compute the amount of token to that will be received, call bondingCurve.getSellInfo.
                        @param nftIds The list of IDs of the NFTs to sell to the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param tokenRecipient The recipient of the token output
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return outputAmount The amount of token received
                     */
                    function swapNFTsForToken(
                        uint256[] calldata nftIds,
                        uint256 minExpectedTokenOutput,
                        address payable tokenRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external virtual nonReentrant returns (uint256 outputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.TOKEN || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(nftIds.length > 0, "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, outputAmount) = _calculateSellInfoAndUpdatePoolParams(
                            nftIds.length,
                            minExpectedTokenOutput,
                            _bondingCurve,
                            _factory
                        );
                        _sendTokenOutput(tokenRecipient, outputAmount);
                        _payProtocolFeeFromPair(_factory, protocolFee);
                        _takeNFTsFromSender(nft(), nftIds, _factory, isRouter, routerCaller);
                        emit SwapNFTInPair();
                    }
                    /**
                     * View functions
                     */
                    /**
                        @dev Used as read function to query the bonding curve for buy pricing info
                        @param numNFTs The number of NFTs to buy from the pair
                     */
                    function getBuyNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 inputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = bondingCurve().getBuyInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @dev Used as read function to query the bonding curve for sell pricing info
                        @param numNFTs The number of NFTs to sell to the pair
                     */
                    function getSellNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 outputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = bondingCurve().getSellInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @notice Returns all NFT IDs held by the pool
                     */
                    function getAllHeldIds() external view virtual returns (uint256[] memory);
                    /**
                        @notice Returns the pair's variant (NFT is enumerable or not, pair uses ETH or ERC20)
                     */
                    function pairVariant()
                        public
                        pure
                        virtual
                        returns (ILSSVMPairFactoryLike.PairVariant);
                    function factory() public pure returns (ILSSVMPairFactoryLike _factory) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _factory := shr(
                                0x60,
                                calldataload(sub(calldatasize(), paramsLength))
                            )
                        }
                    }
                    /**
                        @notice Returns the type of bonding curve that parameterizes the pair
                     */
                    function bondingCurve() public pure returns (ICurve _bondingCurve) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _bondingCurve := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 20))
                            )
                        }
                    }
                    /**
                        @notice Returns the NFT collection that parameterizes the pair
                     */
                    function nft() public pure returns (IERC721 _nft) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _nft := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 40))
                            )
                        }
                    }
                    /**
                        @notice Returns the pair's type (TOKEN/NFT/TRADE)
                     */
                    function poolType() public pure returns (PoolType _poolType) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _poolType := shr(
                                0xf8,
                                calldataload(add(sub(calldatasize(), paramsLength), 60))
                            )
                        }
                    }
                    /**
                        @notice Returns the address that assets that receives assets when a swap is done with this pair
                        Can be set to another address by the owner, if set to address(0), defaults to the pair's own address
                     */
                    function getAssetRecipient()
                        public
                        view
                        returns (address payable _assetRecipient)
                    {
                        // If it's a TRADE pool, we know the recipient is 0 (TRADE pools can't set asset recipients)
                        // so just return address(this)
                        if (poolType() == PoolType.TRADE) {
                            return payable(address(this));
                        }
                        // Otherwise, we return the recipient if it's been set
                        // or replace it with address(this) if it's 0
                        _assetRecipient = assetRecipient;
                        if (_assetRecipient == address(0)) {
                            // Tokens will be transferred to address(this)
                            _assetRecipient = payable(address(this));
                        }
                    }
                    /**
                     * Internal functions
                     */
                    /**
                        @notice Calculates the amount needed to be sent into the pair for a buy and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to purchase from the pair
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return inputAmount The amount of tokens total tokens receive
                     */
                    function _calculateBuyInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 inputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = _bondingCurve.getBuyInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if input is more than expected
                        require(inputAmount <= maxExpectedTokenInput, "In too many tokens");
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Calculates the amount needed to be sent by the pair for a sell and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to send to the the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return outputAmount The amount of tokens total tokens receive
                     */
                    function _calculateSellInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 minExpectedTokenOutput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 outputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = _bondingCurve.getSellInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if output is too little
                        require(
                            outputAmount >= minExpectedTokenOutput,
                            "Out too little tokens"
                        );
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Pulls the token input of a trade from the trader and pays the protocol fee.
                        @param inputAmount The amount of tokens to be sent
                        @param isRouter Whether or not the caller is LSSVMRouter
                        @param routerCaller If called from LSSVMRouter, store the original caller
                        @param _factory The LSSVMPairFactory which stores LSSVMRouter allowlist info
                        @param protocolFee The protocol fee to be paid
                     */
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool isRouter,
                        address routerCaller,
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends excess tokens back to the caller (if applicable)
                        @dev We send ETH back to the caller even when called from LSSVMRouter because we do an aggregate slippage check for certain bulk swaps. (Instead of sending directly back to the router caller) 
                        Excess ETH sent for one swap can then be used to help pay for the next swap.
                     */
                    function _refundTokenToSender(uint256 inputAmount) internal virtual;
                    /**
                        @notice Sends protocol fee (if it exists) back to the LSSVMPairFactory from the pair
                     */
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends tokens to a recipient
                        @param tokenRecipient The address receiving the tokens
                        @param outputAmount The amount of tokens to send
                     */
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal virtual;
                    /**
                        @notice Sends some number of NFTs to a recipient address, ID agnostic
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param numNFTs The number of NFTs to send  
                     */
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal virtual;
                    /**
                        @notice Sends specific NFTs to a recipient address
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param nftIds The specific IDs of NFTs to send  
                     */
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal virtual;
                    /**
                        @notice Takes NFTs from the caller and sends them into the pair's asset recipient
                        @dev This is used by the LSSVMPair's swapNFTForToken function. 
                        @param _nft The NFT collection to take from
                        @param nftIds The specific NFT IDs to take
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                     */
                    function _takeNFTsFromSender(
                        IERC721 _nft,
                        uint256[] calldata nftIds,
                        ILSSVMPairFactoryLike _factory,
                        bool isRouter,
                        address routerCaller
                    ) internal virtual {
                        {
                            address _assetRecipient = getAssetRecipient();
                            uint256 numNFTs = nftIds.length;
                            if (isRouter) {
                                // Verify if router is allowed
                                LSSVMRouter router = LSSVMRouter(payable(msg.sender));
                                (bool routerAllowed, ) = _factory.routerStatus(router);
                                require(routerAllowed, "Not router");
                                // Call router to pull NFTs
                                // If more than 1 NFT is being transfered, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection
                                if (numNFTs > 1) {
                                    uint256 beforeBalance = _nft.balanceOf(_assetRecipient);
                                    for (uint256 i = 0; i < numNFTs; ) {
                                        router.pairTransferNFTFrom(
                                            _nft,
                                            routerCaller,
                                            _assetRecipient,
                                            nftIds[i],
                                            pairVariant()
                                        );
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    require(
                                        (_nft.balanceOf(_assetRecipient) - beforeBalance) ==
                                            numNFTs,
                                        "NFTs not transferred"
                                    );
                                } else {
                                    router.pairTransferNFTFrom(
                                        _nft,
                                        routerCaller,
                                        _assetRecipient,
                                        nftIds[0],
                                        pairVariant()
                                    );
                                    require(
                                        _nft.ownerOf(nftIds[0]) == _assetRecipient,
                                        "NFT not transferred"
                                    );
                                }
                            } else {
                                // Pull NFTs directly from sender
                                for (uint256 i; i < numNFTs; ) {
                                    _nft.safeTransferFrom(
                                        msg.sender,
                                        _assetRecipient,
                                        nftIds[i]
                                    );
                                    unchecked {
                                        ++i;
                                    }
                                }
                            }
                        }
                    }
                    /**
                        @dev Used internally to grab pair parameters from calldata, see LSSVMPairCloner for technical details
                     */
                    function _immutableParamsLength() internal pure virtual returns (uint256);
                    /**
                     * Owner functions
                     */
                    /**
                        @notice Rescues a specified set of NFTs owned by the pair to the owner address.
                        @dev If the NFT is the pair's collection, we also remove it from the id tracking.
                        @param a The address of the NFT to transfer
                        @param nftIds The list of IDs of the NFTs to send to the owner
                     */
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        virtual;
                    /**
                        @notice Rescues ERC20 tokens from the pair to the owner. Only callable by the owner.
                        @param a The address of the token to transfer
                        @param amount The amount of tokens to send to the owner
                     */
                    function withdrawERC20(ERC20 a, uint256 amount) external virtual;
                    /**
                        @notice Rescues ERC1155 tokens from the pair to the owner. Only callable by the owner.
                        @param a The NFT to transfer
                        @param ids The NFT ids to transfer
                        @param amounts The amounts of each id to transfer
                     */
                    function withdrawERC1155(
                        IERC1155 a,
                        uint256[] calldata ids,
                        uint256[] calldata amounts
                    ) external onlyOwner {
                        a.safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
                    }
                    /**
                        @notice Updates the selling spot price. Only callable by the owner.
                        @param newSpotPrice The new selling spot price value, in Token
                     */
                    function changeSpotPrice(uint128 newSpotPrice) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateSpotPrice(newSpotPrice),
                            "Invalid new spot price for curve"
                        );
                        if (spotPrice != newSpotPrice) {
                            spotPrice = newSpotPrice;
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                    }
                    /**
                        @notice Updates the delta parameter. Only callable by the owner.
                        @param newDelta The new delta parameter
                     */
                    function changeDelta(uint128 newDelta) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateDelta(newDelta),
                            "Invalid delta for curve"
                        );
                        if (delta != newDelta) {
                            delta = newDelta;
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Updates the fee taken by the LP. Only callable by the owner.
                        Only callable if the pool is a Trade pool. Reverts if the fee is >=
                        MAX_FEE.
                        @param newFee The new LP fee percentage, 18 decimals
                     */
                    function changeFee(uint96 newFee) external onlyOwner {
                        PoolType _poolType = poolType();
                        require(_poolType == PoolType.TRADE, "Only for Trade pools");
                        require(newFee < MAX_FEE, "Trade fee must be less than 90%");
                        if (fee != newFee) {
                            fee = newFee;
                            emit FeeUpdate(newFee);
                        }
                    }
                    /**
                        @notice Changes the address that will receive assets received from
                        trades. Only callable by the owner.
                        @param newRecipient The new asset recipient
                     */
                    function changeAssetRecipient(address payable newRecipient)
                        external
                        onlyOwner
                    {
                        PoolType _poolType = poolType();
                        require(_poolType != PoolType.TRADE, "Not for Trade pools");
                        if (assetRecipient != newRecipient) {
                            assetRecipient = newRecipient;
                            emit AssetRecipientChange(newRecipient);
                        }
                    }
                    /**
                        @notice Allows the pair to make arbitrary external calls to contracts
                        whitelisted by the protocol. Only callable by the owner.
                        @param target The contract to call
                        @param data The calldata to pass to the contract
                     */
                    function call(address payable target, bytes calldata data)
                        external
                        onlyOwner
                    {
                        ILSSVMPairFactoryLike _factory = factory();
                        require(_factory.callAllowed(target), "Target must be whitelisted");
                        (bool result, ) = target.call{value: 0}(data);
                        require(result, "Call failed");
                    }
                    /**
                        @notice Allows owner to batch multiple calls, forked from: https://github.com/boringcrypto/BoringSolidity/blob/master/contracts/BoringBatchable.sol 
                        @dev Intended for withdrawing/altering pool pricing in one tx, only callable by owner, cannot change owner
                        @param calls The calldata for each call to make
                        @param revertOnFail Whether or not to revert the entire tx if any of the calls fail
                     */
                    function multicall(bytes[] calldata calls, bool revertOnFail)
                        external
                        onlyOwner
                    {
                        for (uint256 i; i < calls.length; ) {
                            (bool success, bytes memory result) = address(this).delegatecall(
                                calls[i]
                            );
                            if (!success && revertOnFail) {
                                revert(_getRevertMsg(result));
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Prevent multicall from malicious frontend sneaking in ownership change
                        require(
                            owner() == msg.sender,
                            "Ownership cannot be changed in multicall"
                        );
                    }
                    /**
                      @param _returnData The data returned from a multicall result
                      @dev Used to grab the revert string from the underlying call
                     */
                    function _getRevertMsg(bytes memory _returnData)
                        internal
                        pure
                        returns (string memory)
                    {
                        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
                        if (_returnData.length < 68) return "Transaction reverted silently";
                        assembly {
                            // Slice the sighash.
                            _returnData := add(_returnData, 0x04)
                        }
                        return abi.decode(_returnData, (string)); // All that remains is the revert string
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                import {IOwnershipTransferCallback} from "./IOwnershipTransferCallback.sol";
                import {Address} from "../imports/Address.sol";
                abstract contract OwnableWithTransferCallback {
                    using Address for address;
                    bytes4 constant TRANSFER_CALLBACK =
                        type(IOwnershipTransferCallback).interfaceId;
                    error Ownable_NotOwner();
                    error Ownable_NewOwnerZeroAddress();
                    address private _owner;
                    event OwnershipTransferred(address indexed newOwner);
                    /// @dev Initializes the contract setting the deployer as the initial owner.
                    function __Ownable_init(address initialOwner) internal {
                        _owner = initialOwner;
                    }
                    /// @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() {
                        if (owner() != msg.sender) revert Ownable_NotOwner();
                        _;
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Disallows setting to the zero address as a way to more gas-efficiently avoid reinitialization
                    /// When ownership is transferred, if the new owner implements IOwnershipTransferCallback, we make a callback
                    /// Can only be called by the current owner.
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress();
                        _transferOwnership(newOwner);
                        // Call the on ownership transfer callback if it exists
                        // @dev try/catch is around 5k gas cheaper than doing ERC165 checking
                        if (newOwner.isContract()) {
                            try
                                IOwnershipTransferCallback(newOwner).onOwnershipTransfer(
                                    msg.sender
                                )
                            {} catch (bytes memory) {}
                        }
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Internal function without access restriction.
                    function _transferOwnership(address newOwner) internal virtual {
                        _owner = newOwner;
                        emit OwnershipTransferred(newOwner);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                interface IOwnershipTransferCallback {
                    function onOwnershipTransfer(address oldOwner) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @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
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        return size > 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);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // Forked from OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol),
                // removed initializer check as we already do that in our modified Ownable
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    function __ReentrancyGuard_init() internal {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                        _;
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {CurveErrorCodes} from "./CurveErrorCodes.sol";
                interface ICurve {
                    /**
                        @notice Validates if a delta value is valid for the curve. The criteria for
                        validity can be different for each type of curve, for instance ExponentialCurve
                        requires delta to be greater than 1.
                        @param delta The delta value to be validated
                        @return valid True if delta is valid, false otherwise
                     */
                    function validateDelta(uint128 delta) external pure returns (bool valid);
                    /**
                        @notice Validates if a new spot price is valid for the curve. Spot price is generally assumed to be the immediate sell price of 1 NFT to the pool, in units of the pool's paired token.
                        @param newSpotPrice The new spot price to be set
                        @return valid True if the new spot price is valid, false otherwise
                     */
                    function validateSpotPrice(uint128 newSpotPrice)
                        external
                        view
                        returns (bool valid);
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should pay to purchase an NFT from the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is buying from the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return inputValue The amount that the user should pay, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getBuyInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 inputValue,
                            uint256 protocolFee
                        );
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should receive when selling NFTs to the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is selling to the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return outputValue The amount that the user should receive, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getSellInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 outputValue,
                            uint256 protocolFee
                        );
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                contract CurveErrorCodes {
                    enum Error {
                        OK, // No error
                        INVALID_NUMITEMS, // The numItem value is 0
                        SPOT_PRICE_OVERFLOW // The updated spot price doesn't fit into 128 bits
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721} from "./imports/IERC721.sol";
                import {ERC20} from "./imports/ERC20.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                contract LSSVMRouter {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    struct PairSwapAny {
                        LSSVMPair pair;
                        uint256 numItems;
                    }
                    struct PairSwapSpecific {
                        LSSVMPair pair;
                        uint256[] nftIds;
                    }
                    struct RobustPairSwapAny {
                        PairSwapAny swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecific {
                        PairSwapSpecific swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecificForToken {
                        PairSwapSpecific swapInfo;
                        uint256 minOutput;
                    }
                    struct NFTsForAnyNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapAny[] tokenToNFTTrades;
                    }
                    struct NFTsForSpecificNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapSpecific[] tokenToNFTTrades;
                    }
                    struct RobustPairNFTsFoTokenAndTokenforNFTsTrade {
                        RobustPairSwapSpecific[] tokenToNFTTrades;
                        RobustPairSwapSpecificForToken[] nftToTokenTrades;
                        uint256 inputAmount;
                        address payable tokenRecipient;
                        address nftRecipient;
                    }
                    modifier checkDeadline(uint256 deadline) {
                        _checkDeadline(deadline);
                        _;
                    }
                    ILSSVMPairFactoryLike public immutable factory;
                    constructor(ILSSVMPairFactoryLike _factory) {
                        factory = _factory;
                    }
                    /**
                        ETH swaps
                     */
                    /**
                        @notice Swaps ETH into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForAnyNFTs(swapList, msg.value, ethRecipient, nftRecipient);
                    }
                    /**
                        @notice Swaps ETH into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForSpecificNFTs(
                                swapList,
                                msg.value,
                                ethRecipient,
                                nftRecipient
                            );
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForAnyNFTsThroughETH(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for any NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForSpecificNFTsThroughETH(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for specific NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        ERC20 swaps
                        Note: All ERC20 swaps assume that a single ERC20 token is used for all the pairs involved.
                        Swapping using multiple tokens in the same transaction is possible, but the slippage checks
                        & the return values will be meaningless, and may lead to undefined behavior.
                        Note: The sender should ideally grant infinite token approval to the router in order for NFT-to-NFT
                        swaps to work smoothly.
                     */
                    /**
                        @notice Swaps ERC20 tokens into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForAnyNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps ERC20 tokens into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForSpecificNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps NFTs into ETH/ERC20 using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param minOutput The minimum acceptable total tokens received
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total tokens received
                     */
                    function swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        return _swapNFTsForToken(swapList, minOutput, payable(tokenRecipient));
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForAnyNFTsThroughERC20(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for any NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForSpecificNFTsThroughERC20(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for specific NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        Robust Swaps
                        These are "robust" versions of the NFT<>Token swap functions which will never revert due to slippage
                        Instead, users specify a per-swap max cost. If the price changes more than the user specifies, no swap is attempted. This allows users to specify a batch of swaps, and execute as many of them as possible.
                     */
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @notice Swaps as much ETH for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        // Try doing each swap
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs{
                                    value: pairCost
                                }(
                                    swapList[i].swapInfo.numItems,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs{value: pairCost}(
                                    swapList[i].swapInfo.nftIds,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                        
                     */
                    function robustSwapERC20ForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs(
                                        swapList[i].swapInfo.numItems,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for specific NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapERC20ForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs(
                                        swapList[i].swapInfo.nftIds,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many NFTs for tokens as possible, respecting the per-swap min output
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH/ERC20 received
                     */
                    function robustSwapNFTsForToken(
                        RobustPairSwapSpecificForToken[] calldata swapList,
                        address payable tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            uint256 pairOutput;
                            // Locally scoped to avoid stack too deep error
                            {
                                CurveErrorCodes.Error error;
                                (error, , , pairOutput, ) = swapList[i]
                                    .swapInfo
                                    .pair
                                    .getSellNFTQuote(swapList[i].swapInfo.nftIds.length);
                                if (error != CurveErrorCodes.Error.OK) {
                                    unchecked {
                                        ++i;
                                    }
                                    continue;
                                }
                            }
                            // If at least equal to our minOutput, proceed
                            if (pairOutput >= swapList[i].minOutput) {
                                // Do the swap and update outputAmount with how many tokens we got
                                outputAmount += swapList[i].swapInfo.pair.swapNFTsForToken(
                                    swapList[i].swapInfo.nftIds,
                                    0,
                                    tokenRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ETH and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapETHForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = msg.value;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    // We know how much ETH to send because we already did the math above
                                    // So we just send that much
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs{value: pairCost}(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds,
                                        pairCost,
                                        params.nftRecipient,
                                        true,
                                        msg.sender
                                    );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                            // Return remaining value to sender
                            if (remainingValue > 0) {
                                params.tokenRecipient.safeTransferETH(remainingValue);
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ERC20, and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapERC20ForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = params.inputAmount;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs(
                                            params.tokenToNFTTrades[i].swapInfo.nftIds,
                                            pairCost,
                                            params.nftRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    receive() external payable {}
                    /**
                        Restricted functions
                     */
                    /**
                        @dev Allows an ERC20 pair contract to transfer ERC20 tokens directly from
                        the sender, in order to minimize the number of token transfers. Only callable by an ERC20 pair.
                        @param token The ERC20 token to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param amount The amount of tokens to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferERC20From(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // verify caller is an ERC20 pair
                        require(
                            variant == ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ERC20 ||
                                variant ==
                                ILSSVMPairFactoryLike.PairVariant.MISSING_ENUMERABLE_ERC20,
                            "Not ERC20 pair"
                        );
                        // transfer tokens to pair
                        token.safeTransferFrom(from, to, amount);
                    }
                    /**
                        @dev Allows a pair contract to transfer ERC721 NFTs directly from
                        the sender, in order to minimize the number of token transfers. Only callable by a pair.
                        @param nft The ERC721 NFT to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param id The ID of the NFT to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferNFTFrom(
                        IERC721 nft,
                        address from,
                        address to,
                        uint256 id,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // transfer NFTs to pair
                        nft.safeTransferFrom(from, to, id);
                    }
                    /**
                        Internal functions
                     */
                    /**
                        @param deadline The last valid time for a swap
                     */
                    function _checkDeadline(uint256 deadline) internal view {
                        require(block.timestamp <= deadline, "Deadline passed");
                    }
                    /**
                        @notice Internal function used to swap ETH for any NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].numItems
                            );
                            // Require no error
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs{
                                value: pairCost
                            }(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap ETH for a specific set of NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].nftIds.length
                            );
                            // Require no errors
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs{
                                value: pairCost
                            }(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for any NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for specific NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps NFTs for tokens, designed to be used for 1 token at a time
                        @dev Calling with multiple tokens is permitted, BUT minOutput will be 
                        far from enough of a safety check because different tokens almost certainly have different unit prices.
                        @param swapList The list of pairs and swap calldata 
                        @param minOutput The minimum number of tokens to be receieved frm the swaps 
                        @param tokenRecipient The address that receives the tokens
                        @return outputAmount The number of tokens to be received
                     */
                    function _swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address payable tokenRecipient
                    ) internal returns (uint256 outputAmount) {
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Do the swap for token and then update outputAmount
                            // Note: minExpectedTokenOutput is set to 0 since we're doing an aggregate slippage check below
                            outputAmount += swapList[i].pair.swapNFTsForToken(
                                swapList[i].nftIds,
                                0,
                                tokenRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Aggregate slippage check
                        require(outputAmount >= minOutput, "outputAmount too low");
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                interface ILSSVMPairFactoryLike {
                    enum PairVariant {
                        ENUMERABLE_ETH,
                        MISSING_ENUMERABLE_ETH,
                        ENUMERABLE_ERC20,
                        MISSING_ENUMERABLE_ERC20
                    }
                    function protocolFeeMultiplier() external view returns (uint256);
                    function protocolFeeRecipient() external view returns (address payable);
                    function callAllowed(address target) external view returns (bool);
                    function routerStatus(LSSVMRouter router)
                        external
                        view
                        returns (bool allowed, bool wasEverAllowed);
                    function isPair(address potentialPair, PairVariant variant)
                        external
                        view
                        returns (bool);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./ERC1155Receiver.sol";
                /**
                 * @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;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./IERC1155Receiver.sol";
                import "./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);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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.
                        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. 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);
                }
                // SPDX-License-Identifier: MIT
                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;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721Enumerable} from "./imports/IERC721Enumerable.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair for an NFT that implements ERC721Enumerable
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairEnumerable is LSSVMPair {
                    /// @inheritdoc LSSVMPair
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal override {
                        // Send NFTs to recipient
                        // (we know NFT implements IERC721Enumerable so we just iterate)
                        uint256 lastIndex = _nft.balanceOf(address(this)) - 1;
                        for (uint256 i = 0; i < numNFTs; ) {
                            uint256 nftId = IERC721Enumerable(address(_nft))
                                .tokenOfOwnerByIndex(address(this), lastIndex);
                            _nft.safeTransferFrom(address(this), nftRecipient, nftId);
                            unchecked {
                                --lastIndex;
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal override {
                        // Send NFTs to recipient
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(address(this), nftRecipient, nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function getAllHeldIds() external view override returns (uint256[] memory) {
                        IERC721 _nft = nft();
                        uint256 numNFTs = _nft.balanceOf(address(this));
                        uint256[] memory ids = new uint256[](numNFTs);
                        for (uint256 i; i < numNFTs; ) {
                            ids[i] = IERC721Enumerable(address(_nft)).tokenOfOwnerByIndex(
                                address(this),
                                i
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        return ids;
                    }
                    function onERC721Received(
                        address,
                        address,
                        uint256,
                        bytes memory
                    ) public virtual returns (bytes4) {
                        return this.onERC721Received.selector;
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        override
                        onlyOwner
                    {
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            a.safeTransferFrom(address(this), msg.sender, nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                        emit NFTWithdrawal();
                    }
                }
                // SPDX-License-Identifier: MIT
                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 tokenId);
                    /**
                     * @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 3 of 8: poobs
                /*                
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxddoolllllllllooddxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdolcccclloooddddddddoollc:ccldxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdoc:cloxk0XNWWMMMMMMMMMMMMWNX0kdoc::ldxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxdl::ldOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMNKxoc:ldxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxxxoc:lxKWMMMMMMMMMMWMMMMMMMMMMMMMMMMWXXWMMMWXkl:coxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxxxo::o0WMMMMMMMMMMMWOlkWMMMMMMMMMMMMMM0:;0MMMMMMW0o::oxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxxdc;oKWMMMMMMMMMMMMMW0d0WMMMMMMMMMMMMMMXdxXMMMMMMMMW0l;ldxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxxo;c0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNk::oxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxxl;oXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKl;lxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxxl;oNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNd;lxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxxo;lNMMMMMMMMMMMMMMMMMMMMMMN00KKXXNWWMMMMMMMMMMMMMMMMMMMMMMMMNd,lxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxd;:KMMMMMMMMMMMMMMMMMMMMMMMNOxxddddddddddxxkOO0KKXXNNNWWWWWWWNx,cxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxl,xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWNNXK0Okkxxxddddl::llllllllc:cdxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxd;:KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMk;cdddddddddxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxo,lNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx;lxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxl,xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWd,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxc,kMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWd,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxc;OMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWo,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxc;OMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWo,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxc;OMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWo,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxc;kMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWo,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxl,xMMMMMMMMMMWkkWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWo,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxl,dWMMMMMMMMMXloWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWd,oxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxo,oWMMMMMMMMMKcdWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWd,lxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxo,oNMMMMMMMMMK:dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMx,lxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxd;lNMMMMMMMMM0:xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMk,lxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxd;cXMMMMMMMMM0:xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMk;cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxx::KMMMMMMMMM0:xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMO;cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxx:;0MMMMMMMMMK:dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM0;:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxc;OMMMMMMMMMKcoWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK::xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxc;kMMMMMMMMMNxkWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK:;dxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxc,kMMMMMMMMMMWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXc;dxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxl,kMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNl;dxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxl,xMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWo,oxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxl,xMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWd,oxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxl,xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWd,lxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                xxxxxxxxxxxxxxxxxxl,xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx,lxxxxxxxxxxxxxxxxxxxxxxxxxxxx  
                */
                
                // File: @openzeppelin/contracts/utils/math/SafeMath.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
                
                pragma solidity ^0.8.0;
                
                // CAUTION
                // This version of SafeMath should only be used with Solidity 0.8 or later,
                // because it relies on the compiler's built in overflow checks.
                
                /**
                 * @dev Wrappers over Solidity's arithmetic operations.
                 *
                 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
                 * now has built in overflow checking.
                 */
                library SafeMath {
                    /**
                     * @dev Returns the addition of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        unchecked {
                            uint256 c = a + b;
                            if (c < a) return (false, 0);
                            return (true, c);
                        }
                    }
                
                    /**
                     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        unchecked {
                            if (b > a) return (false, 0);
                            return (true, a - b);
                        }
                    }
                
                    /**
                     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        unchecked {
                            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                            // benefit is lost if 'b' is also tested.
                            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                            if (a == 0) return (true, 0);
                            uint256 c = a * b;
                            if (c / a != b) return (false, 0);
                            return (true, c);
                        }
                    }
                
                    /**
                     * @dev Returns the division of two unsigned integers, with a division by zero flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        unchecked {
                            if (b == 0) return (false, 0);
                            return (true, a / b);
                        }
                    }
                
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        unchecked {
                            if (b == 0) return (false, 0);
                            return (true, a % b);
                        }
                    }
                
                    /**
                     * @dev Returns the addition of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `+` operator.
                     *
                     * Requirements:
                     *
                     * - Addition cannot overflow.
                     */
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a + b;
                    }
                
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting on
                     * overflow (when the result is negative).
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a - b;
                    }
                
                    /**
                     * @dev Returns the multiplication of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `*` operator.
                     *
                     * Requirements:
                     *
                     * - Multiplication cannot overflow.
                     */
                    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a * b;
                    }
                
                    /**
                     * @dev Returns the integer division of two unsigned integers, reverting on
                     * division by zero. The result is rounded towards zero.
                     *
                     * Counterpart to Solidity's `/` operator.
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a / b;
                    }
                
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * reverting when dividing by zero.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a % b;
                    }
                
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                     * overflow (when the result is negative).
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {trySub}.
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(
                        uint256 a,
                        uint256 b,
                        string memory errorMessage
                    ) internal pure returns (uint256) {
                        unchecked {
                            require(b <= a, errorMessage);
                            return a - b;
                        }
                    }
                
                    /**
                     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                     * division by zero. The result is rounded towards zero.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function div(
                        uint256 a,
                        uint256 b,
                        string memory errorMessage
                    ) internal pure returns (uint256) {
                        unchecked {
                            require(b > 0, errorMessage);
                            return a / b;
                        }
                    }
                
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * reverting with custom message when dividing by zero.
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {tryMod}.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function mod(
                        uint256 a,
                        uint256 b,
                        string memory errorMessage
                    ) internal pure returns (uint256) {
                        unchecked {
                            require(b > 0, errorMessage);
                            return a % b;
                        }
                    }
                }
                
                // File: @openzeppelin/contracts/utils/Counters.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @title Counters
                 * @author Matt Condon (@shrugs)
                 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
                 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
                 *
                 * Include with `using Counters for Counters.Counter;`
                 */
                library Counters {
                    struct Counter {
                        // This variable should never be directly accessed by users of the library: interactions must be restricted to
                        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
                        // this feature: see https://github.com/ethereum/solidity/issues/4637
                        uint256 _value; // default: 0
                    }
                
                    function current(Counter storage counter) internal view returns (uint256) {
                        return counter._value;
                    }
                
                    function increment(Counter storage counter) internal {
                        unchecked {
                            counter._value += 1;
                        }
                    }
                
                    function decrement(Counter storage counter) internal {
                        uint256 value = counter._value;
                        require(value > 0, "Counter: decrement overflow");
                        unchecked {
                            counter._value = value - 1;
                        }
                    }
                
                    function reset(Counter storage counter) internal {
                        counter._value = 0;
                    }
                }
                
                // File: @openzeppelin/contracts/security/ReentrancyGuard.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                
                    uint256 private _status;
                
                    constructor() {
                        _status = _NOT_ENTERED;
                    }
                
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                
                        _;
                
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                
                // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @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 `recipient`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
                        address recipient,
                        uint256 amount
                    ) external returns (bool);
                
                    /**
                     * @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);
                }
                
                // File: @openzeppelin/contracts/interfaces/IERC20.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
                
                pragma solidity ^0.8.0;
                
                
                // File: @openzeppelin/contracts/utils/Strings.sol
                
                
                // 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: @openzeppelin/contracts/utils/Context.sol
                
                
                // 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: @openzeppelin/contracts/access/Ownable.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
                
                pragma solidity ^0.8.0;
                
                
                /**
                 * @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: @openzeppelin/contracts/utils/Address.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
                
                pragma solidity ^0.8.0;
                
                /**
                 * @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
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        return size > 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: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (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 `IERC721.onERC721Received.selector`.
                     */
                    function onERC721Received(
                        address operator,
                        address from,
                        uint256 tokenId,
                        bytes calldata data
                    ) external returns (bytes4);
                }
                
                // File: @openzeppelin/contracts/utils/introspection/IERC165.sol
                
                
                // 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: @openzeppelin/contracts/interfaces/IERC165.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
                
                pragma solidity ^0.8.0;
                
                
                // File: @openzeppelin/contracts/interfaces/IERC2981.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
                
                pragma solidity ^0.8.0;
                
                
                /**
                 * @dev Interface for the NFT Royalty Standard
                 */
                interface IERC2981 is IERC165 {
                    /**
                     * @dev Called with the sale price to determine how much royalty is owed and to whom.
                     * @param tokenId - the NFT asset queried for royalty information
                     * @param salePrice - the sale price of the NFT asset specified by `tokenId`
                     * @return receiver - address of who should be sent the royalty payment
                     * @return royaltyAmount - the royalty payment amount for `salePrice`
                     */
                    function royaltyInfo(uint256 tokenId, uint256 salePrice)
                        external
                        view
                        returns (address receiver, uint256 royaltyAmount);
                }
                
                // File: @openzeppelin/contracts/utils/introspection/ERC165.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
                
                pragma solidity ^0.8.0;
                
                
                /**
                 * @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: @openzeppelin/contracts/token/ERC721/IERC721.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
                
                pragma solidity ^0.8.0;
                
                
                /**
                 * @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`, 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 Returns the account approved for `tokenId` token.
                     *
                     * Requirements:
                     *
                     * - `tokenId` must exist.
                     */
                    function getApproved(uint256 tokenId) external view returns (address operator);
                
                    /**
                     * @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 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);
                
                    /**
                     * @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;
                }
                
                // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
                
                pragma solidity ^0.8.0;
                
                
                /**
                 * @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 tokenId);
                
                    /**
                     * @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: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
                
                
                // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
                
                pragma solidity ^0.8.0;
                
                
                /**
                 * @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: contracts/ERC721A.sol
                
                
                
                pragma solidity ^0.8.0;
                
                
                
                
                
                
                
                
                
                /**
                 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
                 * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
                 *
                 * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
                 *
                 * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
                 *
                 * Does not support burning tokens to address(0).
                 */
                contract ERC721A is
                  Context,
                  ERC165,
                  IERC721,
                  IERC721Metadata,
                  IERC721Enumerable
                {
                  using Address for address;
                  using Strings for uint256;
                
                  struct TokenOwnership {
                    address addr;
                    uint64 startTimestamp;
                  }
                
                  struct AddressData {
                    uint128 balance;
                    uint128 numberMinted;
                  }
                
                  uint256 private currentIndex = 0;
                
                  uint256 internal immutable collectionSize;
                  uint256 internal immutable maxBatchSize;
                
                  // Token name
                  string private _name;
                
                  // Token symbol
                  string private _symbol;
                
                  // Mapping from token ID to ownership details
                  // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
                  mapping(uint256 => TokenOwnership) private _ownerships;
                
                  // Mapping owner address to address data
                  mapping(address => AddressData) private _addressData;
                
                  // 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
                   * `maxBatchSize` refers to how much a minter can mint at a time.
                   * `collectionSize_` refers to how many tokens are in the collection.
                   */
                  constructor(
                    string memory name_,
                    string memory symbol_,
                    uint256 maxBatchSize_,
                    uint256 collectionSize_
                  ) {
                    require(
                      collectionSize_ > 0,
                      "ERC721A: collection must have a nonzero supply"
                    );
                    require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
                    _name = name_;
                    _symbol = symbol_;
                    maxBatchSize = maxBatchSize_;
                    collectionSize = collectionSize_;
                  }
                
                  /**
                   * @dev See {IERC721Enumerable-totalSupply}.
                   */
                  function totalSupply() public view override returns (uint256) {
                    return currentIndex;
                  }
                
                  /**
                   * @dev See {IERC721Enumerable-tokenByIndex}.
                   */
                  function tokenByIndex(uint256 index) public view override returns (uint256) {
                    require(index < totalSupply(), "ERC721A: global index out of bounds");
                    return index;
                  }
                
                  /**
                   * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
                   * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
                   * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
                   */
                  function tokenOfOwnerByIndex(address owner, uint256 index)
                    public
                    view
                    override
                    returns (uint256)
                  {
                    require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
                    uint256 numMintedSoFar = totalSupply();
                    uint256 tokenIdsIdx = 0;
                    address currOwnershipAddr = address(0);
                    for (uint256 i = 0; i < numMintedSoFar; i++) {
                      TokenOwnership memory ownership = _ownerships[i];
                      if (ownership.addr != address(0)) {
                        currOwnershipAddr = ownership.addr;
                      }
                      if (currOwnershipAddr == owner) {
                        if (tokenIdsIdx == index) {
                          return i;
                        }
                        tokenIdsIdx++;
                      }
                    }
                    revert("ERC721A: unable to get token of owner by index");
                  }
                
                  /**
                   * @dev See {IERC165-supportsInterface}.
                   */
                  function supportsInterface(bytes4 interfaceId)
                    public
                    view
                    virtual
                    override(ERC165, IERC165)
                    returns (bool)
                  {
                    return
                      interfaceId == type(IERC721).interfaceId ||
                      interfaceId == type(IERC721Metadata).interfaceId ||
                      interfaceId == type(IERC721Enumerable).interfaceId ||
                      super.supportsInterface(interfaceId);
                  }
                
                  /**
                   * @dev See {IERC721-balanceOf}.
                   */
                  function balanceOf(address owner) public view override returns (uint256) {
                    require(owner != address(0), "ERC721A: balance query for the zero address");
                    return uint256(_addressData[owner].balance);
                  }
                
                  function _numberMinted(address owner) internal view returns (uint256) {
                    require(
                      owner != address(0),
                      "ERC721A: number minted query for the zero address"
                    );
                    return uint256(_addressData[owner].numberMinted);
                  }
                
                  function ownershipOf(uint256 tokenId)
                    internal
                    view
                    returns (TokenOwnership memory)
                  {
                    require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
                
                    uint256 lowestTokenToCheck;
                    if (tokenId >= maxBatchSize) {
                      lowestTokenToCheck = tokenId - maxBatchSize + 1;
                    }
                
                    for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
                      TokenOwnership memory ownership = _ownerships[curr];
                      if (ownership.addr != address(0)) {
                        return ownership;
                      }
                    }
                
                    revert("ERC721A: unable to determine the owner of token");
                  }
                
                  /**
                   * @dev See {IERC721-ownerOf}.
                   */
                  function ownerOf(uint256 tokenId) public view override returns (address) {
                    return ownershipOf(tokenId).addr;
                  }
                
                  /**
                   * @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)
                  {
                    require(
                      _exists(tokenId),
                      "ERC721Metadata: URI query for nonexistent token"
                    );
                
                    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 overriden in child contracts.
                   */
                  function _baseURI() internal view virtual returns (string memory) {
                    return "";
                  }
                
                  /**
                   * @dev See {IERC721-approve}.
                   */
                  function approve(address to, uint256 tokenId) public override {
                    address owner = ERC721A.ownerOf(tokenId);
                    require(to != owner, "ERC721A: approval to current owner");
                
                    require(
                      _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
                      "ERC721A: approve caller is not owner nor approved for all"
                    );
                
                    _approve(to, tokenId, owner);
                  }
                
                  /**
                   * @dev See {IERC721-getApproved}.
                   */
                  function getApproved(uint256 tokenId) public view override returns (address) {
                    require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
                
                    return _tokenApprovals[tokenId];
                  }
                
                  /**
                   * @dev See {IERC721-setApprovalForAll}.
                   */
                  function setApprovalForAll(address operator, bool approved) public override {
                    require(operator != _msgSender(), "ERC721A: approve to caller");
                
                    _operatorApprovals[_msgSender()][operator] = approved;
                    emit ApprovalForAll(_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 override {
                    _transfer(from, to, tokenId);
                  }
                
                  /**
                   * @dev See {IERC721-safeTransferFrom}.
                   */
                  function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                  ) public override {
                    safeTransferFrom(from, to, tokenId, "");
                  }
                
                  /**
                   * @dev See {IERC721-safeTransferFrom}.
                   */
                  function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                  ) public override {
                    _transfer(from, to, tokenId);
                    require(
                      _checkOnERC721Received(from, to, tokenId, _data),
                      "ERC721A: transfer to non ERC721Receiver implementer"
                    );
                  }
                
                  /**
                   * @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`),
                   */
                  function _exists(uint256 tokenId) internal view returns (bool) {
                    return tokenId < currentIndex;
                  }
                
                  function _safeMint(address to, uint256 quantity) internal {
                    _safeMint(to, quantity, "");
                  }
                
                  /**
                   * @dev Mints `quantity` tokens and transfers them to `to`.
                   *
                   * Requirements:
                   *
                   * - there must be `quantity` tokens remaining unminted in the total collection.
                   * - `to` cannot be the zero address.
                   * - `quantity` cannot be larger than the max batch size.
                   *
                   * Emits a {Transfer} event.
                   */
                  function _safeMint(
                    address to,
                    uint256 quantity,
                    bytes memory _data
                  ) internal {
                    uint256 startTokenId = currentIndex;
                    require(to != address(0), "ERC721A: mint to the zero address");
                    // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
                    require(!_exists(startTokenId), "ERC721A: token already minted");
                    require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
                
                    _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                
                    AddressData memory addressData = _addressData[to];
                    _addressData[to] = AddressData(
                      addressData.balance + uint128(quantity),
                      addressData.numberMinted + uint128(quantity)
                    );
                    _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
                
                    uint256 updatedIndex = startTokenId;
                
                    for (uint256 i = 0; i < quantity; i++) {
                      emit Transfer(address(0), to, updatedIndex);
                      require(
                        _checkOnERC721Received(address(0), to, updatedIndex, _data),
                        "ERC721A: transfer to non ERC721Receiver implementer"
                      );
                      updatedIndex++;
                    }
                
                    currentIndex = updatedIndex;
                    _afterTokenTransfers(address(0), to, startTokenId, quantity);
                  }
                
                  /**
                   * @dev Transfers `tokenId` from `from` to `to`.
                   *
                   * 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
                  ) private {
                    TokenOwnership memory prevOwnership = ownershipOf(tokenId);
                
                    bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
                      getApproved(tokenId) == _msgSender() ||
                      isApprovedForAll(prevOwnership.addr, _msgSender()));
                
                    require(
                      isApprovedOrOwner,
                      "ERC721A: transfer caller is not owner nor approved"
                    );
                
                    require(
                      prevOwnership.addr == from,
                      "ERC721A: transfer from incorrect owner"
                    );
                    require(to != address(0), "ERC721A: transfer to the zero address");
                
                    _beforeTokenTransfers(from, to, tokenId, 1);
                
                    // Clear approvals from the previous owner
                    _approve(address(0), tokenId, prevOwnership.addr);
                
                    _addressData[from].balance -= 1;
                    _addressData[to].balance += 1;
                    _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
                
                    // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
                    // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
                    uint256 nextTokenId = tokenId + 1;
                    if (_ownerships[nextTokenId].addr == address(0)) {
                      if (_exists(nextTokenId)) {
                        _ownerships[nextTokenId] = TokenOwnership(
                          prevOwnership.addr,
                          prevOwnership.startTimestamp
                        );
                      }
                    }
                
                    emit Transfer(from, to, tokenId);
                    _afterTokenTransfers(from, to, tokenId, 1);
                  }
                
                  /**
                   * @dev Approve `to` to operate on `tokenId`
                   *
                   * Emits a {Approval} event.
                   */
                  function _approve(
                    address to,
                    uint256 tokenId,
                    address owner
                  ) private {
                    _tokenApprovals[tokenId] = to;
                    emit Approval(owner, to, tokenId);
                  }
                
                  uint256 public nextOwnerToExplicitlySet = 0;
                
                  /**
                   * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
                   */
                  function _setOwnersExplicit(uint256 quantity) internal {
                    uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
                    require(quantity > 0, "quantity must be nonzero");
                    uint256 endIndex = oldNextOwnerToSet + quantity - 1;
                    if (endIndex > collectionSize - 1) {
                      endIndex = collectionSize - 1;
                    }
                    // We know if the last one in the group exists, all in the group exist, due to serial ordering.
                    require(_exists(endIndex), "not enough minted yet for this cleanup");
                    for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
                      if (_ownerships[i].addr == address(0)) {
                        TokenOwnership memory ownership = ownershipOf(i);
                        _ownerships[i] = TokenOwnership(
                          ownership.addr,
                          ownership.startTimestamp
                        );
                      }
                    }
                    nextOwnerToExplicitlySet = endIndex + 1;
                  }
                
                  /**
                   * @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
                        IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
                      returns (bytes4 retval) {
                        return retval == IERC721Receiver(to).onERC721Received.selector;
                      } catch (bytes memory reason) {
                        if (reason.length == 0) {
                          revert("ERC721A: transfer to non ERC721Receiver implementer");
                        } else {
                          assembly {
                            revert(add(32, reason), mload(reason))
                          }
                        }
                      }
                    } else {
                      return true;
                    }
                  }
                
                  /**
                   * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
                   *
                   * startTokenId - the first token id to be transferred
                   * quantity - the amount to be transferred
                   *
                   * Calling conditions:
                   *
                   * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
                   * transferred to `to`.
                   * - When `from` is zero, `tokenId` will be minted for `to`.
                   */
                  function _beforeTokenTransfers(
                    address from,
                    address to,
                    uint256 startTokenId,
                    uint256 quantity
                  ) internal virtual {}
                
                  /**
                   * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
                   * minting.
                   *
                   * startTokenId - the first token id to be transferred
                   * quantity - the amount to be transferred
                   *
                   * Calling conditions:
                   *
                   * - when `from` and `to` are both non-zero.
                   * - `from` and `to` are never both zero.
                   */
                  function _afterTokenTransfers(
                    address from,
                    address to,
                    uint256 startTokenId,
                    uint256 quantity
                  ) internal virtual {}
                }
                
                //SPDX-License-Identifier: MIT
                //Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)
                
                pragma solidity ^0.8.0;
                
                
                
                
                
                
                
                
                
                contract poobs is ERC721A, IERC2981, Ownable, ReentrancyGuard {
                    using Counters for Counters.Counter;
                    using Strings for uint256;
                
                    Counters.Counter private tokenCounter;
                
                    string private release_all_poobs = "ipfs://QmZU6h1b9Srf1CALZjJ7eDQN9MVjEAjPoEKMdYDUwuLjKH";
                    address private openSeaProxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
                    bool private isOpenSeaProxyActive = true;
                
                uint256 public constant price = 0.01 ether;
                uint256 public  total_amount_of_poobs = 5555;
                uint256 public reserved_amount_for_whitelist = 555;
                uint256 public constant mint_amount_for_public = 3;
                uint256 public constant mint_amount_for_whitelist= 1;
                bool public isPublicSaleActive = true;
                bool public paused = true;
                
                
                
                    // ============ ACCESS CONTROL/SANITY MODIFIERS ============
                
                    modifier publicSaleActive() {
                        require(isPublicSaleActive, "Public sale is not open");
                        _;
                    }
                
                
                
                    modifier maxMintsPerTX(uint256 numberOfTokens) {
                        require(
                            numberOfTokens <= mint_amount_for_public,
                            "Max mints per transaction exceeded"
                        );
                        _;
                    }
                
                    modifier canMintNFTs(uint256 numberOfTokens) {
                        require(
                            totalSupply() + numberOfTokens <=
                                 total_amount_of_poobs,
                            "Not enough mints remaining to mint"
                        );
                        _;
                    }
                
                    modifier freeMintsAvailable() {
                        require(
                            totalSupply() <=
                                reserved_amount_for_whitelist,
                            "Not enough free mints remain"
                        );
                        _;
                    }
                
                
                
                
                    constructor(
                    ) ERC721A("poobs", "poobsnft", 100,  total_amount_of_poobs) {
                    }
                
                    // ============ PUBLIC FUNCTIONS FOR MINTING ============
                
                    function mintpoobs(uint256 _amount) external payable {
                        address _caller = _msgSender();
                        require(!paused, "Paused");
                        require( total_amount_of_poobs >= totalSupply() + _amount, "Exceeds max supply");
                        require(_amount > 0, "No 0 mints");
                        require(tx.origin == _caller, "No contracts");
                        require(mint_amount_for_public >= _amount , "Excess max per paid tx");
                        
                      if(reserved_amount_for_whitelist >= totalSupply()){
                            require(mint_amount_for_whitelist  >= _amount , "Excess max per free tx");
                        }else{
                            require(mint_amount_for_public>= _amount , "Excess max per paid tx");
                            require(_amount * price == msg.value, "Invalid funds provided");
                        }
                
                
                        _safeMint(_caller, _amount);
                    }
                
                
                    //A simple free mint function to avoid confusion
                    //The normal mint function with a cost of 0 would work too
                
                    // ============ PUBLIC READ-ONLY FUNCTIONS ============
                
                    function getBaseURI() external view returns (string memory) {
                        return release_all_poobs;
                    }
                
                    // ============ OWNER-ONLY ADMIN FUNCTIONS ============
                
                    function reveal_all_poobs(string memory _baseURI) external onlyOwner {
                        release_all_poobs = _baseURI;
                    }
                
                    // function to disable gasless listings for security in case
                    // opensea ever shuts down or is compromised
                    function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive)
                        external
                        onlyOwner
                    {
                        isOpenSeaProxyActive = _isOpenSeaProxyActive;
                    }
                
                    function setIsPublicSaleActive(bool _isPublicSaleActive)
                        external
                        onlyOwner
                    {
                        isPublicSaleActive = _isPublicSaleActive;
                    }
                
                 function IsPaused(bool _paused)
                        external
                        onlyOwner
                    {
                        paused = _paused;
                    }
                
                    function reserved_for_whitelist(uint256 reserved)
                        external
                        onlyOwner
                    {
                       reserved_amount_for_whitelist = reserved;
                    }
                
                
                    function withdrawfunds() public onlyOwner {
                        uint256 balance = address(this).balance;
                        payable(msg.sender).transfer(balance);
                    }
                
                    function withdrawTokens(IERC20 token) public onlyOwner {
                        uint256 balance = token.balanceOf(address(this));
                        token.transfer(msg.sender, balance);
                    }
                
                
                
                    // ============ SUPPORTING FUNCTIONS ============
                
                    function nextTokenId() private returns (uint256) {
                        tokenCounter.increment();
                        return tokenCounter.current();
                    }
                
                    // ============ FUNCTION OVERRIDES ============
                
                    function supportsInterface(bytes4 interfaceId)
                        public
                        view
                        virtual
                        override(ERC721A, IERC165)
                        returns (bool)
                    {
                        return
                            interfaceId == type(IERC2981).interfaceId ||
                            super.supportsInterface(interfaceId);
                    }
                
                    /**
                     * @dev Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings.
                     */
                    function isApprovedForAll(address owner, address operator)
                        public
                        view
                        override
                        returns (bool)
                    {
                        // Get a reference to OpenSea's proxy registry contract by instantiating
                        // the contract using the already existing address.
                        ProxyRegistry proxyRegistry = ProxyRegistry(
                            openSeaProxyRegistryAddress
                        );
                        if (
                            isOpenSeaProxyActive &&
                            address(proxyRegistry.proxies(owner)) == operator
                        ) {
                            return true;
                        }
                
                        return super.isApprovedForAll(owner, operator);
                    }
                
                    /**
                     * @dev See {IERC721Metadata-tokenURI}.
                     */
                    function tokenURI(uint256 tokenId)
                        public
                        view
                        virtual
                        override
                        returns (string memory)
                    {
                        require(_exists(tokenId), "Nonexistent token");
                
                        return
                            string(abi.encodePacked(release_all_poobs, "/", (tokenId+1).toString(), ".json"));
                    }
                
                    /**
                     * @dev See {IERC165-royaltyInfo}.
                     */
                    function royaltyInfo(uint256 tokenId, uint256 salePrice)
                        external
                        view
                        override
                        returns (address receiver, uint256 royaltyAmount)
                    {
                        require(_exists(tokenId), "Nonexistent token");
                
                        return (address(this), SafeMath.div(SafeMath.mul(salePrice, 5), 100));
                    }
                }
                
                // These contract definitions are used to create a reference to the OpenSea
                // ProxyRegistry contract by using the registry's address (see isApprovedForAll).
                contract OwnableDelegateProxy {
                
                }
                
                contract ProxyRegistry {
                    mapping(address => OwnableDelegateProxy) public proxies;
                }

                File 4 of 8: MarketRegistry
                // SPDX-License-Identifier: MIT
                
                pragma solidity 0.8.11;
                
                abstract contract Context {
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                }
                
                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);
                    }
                }
                
                contract MarketRegistry is Ownable {
                
                    struct TradeDetails {
                        uint256 marketId;
                        uint256 value;
                        bytes tradeData;
                    }
                
                    struct Market {
                        address proxy;
                        bool isLib;
                        bool isActive;
                    }
                
                    Market[] public markets;
                
                    constructor(address[] memory proxies, bool[] memory isLibs) {
                        for (uint256 i = 0; i < proxies.length; i++) {
                            markets.push(Market(proxies[i], isLibs[i], true));
                        }
                    }
                
                    function addMarket(address proxy, bool isLib) external onlyOwner {
                        markets.push(Market(proxy, isLib, true));
                    }
                
                    function setMarketStatus(uint256 marketId, bool newStatus) external onlyOwner {
                        Market storage market = markets[marketId];
                        market.isActive = newStatus;
                    }
                
                    function setMarketProxy(uint256 marketId, address newProxy, bool isLib) external onlyOwner {
                        Market storage market = markets[marketId];
                        market.proxy = newProxy;
                        market.isLib = isLib;
                    }
                }

                File 5 of 8: LSSVMRouter
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721} from "./imports/IERC721.sol";
                import {ERC20} from "./imports/ERC20.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                contract LSSVMRouter {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    struct PairSwapAny {
                        LSSVMPair pair;
                        uint256 numItems;
                    }
                    struct PairSwapSpecific {
                        LSSVMPair pair;
                        uint256[] nftIds;
                    }
                    struct RobustPairSwapAny {
                        PairSwapAny swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecific {
                        PairSwapSpecific swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecificForToken {
                        PairSwapSpecific swapInfo;
                        uint256 minOutput;
                    }
                    struct NFTsForAnyNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapAny[] tokenToNFTTrades;
                    }
                    struct NFTsForSpecificNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapSpecific[] tokenToNFTTrades;
                    }
                    struct RobustPairNFTsFoTokenAndTokenforNFTsTrade {
                        RobustPairSwapSpecific[] tokenToNFTTrades;
                        RobustPairSwapSpecificForToken[] nftToTokenTrades;
                        uint256 inputAmount;
                        address payable tokenRecipient;
                        address nftRecipient;
                    }
                    modifier checkDeadline(uint256 deadline) {
                        _checkDeadline(deadline);
                        _;
                    }
                    ILSSVMPairFactoryLike public immutable factory;
                    constructor(ILSSVMPairFactoryLike _factory) {
                        factory = _factory;
                    }
                    /**
                        ETH swaps
                     */
                    /**
                        @notice Swaps ETH into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForAnyNFTs(swapList, msg.value, ethRecipient, nftRecipient);
                    }
                    /**
                        @notice Swaps ETH into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForSpecificNFTs(
                                swapList,
                                msg.value,
                                ethRecipient,
                                nftRecipient
                            );
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForAnyNFTsThroughETH(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for any NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForSpecificNFTsThroughETH(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for specific NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        ERC20 swaps
                        Note: All ERC20 swaps assume that a single ERC20 token is used for all the pairs involved.
                        Swapping using multiple tokens in the same transaction is possible, but the slippage checks
                        & the return values will be meaningless, and may lead to undefined behavior.
                        Note: The sender should ideally grant infinite token approval to the router in order for NFT-to-NFT
                        swaps to work smoothly.
                     */
                    /**
                        @notice Swaps ERC20 tokens into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForAnyNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps ERC20 tokens into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForSpecificNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps NFTs into ETH/ERC20 using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param minOutput The minimum acceptable total tokens received
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total tokens received
                     */
                    function swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        return _swapNFTsForToken(swapList, minOutput, payable(tokenRecipient));
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForAnyNFTsThroughERC20(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for any NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForSpecificNFTsThroughERC20(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for specific NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        Robust Swaps
                        These are "robust" versions of the NFT<>Token swap functions which will never revert due to slippage
                        Instead, users specify a per-swap max cost. If the price changes more than the user specifies, no swap is attempted. This allows users to specify a batch of swaps, and execute as many of them as possible.
                     */
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @notice Swaps as much ETH for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        // Try doing each swap
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs{
                                    value: pairCost
                                }(
                                    swapList[i].swapInfo.numItems,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs{value: pairCost}(
                                    swapList[i].swapInfo.nftIds,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                        
                     */
                    function robustSwapERC20ForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs(
                                        swapList[i].swapInfo.numItems,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for specific NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapERC20ForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs(
                                        swapList[i].swapInfo.nftIds,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many NFTs for tokens as possible, respecting the per-swap min output
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH/ERC20 received
                     */
                    function robustSwapNFTsForToken(
                        RobustPairSwapSpecificForToken[] calldata swapList,
                        address payable tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            uint256 pairOutput;
                            // Locally scoped to avoid stack too deep error
                            {
                                CurveErrorCodes.Error error;
                                (error, , , pairOutput, ) = swapList[i]
                                    .swapInfo
                                    .pair
                                    .getSellNFTQuote(swapList[i].swapInfo.nftIds.length);
                                if (error != CurveErrorCodes.Error.OK) {
                                    unchecked {
                                        ++i;
                                    }
                                    continue;
                                }
                            }
                            // If at least equal to our minOutput, proceed
                            if (pairOutput >= swapList[i].minOutput) {
                                // Do the swap and update outputAmount with how many tokens we got
                                outputAmount += swapList[i].swapInfo.pair.swapNFTsForToken(
                                    swapList[i].swapInfo.nftIds,
                                    0,
                                    tokenRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ETH and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapETHForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = msg.value;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    // We know how much ETH to send because we already did the math above
                                    // So we just send that much
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs{value: pairCost}(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds,
                                        pairCost,
                                        params.nftRecipient,
                                        true,
                                        msg.sender
                                    );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                            // Return remaining value to sender
                            if (remainingValue > 0) {
                                params.tokenRecipient.safeTransferETH(remainingValue);
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ERC20, and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapERC20ForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = params.inputAmount;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs(
                                            params.tokenToNFTTrades[i].swapInfo.nftIds,
                                            pairCost,
                                            params.nftRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    receive() external payable {}
                    /**
                        Restricted functions
                     */
                    /**
                        @dev Allows an ERC20 pair contract to transfer ERC20 tokens directly from
                        the sender, in order to minimize the number of token transfers. Only callable by an ERC20 pair.
                        @param token The ERC20 token to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param amount The amount of tokens to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferERC20From(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // verify caller is an ERC20 pair
                        require(
                            variant == ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ERC20 ||
                                variant ==
                                ILSSVMPairFactoryLike.PairVariant.MISSING_ENUMERABLE_ERC20,
                            "Not ERC20 pair"
                        );
                        // transfer tokens to pair
                        token.safeTransferFrom(from, to, amount);
                    }
                    /**
                        @dev Allows a pair contract to transfer ERC721 NFTs directly from
                        the sender, in order to minimize the number of token transfers. Only callable by a pair.
                        @param nft The ERC721 NFT to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param id The ID of the NFT to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferNFTFrom(
                        IERC721 nft,
                        address from,
                        address to,
                        uint256 id,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // transfer NFTs to pair
                        nft.safeTransferFrom(from, to, id);
                    }
                    /**
                        Internal functions
                     */
                    /**
                        @param deadline The last valid time for a swap
                     */
                    function _checkDeadline(uint256 deadline) internal view {
                        require(block.timestamp <= deadline, "Deadline passed");
                    }
                    /**
                        @notice Internal function used to swap ETH for any NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].numItems
                            );
                            // Require no error
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs{
                                value: pairCost
                            }(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap ETH for a specific set of NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].nftIds.length
                            );
                            // Require no errors
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs{
                                value: pairCost
                            }(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for any NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for specific NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps NFTs for tokens, designed to be used for 1 token at a time
                        @dev Calling with multiple tokens is permitted, BUT minOutput will be 
                        far from enough of a safety check because different tokens almost certainly have different unit prices.
                        @param swapList The list of pairs and swap calldata 
                        @param minOutput The minimum number of tokens to be receieved frm the swaps 
                        @param tokenRecipient The address that receives the tokens
                        @return outputAmount The number of tokens to be received
                     */
                    function _swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address payable tokenRecipient
                    ) internal returns (uint256 outputAmount) {
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Do the swap for token and then update outputAmount
                            // Note: minExpectedTokenOutput is set to 0 since we're doing an aggregate slippage check below
                            outputAmount += swapList[i].pair.swapNFTsForToken(
                                swapList[i].nftIds,
                                0,
                                tokenRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Aggregate slippage check
                        require(outputAmount >= minOutput, "outputAmount too low");
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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`, 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 Returns the account approved for `tokenId` token.
                     *
                     * Requirements:
                     *
                     * - `tokenId` must exist.
                     */
                    function getApproved(uint256 tokenId)
                        external
                        view
                        returns (address operator);
                    /**
                     * @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 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);
                    /**
                     * @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;
                }
                // SPDX-License-Identifier: MIT
                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);
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                abstract contract ERC20 {
                    /*///////////////////////////////////////////////////////////////
                                                  EVENTS
                    //////////////////////////////////////////////////////////////*/
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 amount
                    );
                    /*///////////////////////////////////////////////////////////////
                                             METADATA STORAGE
                    //////////////////////////////////////////////////////////////*/
                    string public name;
                    string public symbol;
                    uint8 public immutable decimals;
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    uint256 public totalSupply;
                    mapping(address => uint256) public balanceOf;
                    mapping(address => mapping(address => uint256)) public allowance;
                    /*///////////////////////////////////////////////////////////////
                                           EIP-2612 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    bytes32 public constant PERMIT_TYPEHASH =
                        keccak256(
                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                        );
                    uint256 internal immutable INITIAL_CHAIN_ID;
                    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                    mapping(address => uint256) public nonces;
                    /*///////////////////////////////////////////////////////////////
                                               CONSTRUCTOR
                    //////////////////////////////////////////////////////////////*/
                    constructor(
                        string memory _name,
                        string memory _symbol,
                        uint8 _decimals
                    ) {
                        name = _name;
                        symbol = _symbol;
                        decimals = _decimals;
                        INITIAL_CHAIN_ID = block.chainid;
                        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                    }
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function approve(address spender, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        allowance[msg.sender][spender] = amount;
                        emit Approval(msg.sender, spender, amount);
                        return true;
                    }
                    function transfer(address to, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        balanceOf[msg.sender] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(msg.sender, to, amount);
                        return true;
                    }
                    function transferFrom(
                        address from,
                        address to,
                        uint256 amount
                    ) public virtual returns (bool) {
                        if (allowance[from][msg.sender] != type(uint256).max) {
                            allowance[from][msg.sender] -= amount;
                        }
                        balanceOf[from] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        return true;
                    }
                    /*///////////////////////////////////////////////////////////////
                                              EIP-2612 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public virtual {
                        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                        // Unchecked because the only math done is incrementing
                        // the owner's nonce which cannot realistically overflow.
                        unchecked {
                            bytes32 digest = keccak256(
                                abi.encodePacked(
                                    "\\x19\\x01",
                                    DOMAIN_SEPARATOR(),
                                    keccak256(
                                        abi.encode(
                                            PERMIT_TYPEHASH,
                                            owner,
                                            spender,
                                            value,
                                            nonces[owner]++,
                                            deadline
                                        )
                                    )
                                )
                            );
                            address recoveredAddress = ecrecover(digest, v, r, s);
                            require(
                                recoveredAddress != address(0) && recoveredAddress == owner,
                                "INVALID_PERMIT_SIGNATURE"
                            );
                            allowance[recoveredAddress][spender] = value;
                        }
                        emit Approval(owner, spender, value);
                    }
                    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                        return
                            block.chainid == INITIAL_CHAIN_ID
                                ? INITIAL_DOMAIN_SEPARATOR
                                : computeDomainSeparator();
                    }
                    function computeDomainSeparator() internal view virtual returns (bytes32) {
                        return
                            keccak256(
                                abi.encode(
                                    keccak256(
                                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                                    ),
                                    keccak256(bytes(name)),
                                    keccak256(bytes("1")),
                                    block.chainid,
                                    address(this)
                                )
                            );
                    }
                    /*///////////////////////////////////////////////////////////////
                                       INTERNAL MINT/BURN LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function _mint(address to, uint256 amount) internal virtual {
                        totalSupply += amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(address(0), to, amount);
                    }
                    function _burn(address from, uint256 amount) internal virtual {
                        balanceOf[from] -= amount;
                        // Cannot underflow because a user's balance
                        // will never be larger than the total supply.
                        unchecked {
                            totalSupply -= amount;
                        }
                        emit Transfer(from, address(0), amount);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                import {ERC20} from "./ERC20.sol";
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
                /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                library SafeTransferLib {
                    /*///////////////////////////////////////////////////////////////
                                            ETH OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferETH(address to, uint256 amount) internal {
                        bool callStatus;
                        assembly {
                            // Transfer the ETH and store if it succeeded or not.
                            callStatus := call(gas(), to, amount, 0, 0, 0, 0)
                        }
                        require(callStatus, "ETH_TRANSFER_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                           ERC20 OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferFrom(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x23b872dd00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(from, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "from" argument.
                            mstore(
                                add(freeMemoryPointer, 36),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 100 because the calldata length is 4 + 32 * 3.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FROM_FAILED"
                        );
                    }
                    function safeTransfer(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0xa9059cbb00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FAILED"
                        );
                    }
                    function safeApprove(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x095ea7b300000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                         INTERNAL HELPER LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function didLastOptionalReturnCallSucceed(bool callStatus)
                        private
                        pure
                        returns (bool success)
                    {
                        assembly {
                            // Get how many bytes the call returned.
                            let returnDataSize := returndatasize()
                            // If the call reverted:
                            if iszero(callStatus) {
                                // Copy the revert message into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Revert with the same message.
                                revert(0, returnDataSize)
                            }
                            switch returnDataSize
                            case 32 {
                                // Copy the return data into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Set success to whether it returned true.
                                success := iszero(iszero(mload(0)))
                            }
                            case 0 {
                                // There was no return data.
                                success := 1
                            }
                            default {
                                // It returned some malformed input.
                                success := 0
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {OwnableWithTransferCallback} from "./lib/OwnableWithTransferCallback.sol";
                import {ReentrancyGuard} from "./lib/ReentrancyGuard.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                import {IERC1155} from "./imports/IERC1155.sol";
                import {ERC1155Holder} from "./imports/ERC1155Holder.sol";
                /// @title The base contract for an NFT/TOKEN AMM pair
                /// @author boredGenius and 0xmons
                /// @notice This implements the core swap logic from NFT to TOKEN
                abstract contract LSSVMPair is
                    OwnableWithTransferCallback,
                    ReentrancyGuard,
                    ERC1155Holder
                {
                    enum PoolType {
                        TOKEN,
                        NFT,
                        TRADE
                    }
                    // 90%, must <= 1 - MAX_PROTOCOL_FEE (set in LSSVMPairFactory)
                    uint256 internal constant MAX_FEE = 0.90e18;
                    // The current price of the NFT
                    // @dev This is generally used to mean the immediate sell price for the next marginal NFT.
                    // However, this should NOT be assumed, as future bonding curves may use spotPrice in different ways.
                    // Use getBuyNFTQuote and getSellNFTQuote for accurate pricing info.
                    uint128 public spotPrice;
                    // The parameter for the pair's bonding curve.
                    // Units and meaning are bonding curve dependent.
                    uint128 public delta;
                    // The spread between buy and sell prices, set to be a multiplier we apply to the buy price
                    // Fee is only relevant for TRADE pools
                    // Units are in base 1e18
                    uint96 public fee;
                    // If set to 0, NFTs/tokens sent by traders during trades will be sent to the pair.
                    // Otherwise, assets will be sent to the set address. Not available for TRADE pools.
                    address payable public assetRecipient;
                    // Events
                    event SwapNFTInPair();
                    event SwapNFTOutPair();
                    event SpotPriceUpdate(uint128 newSpotPrice);
                    event TokenDeposit(uint256 amount);
                    event TokenWithdrawal(uint256 amount);
                    event NFTWithdrawal();
                    event DeltaUpdate(uint128 newDelta);
                    event FeeUpdate(uint96 newFee);
                    event AssetRecipientChange(address a);
                    // Parameterized Errors
                    error BondingCurveError(CurveErrorCodes.Error error);
                    /**
                      @notice Called during pair creation to set initial parameters
                      @dev Only called once by factory to initialize.
                      We verify this by making sure that the current owner is address(0). 
                      The Ownable library we use disallows setting the owner to be address(0), so this condition
                      should only be valid before the first initialize call. 
                      @param _owner The owner of the pair
                      @param _assetRecipient The address that will receive the TOKEN or NFT sent to this pair during swaps. NOTE: If set to address(0), they will go to the pair itself.
                      @param _delta The initial delta of the bonding curve
                      @param _fee The initial % fee taken, if this is a trade pair 
                      @param _spotPrice The initial price to sell an asset into the pair
                     */
                    function initialize(
                        address _owner,
                        address payable _assetRecipient,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice
                    ) external payable {
                        require(owner() == address(0), "Initialized");
                        __Ownable_init(_owner);
                        __ReentrancyGuard_init();
                        ICurve _bondingCurve = bondingCurve();
                        PoolType _poolType = poolType();
                        if ((_poolType == PoolType.TOKEN) || (_poolType == PoolType.NFT)) {
                            require(_fee == 0, "Only Trade Pools can have nonzero fee");
                            assetRecipient = _assetRecipient;
                        } else if (_poolType == PoolType.TRADE) {
                            require(_fee < MAX_FEE, "Trade fee must be less than 90%");
                            require(
                                _assetRecipient == address(0),
                                "Trade pools can't set asset recipient"
                            );
                            fee = _fee;
                        }
                        require(_bondingCurve.validateDelta(_delta), "Invalid delta for curve");
                        require(
                            _bondingCurve.validateSpotPrice(_spotPrice),
                            "Invalid new spot price for curve"
                        );
                        delta = _delta;
                        spotPrice = _spotPrice;
                    }
                    /**
                     * External state-changing functions
                     */
                    /**
                        @notice Sends token to the pair in exchange for any `numNFTs` NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo.
                        This swap function is meant for users who are ID agnostic
                        @param numNFTs The number of NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForAnyNFTs(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        IERC721 _nft = nft();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(
                                (numNFTs > 0) && (numNFTs <= _nft.balanceOf(address(this))),
                                "Ask for > 0 and <= balanceOf NFTs"
                            );
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            numNFTs,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendAnyNFTsToRecipient(_nft, nftRecipient, numNFTs);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends token to the pair in exchange for a specific set of NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo
                        This swap is meant for users who want specific IDs. Also higher chance of
                        reverting if some of the specified IDs leave the pool before the swap goes through.
                        @param nftIds The list of IDs of the NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForSpecificNFTs(
                        uint256[] calldata nftIds,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require((nftIds.length > 0), "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            nftIds.length,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendSpecificNFTsToRecipient(nft(), nftRecipient, nftIds);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends a set of NFTs to the pair in exchange for token
                        @dev To compute the amount of token to that will be received, call bondingCurve.getSellInfo.
                        @param nftIds The list of IDs of the NFTs to sell to the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param tokenRecipient The recipient of the token output
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return outputAmount The amount of token received
                     */
                    function swapNFTsForToken(
                        uint256[] calldata nftIds,
                        uint256 minExpectedTokenOutput,
                        address payable tokenRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external virtual nonReentrant returns (uint256 outputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.TOKEN || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(nftIds.length > 0, "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, outputAmount) = _calculateSellInfoAndUpdatePoolParams(
                            nftIds.length,
                            minExpectedTokenOutput,
                            _bondingCurve,
                            _factory
                        );
                        _sendTokenOutput(tokenRecipient, outputAmount);
                        _payProtocolFeeFromPair(_factory, protocolFee);
                        _takeNFTsFromSender(nft(), nftIds, _factory, isRouter, routerCaller);
                        emit SwapNFTInPair();
                    }
                    /**
                     * View functions
                     */
                    /**
                        @dev Used as read function to query the bonding curve for buy pricing info
                        @param numNFTs The number of NFTs to buy from the pair
                     */
                    function getBuyNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 inputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = bondingCurve().getBuyInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @dev Used as read function to query the bonding curve for sell pricing info
                        @param numNFTs The number of NFTs to sell to the pair
                     */
                    function getSellNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 outputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = bondingCurve().getSellInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @notice Returns all NFT IDs held by the pool
                     */
                    function getAllHeldIds() external view virtual returns (uint256[] memory);
                    /**
                        @notice Returns the pair's variant (NFT is enumerable or not, pair uses ETH or ERC20)
                     */
                    function pairVariant()
                        public
                        pure
                        virtual
                        returns (ILSSVMPairFactoryLike.PairVariant);
                    function factory() public pure returns (ILSSVMPairFactoryLike _factory) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _factory := shr(
                                0x60,
                                calldataload(sub(calldatasize(), paramsLength))
                            )
                        }
                    }
                    /**
                        @notice Returns the type of bonding curve that parameterizes the pair
                     */
                    function bondingCurve() public pure returns (ICurve _bondingCurve) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _bondingCurve := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 20))
                            )
                        }
                    }
                    /**
                        @notice Returns the NFT collection that parameterizes the pair
                     */
                    function nft() public pure returns (IERC721 _nft) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _nft := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 40))
                            )
                        }
                    }
                    /**
                        @notice Returns the pair's type (TOKEN/NFT/TRADE)
                     */
                    function poolType() public pure returns (PoolType _poolType) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _poolType := shr(
                                0xf8,
                                calldataload(add(sub(calldatasize(), paramsLength), 60))
                            )
                        }
                    }
                    /**
                        @notice Returns the address that assets that receives assets when a swap is done with this pair
                        Can be set to another address by the owner, if set to address(0), defaults to the pair's own address
                     */
                    function getAssetRecipient()
                        public
                        view
                        returns (address payable _assetRecipient)
                    {
                        // If it's a TRADE pool, we know the recipient is 0 (TRADE pools can't set asset recipients)
                        // so just return address(this)
                        if (poolType() == PoolType.TRADE) {
                            return payable(address(this));
                        }
                        // Otherwise, we return the recipient if it's been set
                        // or replace it with address(this) if it's 0
                        _assetRecipient = assetRecipient;
                        if (_assetRecipient == address(0)) {
                            // Tokens will be transferred to address(this)
                            _assetRecipient = payable(address(this));
                        }
                    }
                    /**
                     * Internal functions
                     */
                    /**
                        @notice Calculates the amount needed to be sent into the pair for a buy and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to purchase from the pair
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return inputAmount The amount of tokens total tokens receive
                     */
                    function _calculateBuyInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 inputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = _bondingCurve.getBuyInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if input is more than expected
                        require(inputAmount <= maxExpectedTokenInput, "In too many tokens");
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Calculates the amount needed to be sent by the pair for a sell and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to send to the the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return outputAmount The amount of tokens total tokens receive
                     */
                    function _calculateSellInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 minExpectedTokenOutput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 outputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = _bondingCurve.getSellInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if output is too little
                        require(
                            outputAmount >= minExpectedTokenOutput,
                            "Out too little tokens"
                        );
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Pulls the token input of a trade from the trader and pays the protocol fee.
                        @param inputAmount The amount of tokens to be sent
                        @param isRouter Whether or not the caller is LSSVMRouter
                        @param routerCaller If called from LSSVMRouter, store the original caller
                        @param _factory The LSSVMPairFactory which stores LSSVMRouter allowlist info
                        @param protocolFee The protocol fee to be paid
                     */
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool isRouter,
                        address routerCaller,
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends excess tokens back to the caller (if applicable)
                        @dev We send ETH back to the caller even when called from LSSVMRouter because we do an aggregate slippage check for certain bulk swaps. (Instead of sending directly back to the router caller) 
                        Excess ETH sent for one swap can then be used to help pay for the next swap.
                     */
                    function _refundTokenToSender(uint256 inputAmount) internal virtual;
                    /**
                        @notice Sends protocol fee (if it exists) back to the LSSVMPairFactory from the pair
                     */
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends tokens to a recipient
                        @param tokenRecipient The address receiving the tokens
                        @param outputAmount The amount of tokens to send
                     */
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal virtual;
                    /**
                        @notice Sends some number of NFTs to a recipient address, ID agnostic
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param numNFTs The number of NFTs to send  
                     */
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal virtual;
                    /**
                        @notice Sends specific NFTs to a recipient address
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param nftIds The specific IDs of NFTs to send  
                     */
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal virtual;
                    /**
                        @notice Takes NFTs from the caller and sends them into the pair's asset recipient
                        @dev This is used by the LSSVMPair's swapNFTForToken function. 
                        @param _nft The NFT collection to take from
                        @param nftIds The specific NFT IDs to take
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                     */
                    function _takeNFTsFromSender(
                        IERC721 _nft,
                        uint256[] calldata nftIds,
                        ILSSVMPairFactoryLike _factory,
                        bool isRouter,
                        address routerCaller
                    ) internal virtual {
                        {
                            address _assetRecipient = getAssetRecipient();
                            uint256 numNFTs = nftIds.length;
                            if (isRouter) {
                                // Verify if router is allowed
                                LSSVMRouter router = LSSVMRouter(payable(msg.sender));
                                (bool routerAllowed, ) = _factory.routerStatus(router);
                                require(routerAllowed, "Not router");
                                // Call router to pull NFTs
                                // If more than 1 NFT is being transfered, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection
                                if (numNFTs > 1) {
                                    uint256 beforeBalance = _nft.balanceOf(_assetRecipient);
                                    for (uint256 i = 0; i < numNFTs; ) {
                                        router.pairTransferNFTFrom(
                                            _nft,
                                            routerCaller,
                                            _assetRecipient,
                                            nftIds[i],
                                            pairVariant()
                                        );
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    require(
                                        (_nft.balanceOf(_assetRecipient) - beforeBalance) ==
                                            numNFTs,
                                        "NFTs not transferred"
                                    );
                                } else {
                                    router.pairTransferNFTFrom(
                                        _nft,
                                        routerCaller,
                                        _assetRecipient,
                                        nftIds[0],
                                        pairVariant()
                                    );
                                    require(
                                        _nft.ownerOf(nftIds[0]) == _assetRecipient,
                                        "NFT not transferred"
                                    );
                                }
                            } else {
                                // Pull NFTs directly from sender
                                for (uint256 i; i < numNFTs; ) {
                                    _nft.safeTransferFrom(
                                        msg.sender,
                                        _assetRecipient,
                                        nftIds[i]
                                    );
                                    unchecked {
                                        ++i;
                                    }
                                }
                            }
                        }
                    }
                    /**
                        @dev Used internally to grab pair parameters from calldata, see LSSVMPairCloner for technical details
                     */
                    function _immutableParamsLength() internal pure virtual returns (uint256);
                    /**
                     * Owner functions
                     */
                    /**
                        @notice Rescues a specified set of NFTs owned by the pair to the owner address.
                        @dev If the NFT is the pair's collection, we also remove it from the id tracking.
                        @param a The address of the NFT to transfer
                        @param nftIds The list of IDs of the NFTs to send to the owner
                     */
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        virtual;
                    /**
                        @notice Rescues ERC20 tokens from the pair to the owner. Only callable by the owner.
                        @param a The address of the token to transfer
                        @param amount The amount of tokens to send to the owner
                     */
                    function withdrawERC20(ERC20 a, uint256 amount) external virtual;
                    /**
                        @notice Rescues ERC1155 tokens from the pair to the owner. Only callable by the owner.
                        @param a The NFT to transfer
                        @param ids The NFT ids to transfer
                        @param amounts The amounts of each id to transfer
                     */
                    function withdrawERC1155(
                        IERC1155 a,
                        uint256[] calldata ids,
                        uint256[] calldata amounts
                    ) external onlyOwner {
                        a.safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
                    }
                    /**
                        @notice Updates the selling spot price. Only callable by the owner.
                        @param newSpotPrice The new selling spot price value, in Token
                     */
                    function changeSpotPrice(uint128 newSpotPrice) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateSpotPrice(newSpotPrice),
                            "Invalid new spot price for curve"
                        );
                        if (spotPrice != newSpotPrice) {
                            spotPrice = newSpotPrice;
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                    }
                    /**
                        @notice Updates the delta parameter. Only callable by the owner.
                        @param newDelta The new delta parameter
                     */
                    function changeDelta(uint128 newDelta) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateDelta(newDelta),
                            "Invalid delta for curve"
                        );
                        if (delta != newDelta) {
                            delta = newDelta;
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Updates the fee taken by the LP. Only callable by the owner.
                        Only callable if the pool is a Trade pool. Reverts if the fee is >=
                        MAX_FEE.
                        @param newFee The new LP fee percentage, 18 decimals
                     */
                    function changeFee(uint96 newFee) external onlyOwner {
                        PoolType _poolType = poolType();
                        require(_poolType == PoolType.TRADE, "Only for Trade pools");
                        require(newFee < MAX_FEE, "Trade fee must be less than 90%");
                        if (fee != newFee) {
                            fee = newFee;
                            emit FeeUpdate(newFee);
                        }
                    }
                    /**
                        @notice Changes the address that will receive assets received from
                        trades. Only callable by the owner.
                        @param newRecipient The new asset recipient
                     */
                    function changeAssetRecipient(address payable newRecipient)
                        external
                        onlyOwner
                    {
                        PoolType _poolType = poolType();
                        require(_poolType != PoolType.TRADE, "Not for Trade pools");
                        if (assetRecipient != newRecipient) {
                            assetRecipient = newRecipient;
                            emit AssetRecipientChange(newRecipient);
                        }
                    }
                    /**
                        @notice Allows the pair to make arbitrary external calls to contracts
                        whitelisted by the protocol. Only callable by the owner.
                        @param target The contract to call
                        @param data The calldata to pass to the contract
                     */
                    function call(address payable target, bytes calldata data)
                        external
                        onlyOwner
                    {
                        ILSSVMPairFactoryLike _factory = factory();
                        require(_factory.callAllowed(target), "Target must be whitelisted");
                        (bool result, ) = target.call{value: 0}(data);
                        require(result, "Call failed");
                    }
                    /**
                        @notice Allows owner to batch multiple calls, forked from: https://github.com/boringcrypto/BoringSolidity/blob/master/contracts/BoringBatchable.sol 
                        @dev Intended for withdrawing/altering pool pricing in one tx, only callable by owner, cannot change owner
                        @param calls The calldata for each call to make
                        @param revertOnFail Whether or not to revert the entire tx if any of the calls fail
                     */
                    function multicall(bytes[] calldata calls, bool revertOnFail)
                        external
                        onlyOwner
                    {
                        for (uint256 i; i < calls.length; ) {
                            (bool success, bytes memory result) = address(this).delegatecall(
                                calls[i]
                            );
                            if (!success && revertOnFail) {
                                revert(_getRevertMsg(result));
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Prevent multicall from malicious frontend sneaking in ownership change
                        require(
                            owner() == msg.sender,
                            "Ownership cannot be changed in multicall"
                        );
                    }
                    /**
                      @param _returnData The data returned from a multicall result
                      @dev Used to grab the revert string from the underlying call
                     */
                    function _getRevertMsg(bytes memory _returnData)
                        internal
                        pure
                        returns (string memory)
                    {
                        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
                        if (_returnData.length < 68) return "Transaction reverted silently";
                        assembly {
                            // Slice the sighash.
                            _returnData := add(_returnData, 0x04)
                        }
                        return abi.decode(_returnData, (string)); // All that remains is the revert string
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                import {IOwnershipTransferCallback} from "./IOwnershipTransferCallback.sol";
                import {Address} from "../imports/Address.sol";
                abstract contract OwnableWithTransferCallback {
                    using Address for address;
                    bytes4 constant TRANSFER_CALLBACK =
                        type(IOwnershipTransferCallback).interfaceId;
                    error Ownable_NotOwner();
                    error Ownable_NewOwnerZeroAddress();
                    address private _owner;
                    event OwnershipTransferred(address indexed newOwner);
                    /// @dev Initializes the contract setting the deployer as the initial owner.
                    function __Ownable_init(address initialOwner) internal {
                        _owner = initialOwner;
                    }
                    /// @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() {
                        if (owner() != msg.sender) revert Ownable_NotOwner();
                        _;
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Disallows setting to the zero address as a way to more gas-efficiently avoid reinitialization
                    /// When ownership is transferred, if the new owner implements IOwnershipTransferCallback, we make a callback
                    /// Can only be called by the current owner.
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress();
                        _transferOwnership(newOwner);
                        // Call the on ownership transfer callback if it exists
                        // @dev try/catch is around 5k gas cheaper than doing ERC165 checking
                        if (newOwner.isContract()) {
                            try
                                IOwnershipTransferCallback(newOwner).onOwnershipTransfer(
                                    msg.sender
                                )
                            {} catch (bytes memory) {}
                        }
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Internal function without access restriction.
                    function _transferOwnership(address newOwner) internal virtual {
                        _owner = newOwner;
                        emit OwnershipTransferred(newOwner);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                interface IOwnershipTransferCallback {
                    function onOwnershipTransfer(address oldOwner) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @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
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        return size > 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);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // Forked from OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol),
                // removed initializer check as we already do that in our modified Ownable
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    function __ReentrancyGuard_init() internal {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                        _;
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {CurveErrorCodes} from "./CurveErrorCodes.sol";
                interface ICurve {
                    /**
                        @notice Validates if a delta value is valid for the curve. The criteria for
                        validity can be different for each type of curve, for instance ExponentialCurve
                        requires delta to be greater than 1.
                        @param delta The delta value to be validated
                        @return valid True if delta is valid, false otherwise
                     */
                    function validateDelta(uint128 delta) external pure returns (bool valid);
                    /**
                        @notice Validates if a new spot price is valid for the curve. Spot price is generally assumed to be the immediate sell price of 1 NFT to the pool, in units of the pool's paired token.
                        @param newSpotPrice The new spot price to be set
                        @return valid True if the new spot price is valid, false otherwise
                     */
                    function validateSpotPrice(uint128 newSpotPrice)
                        external
                        view
                        returns (bool valid);
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should pay to purchase an NFT from the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is buying from the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return inputValue The amount that the user should pay, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getBuyInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 inputValue,
                            uint256 protocolFee
                        );
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should receive when selling NFTs to the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is selling to the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return outputValue The amount that the user should receive, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getSellInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 outputValue,
                            uint256 protocolFee
                        );
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                contract CurveErrorCodes {
                    enum Error {
                        OK, // No error
                        INVALID_NUMITEMS, // The numItem value is 0
                        SPOT_PRICE_OVERFLOW // The updated spot price doesn't fit into 128 bits
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                interface ILSSVMPairFactoryLike {
                    enum PairVariant {
                        ENUMERABLE_ETH,
                        MISSING_ENUMERABLE_ETH,
                        ENUMERABLE_ERC20,
                        MISSING_ENUMERABLE_ERC20
                    }
                    function protocolFeeMultiplier() external view returns (uint256);
                    function protocolFeeRecipient() external view returns (address payable);
                    function callAllowed(address target) external view returns (bool);
                    function routerStatus(LSSVMRouter router)
                        external
                        view
                        returns (bool allowed, bool wasEverAllowed);
                    function isPair(address potentialPair, PairVariant variant)
                        external
                        view
                        returns (bool);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./ERC1155Receiver.sol";
                /**
                 * @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;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./IERC1155Receiver.sol";
                import "./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);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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.
                        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. 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);
                }
                // SPDX-License-Identifier: MIT
                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 6 of 8: LSSVMPairEnumerableETH
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMPairETH} from "./LSSVMPairETH.sol";
                import {LSSVMPairEnumerable} from "./LSSVMPairEnumerable.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair where the NFT implements ERC721Enumerable, and the token is ETH
                    @author boredGenius and 0xmons
                 */
                contract LSSVMPairEnumerableETH is LSSVMPairEnumerable, LSSVMPairETH {
                    /**
                        @notice Returns the LSSVMPair type
                     */
                    function pairVariant()
                        public
                        pure
                        override
                        returns (ILSSVMPairFactoryLike.PairVariant)
                    {
                        return ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ETH;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports//IERC721.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                /**
                    @title An NFT/Token pair where the token is ETH
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairETH is LSSVMPair {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    uint256 internal constant IMMUTABLE_PARAMS_LENGTH = 61;
                    /// @inheritdoc LSSVMPair
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool, /*isRouter*/
                        address, /*routerCaller*/
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        require(msg.value >= inputAmount, "Sent too little ETH");
                        // Transfer inputAmount ETH to assetRecipient if it's been set
                        address payable _assetRecipient = getAssetRecipient();
                        if (_assetRecipient != address(this)) {
                            _assetRecipient.safeTransferETH(inputAmount - protocolFee);
                        }
                        // Take protocol fee
                        if (protocolFee > 0) {
                            // Round down to the actual ETH balance if there are numerical stability issues with the bonding curve calculations
                            if (protocolFee > address(this).balance) {
                                protocolFee = address(this).balance;
                            }
                            if (protocolFee > 0) {
                                payable(address(_factory)).safeTransferETH(protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _refundTokenToSender(uint256 inputAmount) internal override {
                        // Give excess ETH back to caller
                        if (msg.value > inputAmount) {
                            payable(msg.sender).safeTransferETH(msg.value - inputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        // Take protocol fee
                        if (protocolFee > 0) {
                            // Round down to the actual ETH balance if there are numerical stability issues with the bonding curve calculations
                            if (protocolFee > address(this).balance) {
                                protocolFee = address(this).balance;
                            }
                            if (protocolFee > 0) {
                                payable(address(_factory)).safeTransferETH(protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal override {
                        // Send ETH to caller
                        if (outputAmount > 0) {
                            tokenRecipient.safeTransferETH(outputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    // @dev see LSSVMPairCloner for params length calculation
                    function _immutableParamsLength() internal pure override returns (uint256) {
                        return IMMUTABLE_PARAMS_LENGTH;
                    }
                    /**
                        @notice Withdraws all token owned by the pair to the owner address.
                        @dev Only callable by the owner.
                     */
                    function withdrawAllETH() external onlyOwner {
                        withdrawETH(address(this).balance);
                    }
                    /**
                        @notice Withdraws a specified amount of token owned by the pair to the owner address.
                        @dev Only callable by the owner.
                        @param amount The amount of token to send to the owner. If the pair's balance is less than
                        this value, the transaction will be reverted.
                     */
                    function withdrawETH(uint256 amount) public onlyOwner {
                        payable(owner()).safeTransferETH(amount);
                        // emit event since ETH is the pair token
                        emit TokenWithdrawal(amount);
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC20(ERC20 a, uint256 amount)
                        external
                        override
                        onlyOwner
                    {
                        a.safeTransfer(msg.sender, amount);
                    }
                    /**
                        @dev All ETH transfers into the pair are accepted. This is the main method
                        for the owner to top up the pair's token reserves.
                     */
                    receive() external payable {
                        emit TokenDeposit(msg.value);
                    }
                    /**
                        @dev All ETH transfers into the pair are accepted. This is the main method
                        for the owner to top up the pair's token reserves.
                     */
                    fallback() external payable {
                        // Only allow calls without function selector
                        require(msg.data.length == _immutableParamsLength());
                        emit TokenDeposit(msg.value);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                abstract contract ERC20 {
                    /*///////////////////////////////////////////////////////////////
                                                  EVENTS
                    //////////////////////////////////////////////////////////////*/
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 amount
                    );
                    /*///////////////////////////////////////////////////////////////
                                             METADATA STORAGE
                    //////////////////////////////////////////////////////////////*/
                    string public name;
                    string public symbol;
                    uint8 public immutable decimals;
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    uint256 public totalSupply;
                    mapping(address => uint256) public balanceOf;
                    mapping(address => mapping(address => uint256)) public allowance;
                    /*///////////////////////////////////////////////////////////////
                                           EIP-2612 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    bytes32 public constant PERMIT_TYPEHASH =
                        keccak256(
                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                        );
                    uint256 internal immutable INITIAL_CHAIN_ID;
                    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                    mapping(address => uint256) public nonces;
                    /*///////////////////////////////////////////////////////////////
                                               CONSTRUCTOR
                    //////////////////////////////////////////////////////////////*/
                    constructor(
                        string memory _name,
                        string memory _symbol,
                        uint8 _decimals
                    ) {
                        name = _name;
                        symbol = _symbol;
                        decimals = _decimals;
                        INITIAL_CHAIN_ID = block.chainid;
                        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                    }
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function approve(address spender, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        allowance[msg.sender][spender] = amount;
                        emit Approval(msg.sender, spender, amount);
                        return true;
                    }
                    function transfer(address to, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        balanceOf[msg.sender] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(msg.sender, to, amount);
                        return true;
                    }
                    function transferFrom(
                        address from,
                        address to,
                        uint256 amount
                    ) public virtual returns (bool) {
                        if (allowance[from][msg.sender] != type(uint256).max) {
                            allowance[from][msg.sender] -= amount;
                        }
                        balanceOf[from] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        return true;
                    }
                    /*///////////////////////////////////////////////////////////////
                                              EIP-2612 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public virtual {
                        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                        // Unchecked because the only math done is incrementing
                        // the owner's nonce which cannot realistically overflow.
                        unchecked {
                            bytes32 digest = keccak256(
                                abi.encodePacked(
                                    "\\x19\\x01",
                                    DOMAIN_SEPARATOR(),
                                    keccak256(
                                        abi.encode(
                                            PERMIT_TYPEHASH,
                                            owner,
                                            spender,
                                            value,
                                            nonces[owner]++,
                                            deadline
                                        )
                                    )
                                )
                            );
                            address recoveredAddress = ecrecover(digest, v, r, s);
                            require(
                                recoveredAddress != address(0) && recoveredAddress == owner,
                                "INVALID_PERMIT_SIGNATURE"
                            );
                            allowance[recoveredAddress][spender] = value;
                        }
                        emit Approval(owner, spender, value);
                    }
                    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                        return
                            block.chainid == INITIAL_CHAIN_ID
                                ? INITIAL_DOMAIN_SEPARATOR
                                : computeDomainSeparator();
                    }
                    function computeDomainSeparator() internal view virtual returns (bytes32) {
                        return
                            keccak256(
                                abi.encode(
                                    keccak256(
                                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                                    ),
                                    keccak256(bytes(name)),
                                    keccak256(bytes("1")),
                                    block.chainid,
                                    address(this)
                                )
                            );
                    }
                    /*///////////////////////////////////////////////////////////////
                                       INTERNAL MINT/BURN LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function _mint(address to, uint256 amount) internal virtual {
                        totalSupply += amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(address(0), to, amount);
                    }
                    function _burn(address from, uint256 amount) internal virtual {
                        balanceOf[from] -= amount;
                        // Cannot underflow because a user's balance
                        // will never be larger than the total supply.
                        unchecked {
                            totalSupply -= amount;
                        }
                        emit Transfer(from, address(0), amount);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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`, 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 Returns the account approved for `tokenId` token.
                     *
                     * Requirements:
                     *
                     * - `tokenId` must exist.
                     */
                    function getApproved(uint256 tokenId)
                        external
                        view
                        returns (address operator);
                    /**
                     * @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 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);
                    /**
                     * @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;
                }
                // SPDX-License-Identifier: MIT
                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);
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                import {ERC20} from "./ERC20.sol";
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
                /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                library SafeTransferLib {
                    /*///////////////////////////////////////////////////////////////
                                            ETH OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferETH(address to, uint256 amount) internal {
                        bool callStatus;
                        assembly {
                            // Transfer the ETH and store if it succeeded or not.
                            callStatus := call(gas(), to, amount, 0, 0, 0, 0)
                        }
                        require(callStatus, "ETH_TRANSFER_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                           ERC20 OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferFrom(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x23b872dd00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(from, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "from" argument.
                            mstore(
                                add(freeMemoryPointer, 36),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 100 because the calldata length is 4 + 32 * 3.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FROM_FAILED"
                        );
                    }
                    function safeTransfer(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0xa9059cbb00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FAILED"
                        );
                    }
                    function safeApprove(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x095ea7b300000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                         INTERNAL HELPER LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function didLastOptionalReturnCallSucceed(bool callStatus)
                        private
                        pure
                        returns (bool success)
                    {
                        assembly {
                            // Get how many bytes the call returned.
                            let returnDataSize := returndatasize()
                            // If the call reverted:
                            if iszero(callStatus) {
                                // Copy the revert message into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Revert with the same message.
                                revert(0, returnDataSize)
                            }
                            switch returnDataSize
                            case 32 {
                                // Copy the return data into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Set success to whether it returned true.
                                success := iszero(iszero(mload(0)))
                            }
                            case 0 {
                                // There was no return data.
                                success := 1
                            }
                            default {
                                // It returned some malformed input.
                                success := 0
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {OwnableWithTransferCallback} from "./lib/OwnableWithTransferCallback.sol";
                import {ReentrancyGuard} from "./lib/ReentrancyGuard.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                import {IERC1155} from "./imports/IERC1155.sol";
                import {ERC1155Holder} from "./imports/ERC1155Holder.sol";
                /// @title The base contract for an NFT/TOKEN AMM pair
                /// @author boredGenius and 0xmons
                /// @notice This implements the core swap logic from NFT to TOKEN
                abstract contract LSSVMPair is
                    OwnableWithTransferCallback,
                    ReentrancyGuard,
                    ERC1155Holder
                {
                    enum PoolType {
                        TOKEN,
                        NFT,
                        TRADE
                    }
                    // 90%, must <= 1 - MAX_PROTOCOL_FEE (set in LSSVMPairFactory)
                    uint256 internal constant MAX_FEE = 0.90e18;
                    // The current price of the NFT
                    // @dev This is generally used to mean the immediate sell price for the next marginal NFT.
                    // However, this should NOT be assumed, as future bonding curves may use spotPrice in different ways.
                    // Use getBuyNFTQuote and getSellNFTQuote for accurate pricing info.
                    uint128 public spotPrice;
                    // The parameter for the pair's bonding curve.
                    // Units and meaning are bonding curve dependent.
                    uint128 public delta;
                    // The spread between buy and sell prices, set to be a multiplier we apply to the buy price
                    // Fee is only relevant for TRADE pools
                    // Units are in base 1e18
                    uint96 public fee;
                    // If set to 0, NFTs/tokens sent by traders during trades will be sent to the pair.
                    // Otherwise, assets will be sent to the set address. Not available for TRADE pools.
                    address payable public assetRecipient;
                    // Events
                    event SwapNFTInPair();
                    event SwapNFTOutPair();
                    event SpotPriceUpdate(uint128 newSpotPrice);
                    event TokenDeposit(uint256 amount);
                    event TokenWithdrawal(uint256 amount);
                    event NFTWithdrawal();
                    event DeltaUpdate(uint128 newDelta);
                    event FeeUpdate(uint96 newFee);
                    event AssetRecipientChange(address a);
                    // Parameterized Errors
                    error BondingCurveError(CurveErrorCodes.Error error);
                    /**
                      @notice Called during pair creation to set initial parameters
                      @dev Only called once by factory to initialize.
                      We verify this by making sure that the current owner is address(0). 
                      The Ownable library we use disallows setting the owner to be address(0), so this condition
                      should only be valid before the first initialize call. 
                      @param _owner The owner of the pair
                      @param _assetRecipient The address that will receive the TOKEN or NFT sent to this pair during swaps. NOTE: If set to address(0), they will go to the pair itself.
                      @param _delta The initial delta of the bonding curve
                      @param _fee The initial % fee taken, if this is a trade pair 
                      @param _spotPrice The initial price to sell an asset into the pair
                     */
                    function initialize(
                        address _owner,
                        address payable _assetRecipient,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice
                    ) external payable {
                        require(owner() == address(0), "Initialized");
                        __Ownable_init(_owner);
                        __ReentrancyGuard_init();
                        ICurve _bondingCurve = bondingCurve();
                        PoolType _poolType = poolType();
                        if ((_poolType == PoolType.TOKEN) || (_poolType == PoolType.NFT)) {
                            require(_fee == 0, "Only Trade Pools can have nonzero fee");
                            assetRecipient = _assetRecipient;
                        } else if (_poolType == PoolType.TRADE) {
                            require(_fee < MAX_FEE, "Trade fee must be less than 90%");
                            require(
                                _assetRecipient == address(0),
                                "Trade pools can't set asset recipient"
                            );
                            fee = _fee;
                        }
                        require(_bondingCurve.validateDelta(_delta), "Invalid delta for curve");
                        require(
                            _bondingCurve.validateSpotPrice(_spotPrice),
                            "Invalid new spot price for curve"
                        );
                        delta = _delta;
                        spotPrice = _spotPrice;
                    }
                    /**
                     * External state-changing functions
                     */
                    /**
                        @notice Sends token to the pair in exchange for any `numNFTs` NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo.
                        This swap function is meant for users who are ID agnostic
                        @param numNFTs The number of NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForAnyNFTs(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        IERC721 _nft = nft();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(
                                (numNFTs > 0) && (numNFTs <= _nft.balanceOf(address(this))),
                                "Ask for > 0 and <= balanceOf NFTs"
                            );
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            numNFTs,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendAnyNFTsToRecipient(_nft, nftRecipient, numNFTs);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends token to the pair in exchange for a specific set of NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo
                        This swap is meant for users who want specific IDs. Also higher chance of
                        reverting if some of the specified IDs leave the pool before the swap goes through.
                        @param nftIds The list of IDs of the NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForSpecificNFTs(
                        uint256[] calldata nftIds,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require((nftIds.length > 0), "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            nftIds.length,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendSpecificNFTsToRecipient(nft(), nftRecipient, nftIds);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends a set of NFTs to the pair in exchange for token
                        @dev To compute the amount of token to that will be received, call bondingCurve.getSellInfo.
                        @param nftIds The list of IDs of the NFTs to sell to the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param tokenRecipient The recipient of the token output
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return outputAmount The amount of token received
                     */
                    function swapNFTsForToken(
                        uint256[] calldata nftIds,
                        uint256 minExpectedTokenOutput,
                        address payable tokenRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external virtual nonReentrant returns (uint256 outputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.TOKEN || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(nftIds.length > 0, "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, outputAmount) = _calculateSellInfoAndUpdatePoolParams(
                            nftIds.length,
                            minExpectedTokenOutput,
                            _bondingCurve,
                            _factory
                        );
                        _sendTokenOutput(tokenRecipient, outputAmount);
                        _payProtocolFeeFromPair(_factory, protocolFee);
                        _takeNFTsFromSender(nft(), nftIds, _factory, isRouter, routerCaller);
                        emit SwapNFTInPair();
                    }
                    /**
                     * View functions
                     */
                    /**
                        @dev Used as read function to query the bonding curve for buy pricing info
                        @param numNFTs The number of NFTs to buy from the pair
                     */
                    function getBuyNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 inputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = bondingCurve().getBuyInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @dev Used as read function to query the bonding curve for sell pricing info
                        @param numNFTs The number of NFTs to sell to the pair
                     */
                    function getSellNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 outputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = bondingCurve().getSellInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @notice Returns all NFT IDs held by the pool
                     */
                    function getAllHeldIds() external view virtual returns (uint256[] memory);
                    /**
                        @notice Returns the pair's variant (NFT is enumerable or not, pair uses ETH or ERC20)
                     */
                    function pairVariant()
                        public
                        pure
                        virtual
                        returns (ILSSVMPairFactoryLike.PairVariant);
                    function factory() public pure returns (ILSSVMPairFactoryLike _factory) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _factory := shr(
                                0x60,
                                calldataload(sub(calldatasize(), paramsLength))
                            )
                        }
                    }
                    /**
                        @notice Returns the type of bonding curve that parameterizes the pair
                     */
                    function bondingCurve() public pure returns (ICurve _bondingCurve) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _bondingCurve := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 20))
                            )
                        }
                    }
                    /**
                        @notice Returns the NFT collection that parameterizes the pair
                     */
                    function nft() public pure returns (IERC721 _nft) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _nft := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 40))
                            )
                        }
                    }
                    /**
                        @notice Returns the pair's type (TOKEN/NFT/TRADE)
                     */
                    function poolType() public pure returns (PoolType _poolType) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _poolType := shr(
                                0xf8,
                                calldataload(add(sub(calldatasize(), paramsLength), 60))
                            )
                        }
                    }
                    /**
                        @notice Returns the address that assets that receives assets when a swap is done with this pair
                        Can be set to another address by the owner, if set to address(0), defaults to the pair's own address
                     */
                    function getAssetRecipient()
                        public
                        view
                        returns (address payable _assetRecipient)
                    {
                        // If it's a TRADE pool, we know the recipient is 0 (TRADE pools can't set asset recipients)
                        // so just return address(this)
                        if (poolType() == PoolType.TRADE) {
                            return payable(address(this));
                        }
                        // Otherwise, we return the recipient if it's been set
                        // or replace it with address(this) if it's 0
                        _assetRecipient = assetRecipient;
                        if (_assetRecipient == address(0)) {
                            // Tokens will be transferred to address(this)
                            _assetRecipient = payable(address(this));
                        }
                    }
                    /**
                     * Internal functions
                     */
                    /**
                        @notice Calculates the amount needed to be sent into the pair for a buy and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to purchase from the pair
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return inputAmount The amount of tokens total tokens receive
                     */
                    function _calculateBuyInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 inputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = _bondingCurve.getBuyInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if input is more than expected
                        require(inputAmount <= maxExpectedTokenInput, "In too many tokens");
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Calculates the amount needed to be sent by the pair for a sell and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to send to the the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return outputAmount The amount of tokens total tokens receive
                     */
                    function _calculateSellInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 minExpectedTokenOutput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 outputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = _bondingCurve.getSellInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if output is too little
                        require(
                            outputAmount >= minExpectedTokenOutput,
                            "Out too little tokens"
                        );
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Pulls the token input of a trade from the trader and pays the protocol fee.
                        @param inputAmount The amount of tokens to be sent
                        @param isRouter Whether or not the caller is LSSVMRouter
                        @param routerCaller If called from LSSVMRouter, store the original caller
                        @param _factory The LSSVMPairFactory which stores LSSVMRouter allowlist info
                        @param protocolFee The protocol fee to be paid
                     */
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool isRouter,
                        address routerCaller,
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends excess tokens back to the caller (if applicable)
                        @dev We send ETH back to the caller even when called from LSSVMRouter because we do an aggregate slippage check for certain bulk swaps. (Instead of sending directly back to the router caller) 
                        Excess ETH sent for one swap can then be used to help pay for the next swap.
                     */
                    function _refundTokenToSender(uint256 inputAmount) internal virtual;
                    /**
                        @notice Sends protocol fee (if it exists) back to the LSSVMPairFactory from the pair
                     */
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends tokens to a recipient
                        @param tokenRecipient The address receiving the tokens
                        @param outputAmount The amount of tokens to send
                     */
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal virtual;
                    /**
                        @notice Sends some number of NFTs to a recipient address, ID agnostic
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param numNFTs The number of NFTs to send  
                     */
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal virtual;
                    /**
                        @notice Sends specific NFTs to a recipient address
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param nftIds The specific IDs of NFTs to send  
                     */
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal virtual;
                    /**
                        @notice Takes NFTs from the caller and sends them into the pair's asset recipient
                        @dev This is used by the LSSVMPair's swapNFTForToken function. 
                        @param _nft The NFT collection to take from
                        @param nftIds The specific NFT IDs to take
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                     */
                    function _takeNFTsFromSender(
                        IERC721 _nft,
                        uint256[] calldata nftIds,
                        ILSSVMPairFactoryLike _factory,
                        bool isRouter,
                        address routerCaller
                    ) internal virtual {
                        {
                            address _assetRecipient = getAssetRecipient();
                            uint256 numNFTs = nftIds.length;
                            if (isRouter) {
                                // Verify if router is allowed
                                LSSVMRouter router = LSSVMRouter(payable(msg.sender));
                                (bool routerAllowed, ) = _factory.routerStatus(router);
                                require(routerAllowed, "Not router");
                                // Call router to pull NFTs
                                // If more than 1 NFT is being transfered, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection
                                if (numNFTs > 1) {
                                    uint256 beforeBalance = _nft.balanceOf(_assetRecipient);
                                    for (uint256 i = 0; i < numNFTs; ) {
                                        router.pairTransferNFTFrom(
                                            _nft,
                                            routerCaller,
                                            _assetRecipient,
                                            nftIds[i],
                                            pairVariant()
                                        );
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    require(
                                        (_nft.balanceOf(_assetRecipient) - beforeBalance) ==
                                            numNFTs,
                                        "NFTs not transferred"
                                    );
                                } else {
                                    router.pairTransferNFTFrom(
                                        _nft,
                                        routerCaller,
                                        _assetRecipient,
                                        nftIds[0],
                                        pairVariant()
                                    );
                                    require(
                                        _nft.ownerOf(nftIds[0]) == _assetRecipient,
                                        "NFT not transferred"
                                    );
                                }
                            } else {
                                // Pull NFTs directly from sender
                                for (uint256 i; i < numNFTs; ) {
                                    _nft.safeTransferFrom(
                                        msg.sender,
                                        _assetRecipient,
                                        nftIds[i]
                                    );
                                    unchecked {
                                        ++i;
                                    }
                                }
                            }
                        }
                    }
                    /**
                        @dev Used internally to grab pair parameters from calldata, see LSSVMPairCloner for technical details
                     */
                    function _immutableParamsLength() internal pure virtual returns (uint256);
                    /**
                     * Owner functions
                     */
                    /**
                        @notice Rescues a specified set of NFTs owned by the pair to the owner address.
                        @dev If the NFT is the pair's collection, we also remove it from the id tracking.
                        @param a The address of the NFT to transfer
                        @param nftIds The list of IDs of the NFTs to send to the owner
                     */
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        virtual;
                    /**
                        @notice Rescues ERC20 tokens from the pair to the owner. Only callable by the owner.
                        @param a The address of the token to transfer
                        @param amount The amount of tokens to send to the owner
                     */
                    function withdrawERC20(ERC20 a, uint256 amount) external virtual;
                    /**
                        @notice Rescues ERC1155 tokens from the pair to the owner. Only callable by the owner.
                        @param a The NFT to transfer
                        @param ids The NFT ids to transfer
                        @param amounts The amounts of each id to transfer
                     */
                    function withdrawERC1155(
                        IERC1155 a,
                        uint256[] calldata ids,
                        uint256[] calldata amounts
                    ) external onlyOwner {
                        a.safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
                    }
                    /**
                        @notice Updates the selling spot price. Only callable by the owner.
                        @param newSpotPrice The new selling spot price value, in Token
                     */
                    function changeSpotPrice(uint128 newSpotPrice) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateSpotPrice(newSpotPrice),
                            "Invalid new spot price for curve"
                        );
                        if (spotPrice != newSpotPrice) {
                            spotPrice = newSpotPrice;
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                    }
                    /**
                        @notice Updates the delta parameter. Only callable by the owner.
                        @param newDelta The new delta parameter
                     */
                    function changeDelta(uint128 newDelta) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateDelta(newDelta),
                            "Invalid delta for curve"
                        );
                        if (delta != newDelta) {
                            delta = newDelta;
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Updates the fee taken by the LP. Only callable by the owner.
                        Only callable if the pool is a Trade pool. Reverts if the fee is >=
                        MAX_FEE.
                        @param newFee The new LP fee percentage, 18 decimals
                     */
                    function changeFee(uint96 newFee) external onlyOwner {
                        PoolType _poolType = poolType();
                        require(_poolType == PoolType.TRADE, "Only for Trade pools");
                        require(newFee < MAX_FEE, "Trade fee must be less than 90%");
                        if (fee != newFee) {
                            fee = newFee;
                            emit FeeUpdate(newFee);
                        }
                    }
                    /**
                        @notice Changes the address that will receive assets received from
                        trades. Only callable by the owner.
                        @param newRecipient The new asset recipient
                     */
                    function changeAssetRecipient(address payable newRecipient)
                        external
                        onlyOwner
                    {
                        PoolType _poolType = poolType();
                        require(_poolType != PoolType.TRADE, "Not for Trade pools");
                        if (assetRecipient != newRecipient) {
                            assetRecipient = newRecipient;
                            emit AssetRecipientChange(newRecipient);
                        }
                    }
                    /**
                        @notice Allows the pair to make arbitrary external calls to contracts
                        whitelisted by the protocol. Only callable by the owner.
                        @param target The contract to call
                        @param data The calldata to pass to the contract
                     */
                    function call(address payable target, bytes calldata data)
                        external
                        onlyOwner
                    {
                        ILSSVMPairFactoryLike _factory = factory();
                        require(_factory.callAllowed(target), "Target must be whitelisted");
                        (bool result, ) = target.call{value: 0}(data);
                        require(result, "Call failed");
                    }
                    /**
                        @notice Allows owner to batch multiple calls, forked from: https://github.com/boringcrypto/BoringSolidity/blob/master/contracts/BoringBatchable.sol 
                        @dev Intended for withdrawing/altering pool pricing in one tx, only callable by owner, cannot change owner
                        @param calls The calldata for each call to make
                        @param revertOnFail Whether or not to revert the entire tx if any of the calls fail
                     */
                    function multicall(bytes[] calldata calls, bool revertOnFail)
                        external
                        onlyOwner
                    {
                        for (uint256 i; i < calls.length; ) {
                            (bool success, bytes memory result) = address(this).delegatecall(
                                calls[i]
                            );
                            if (!success && revertOnFail) {
                                revert(_getRevertMsg(result));
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Prevent multicall from malicious frontend sneaking in ownership change
                        require(
                            owner() == msg.sender,
                            "Ownership cannot be changed in multicall"
                        );
                    }
                    /**
                      @param _returnData The data returned from a multicall result
                      @dev Used to grab the revert string from the underlying call
                     */
                    function _getRevertMsg(bytes memory _returnData)
                        internal
                        pure
                        returns (string memory)
                    {
                        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
                        if (_returnData.length < 68) return "Transaction reverted silently";
                        assembly {
                            // Slice the sighash.
                            _returnData := add(_returnData, 0x04)
                        }
                        return abi.decode(_returnData, (string)); // All that remains is the revert string
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                import {IOwnershipTransferCallback} from "./IOwnershipTransferCallback.sol";
                import {Address} from "../imports/Address.sol";
                abstract contract OwnableWithTransferCallback {
                    using Address for address;
                    bytes4 constant TRANSFER_CALLBACK =
                        type(IOwnershipTransferCallback).interfaceId;
                    error Ownable_NotOwner();
                    error Ownable_NewOwnerZeroAddress();
                    address private _owner;
                    event OwnershipTransferred(address indexed newOwner);
                    /// @dev Initializes the contract setting the deployer as the initial owner.
                    function __Ownable_init(address initialOwner) internal {
                        _owner = initialOwner;
                    }
                    /// @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() {
                        if (owner() != msg.sender) revert Ownable_NotOwner();
                        _;
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Disallows setting to the zero address as a way to more gas-efficiently avoid reinitialization
                    /// When ownership is transferred, if the new owner implements IOwnershipTransferCallback, we make a callback
                    /// Can only be called by the current owner.
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress();
                        _transferOwnership(newOwner);
                        // Call the on ownership transfer callback if it exists
                        // @dev try/catch is around 5k gas cheaper than doing ERC165 checking
                        if (newOwner.isContract()) {
                            try
                                IOwnershipTransferCallback(newOwner).onOwnershipTransfer(
                                    msg.sender
                                )
                            {} catch (bytes memory) {}
                        }
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Internal function without access restriction.
                    function _transferOwnership(address newOwner) internal virtual {
                        _owner = newOwner;
                        emit OwnershipTransferred(newOwner);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                interface IOwnershipTransferCallback {
                    function onOwnershipTransfer(address oldOwner) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @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
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        return size > 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);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // Forked from OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol),
                // removed initializer check as we already do that in our modified Ownable
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    function __ReentrancyGuard_init() internal {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                        _;
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {CurveErrorCodes} from "./CurveErrorCodes.sol";
                interface ICurve {
                    /**
                        @notice Validates if a delta value is valid for the curve. The criteria for
                        validity can be different for each type of curve, for instance ExponentialCurve
                        requires delta to be greater than 1.
                        @param delta The delta value to be validated
                        @return valid True if delta is valid, false otherwise
                     */
                    function validateDelta(uint128 delta) external pure returns (bool valid);
                    /**
                        @notice Validates if a new spot price is valid for the curve. Spot price is generally assumed to be the immediate sell price of 1 NFT to the pool, in units of the pool's paired token.
                        @param newSpotPrice The new spot price to be set
                        @return valid True if the new spot price is valid, false otherwise
                     */
                    function validateSpotPrice(uint128 newSpotPrice)
                        external
                        view
                        returns (bool valid);
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should pay to purchase an NFT from the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is buying from the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return inputValue The amount that the user should pay, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getBuyInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 inputValue,
                            uint256 protocolFee
                        );
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should receive when selling NFTs to the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is selling to the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return outputValue The amount that the user should receive, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getSellInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 outputValue,
                            uint256 protocolFee
                        );
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                contract CurveErrorCodes {
                    enum Error {
                        OK, // No error
                        INVALID_NUMITEMS, // The numItem value is 0
                        SPOT_PRICE_OVERFLOW // The updated spot price doesn't fit into 128 bits
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721} from "./imports/IERC721.sol";
                import {ERC20} from "./imports/ERC20.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                contract LSSVMRouter {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    struct PairSwapAny {
                        LSSVMPair pair;
                        uint256 numItems;
                    }
                    struct PairSwapSpecific {
                        LSSVMPair pair;
                        uint256[] nftIds;
                    }
                    struct RobustPairSwapAny {
                        PairSwapAny swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecific {
                        PairSwapSpecific swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecificForToken {
                        PairSwapSpecific swapInfo;
                        uint256 minOutput;
                    }
                    struct NFTsForAnyNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapAny[] tokenToNFTTrades;
                    }
                    struct NFTsForSpecificNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapSpecific[] tokenToNFTTrades;
                    }
                    struct RobustPairNFTsFoTokenAndTokenforNFTsTrade {
                        RobustPairSwapSpecific[] tokenToNFTTrades;
                        RobustPairSwapSpecificForToken[] nftToTokenTrades;
                        uint256 inputAmount;
                        address payable tokenRecipient;
                        address nftRecipient;
                    }
                    modifier checkDeadline(uint256 deadline) {
                        _checkDeadline(deadline);
                        _;
                    }
                    ILSSVMPairFactoryLike public immutable factory;
                    constructor(ILSSVMPairFactoryLike _factory) {
                        factory = _factory;
                    }
                    /**
                        ETH swaps
                     */
                    /**
                        @notice Swaps ETH into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForAnyNFTs(swapList, msg.value, ethRecipient, nftRecipient);
                    }
                    /**
                        @notice Swaps ETH into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForSpecificNFTs(
                                swapList,
                                msg.value,
                                ethRecipient,
                                nftRecipient
                            );
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForAnyNFTsThroughETH(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for any NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForSpecificNFTsThroughETH(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for specific NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        ERC20 swaps
                        Note: All ERC20 swaps assume that a single ERC20 token is used for all the pairs involved.
                        Swapping using multiple tokens in the same transaction is possible, but the slippage checks
                        & the return values will be meaningless, and may lead to undefined behavior.
                        Note: The sender should ideally grant infinite token approval to the router in order for NFT-to-NFT
                        swaps to work smoothly.
                     */
                    /**
                        @notice Swaps ERC20 tokens into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForAnyNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps ERC20 tokens into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForSpecificNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps NFTs into ETH/ERC20 using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param minOutput The minimum acceptable total tokens received
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total tokens received
                     */
                    function swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        return _swapNFTsForToken(swapList, minOutput, payable(tokenRecipient));
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForAnyNFTsThroughERC20(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for any NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForSpecificNFTsThroughERC20(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for specific NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        Robust Swaps
                        These are "robust" versions of the NFT<>Token swap functions which will never revert due to slippage
                        Instead, users specify a per-swap max cost. If the price changes more than the user specifies, no swap is attempted. This allows users to specify a batch of swaps, and execute as many of them as possible.
                     */
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @notice Swaps as much ETH for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        // Try doing each swap
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs{
                                    value: pairCost
                                }(
                                    swapList[i].swapInfo.numItems,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs{value: pairCost}(
                                    swapList[i].swapInfo.nftIds,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                        
                     */
                    function robustSwapERC20ForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs(
                                        swapList[i].swapInfo.numItems,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for specific NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapERC20ForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs(
                                        swapList[i].swapInfo.nftIds,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many NFTs for tokens as possible, respecting the per-swap min output
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH/ERC20 received
                     */
                    function robustSwapNFTsForToken(
                        RobustPairSwapSpecificForToken[] calldata swapList,
                        address payable tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            uint256 pairOutput;
                            // Locally scoped to avoid stack too deep error
                            {
                                CurveErrorCodes.Error error;
                                (error, , , pairOutput, ) = swapList[i]
                                    .swapInfo
                                    .pair
                                    .getSellNFTQuote(swapList[i].swapInfo.nftIds.length);
                                if (error != CurveErrorCodes.Error.OK) {
                                    unchecked {
                                        ++i;
                                    }
                                    continue;
                                }
                            }
                            // If at least equal to our minOutput, proceed
                            if (pairOutput >= swapList[i].minOutput) {
                                // Do the swap and update outputAmount with how many tokens we got
                                outputAmount += swapList[i].swapInfo.pair.swapNFTsForToken(
                                    swapList[i].swapInfo.nftIds,
                                    0,
                                    tokenRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ETH and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapETHForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = msg.value;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    // We know how much ETH to send because we already did the math above
                                    // So we just send that much
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs{value: pairCost}(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds,
                                        pairCost,
                                        params.nftRecipient,
                                        true,
                                        msg.sender
                                    );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                            // Return remaining value to sender
                            if (remainingValue > 0) {
                                params.tokenRecipient.safeTransferETH(remainingValue);
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ERC20, and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapERC20ForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = params.inputAmount;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs(
                                            params.tokenToNFTTrades[i].swapInfo.nftIds,
                                            pairCost,
                                            params.nftRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    receive() external payable {}
                    /**
                        Restricted functions
                     */
                    /**
                        @dev Allows an ERC20 pair contract to transfer ERC20 tokens directly from
                        the sender, in order to minimize the number of token transfers. Only callable by an ERC20 pair.
                        @param token The ERC20 token to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param amount The amount of tokens to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferERC20From(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // verify caller is an ERC20 pair
                        require(
                            variant == ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ERC20 ||
                                variant ==
                                ILSSVMPairFactoryLike.PairVariant.MISSING_ENUMERABLE_ERC20,
                            "Not ERC20 pair"
                        );
                        // transfer tokens to pair
                        token.safeTransferFrom(from, to, amount);
                    }
                    /**
                        @dev Allows a pair contract to transfer ERC721 NFTs directly from
                        the sender, in order to minimize the number of token transfers. Only callable by a pair.
                        @param nft The ERC721 NFT to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param id The ID of the NFT to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferNFTFrom(
                        IERC721 nft,
                        address from,
                        address to,
                        uint256 id,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // transfer NFTs to pair
                        nft.safeTransferFrom(from, to, id);
                    }
                    /**
                        Internal functions
                     */
                    /**
                        @param deadline The last valid time for a swap
                     */
                    function _checkDeadline(uint256 deadline) internal view {
                        require(block.timestamp <= deadline, "Deadline passed");
                    }
                    /**
                        @notice Internal function used to swap ETH for any NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].numItems
                            );
                            // Require no error
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs{
                                value: pairCost
                            }(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap ETH for a specific set of NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].nftIds.length
                            );
                            // Require no errors
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs{
                                value: pairCost
                            }(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for any NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for specific NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps NFTs for tokens, designed to be used for 1 token at a time
                        @dev Calling with multiple tokens is permitted, BUT minOutput will be 
                        far from enough of a safety check because different tokens almost certainly have different unit prices.
                        @param swapList The list of pairs and swap calldata 
                        @param minOutput The minimum number of tokens to be receieved frm the swaps 
                        @param tokenRecipient The address that receives the tokens
                        @return outputAmount The number of tokens to be received
                     */
                    function _swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address payable tokenRecipient
                    ) internal returns (uint256 outputAmount) {
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Do the swap for token and then update outputAmount
                            // Note: minExpectedTokenOutput is set to 0 since we're doing an aggregate slippage check below
                            outputAmount += swapList[i].pair.swapNFTsForToken(
                                swapList[i].nftIds,
                                0,
                                tokenRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Aggregate slippage check
                        require(outputAmount >= minOutput, "outputAmount too low");
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                interface ILSSVMPairFactoryLike {
                    enum PairVariant {
                        ENUMERABLE_ETH,
                        MISSING_ENUMERABLE_ETH,
                        ENUMERABLE_ERC20,
                        MISSING_ENUMERABLE_ERC20
                    }
                    function protocolFeeMultiplier() external view returns (uint256);
                    function protocolFeeRecipient() external view returns (address payable);
                    function callAllowed(address target) external view returns (bool);
                    function routerStatus(LSSVMRouter router)
                        external
                        view
                        returns (bool allowed, bool wasEverAllowed);
                    function isPair(address potentialPair, PairVariant variant)
                        external
                        view
                        returns (bool);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./ERC1155Receiver.sol";
                /**
                 * @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;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./IERC1155Receiver.sol";
                import "./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);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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.
                        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. 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);
                }
                // SPDX-License-Identifier: MIT
                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;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721Enumerable} from "./imports/IERC721Enumerable.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair for an NFT that implements ERC721Enumerable
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairEnumerable is LSSVMPair {
                    /// @inheritdoc LSSVMPair
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal override {
                        // Send NFTs to recipient
                        // (we know NFT implements IERC721Enumerable so we just iterate)
                        uint256 lastIndex = _nft.balanceOf(address(this)) - 1;
                        for (uint256 i = 0; i < numNFTs; ) {
                            uint256 nftId = IERC721Enumerable(address(_nft))
                                .tokenOfOwnerByIndex(address(this), lastIndex);
                            _nft.safeTransferFrom(address(this), nftRecipient, nftId);
                            unchecked {
                                --lastIndex;
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal override {
                        // Send NFTs to recipient
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(address(this), nftRecipient, nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function getAllHeldIds() external view override returns (uint256[] memory) {
                        IERC721 _nft = nft();
                        uint256 numNFTs = _nft.balanceOf(address(this));
                        uint256[] memory ids = new uint256[](numNFTs);
                        for (uint256 i; i < numNFTs; ) {
                            ids[i] = IERC721Enumerable(address(_nft)).tokenOfOwnerByIndex(
                                address(this),
                                i
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        return ids;
                    }
                    function onERC721Received(
                        address,
                        address,
                        uint256,
                        bytes memory
                    ) public virtual returns (bytes4) {
                        return this.onERC721Received.selector;
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        override
                        onlyOwner
                    {
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            a.safeTransferFrom(address(this), msg.sender, nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                        emit NFTWithdrawal();
                    }
                }
                // SPDX-License-Identifier: MIT
                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 tokenId);
                    /**
                     * @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 7 of 8: LSSVMPairFactory
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {Ownable} from "./imports/Ownable.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {IERC165} from "./imports/IERC165.sol";
                import {IERC721Enumerable} from "./imports/IERC721Enumerable.sol";
                // @dev Solmate's ERC20 is used instead of OZ's ERC20 so we can use safeTransferLib for cheaper safeTransfers for
                // ETH and ERC20 tokens
                import {ERC20} from "./imports/ERC20.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {LSSVMPairETH} from "./LSSVMPairETH.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                import {LSSVMPairERC20} from "./LSSVMPairERC20.sol";
                import {LSSVMPairCloner} from "./lib/LSSVMPairCloner.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {LSSVMPairEnumerableETH} from "./LSSVMPairEnumerableETH.sol";
                import {LSSVMPairEnumerableERC20} from "./LSSVMPairEnumerableERC20.sol";
                import {LSSVMPairMissingEnumerableETH} from "./LSSVMPairMissingEnumerableETH.sol";
                import {LSSVMPairMissingEnumerableERC20} from "./LSSVMPairMissingEnumerableERC20.sol";
                contract LSSVMPairFactory is Ownable, ILSSVMPairFactoryLike {
                    using LSSVMPairCloner for address;
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    bytes4 private constant INTERFACE_ID_ERC721_ENUMERABLE =
                        type(IERC721Enumerable).interfaceId;
                    uint256 internal constant MAX_PROTOCOL_FEE = 0.10e18; // 10%, must <= 1 - MAX_FEE
                    LSSVMPairEnumerableETH public immutable enumerableETHTemplate;
                    LSSVMPairMissingEnumerableETH public immutable missingEnumerableETHTemplate;
                    LSSVMPairEnumerableERC20 public immutable enumerableERC20Template;
                    LSSVMPairMissingEnumerableERC20
                        public immutable missingEnumerableERC20Template;
                    address payable public override protocolFeeRecipient;
                    // Units are in base 1e18
                    uint256 public override protocolFeeMultiplier;
                    mapping(ICurve => bool) public bondingCurveAllowed;
                    mapping(address => bool) public override callAllowed;
                    struct RouterStatus {
                        bool allowed;
                        bool wasEverAllowed;
                    }
                    mapping(LSSVMRouter => RouterStatus) public override routerStatus;
                    event NewPair(address poolAddress);
                    event TokenDeposit(address poolAddress);
                    event NFTDeposit(address poolAddress);
                    event ProtocolFeeRecipientUpdate(address recipientAddress);
                    event ProtocolFeeMultiplierUpdate(uint256 newMultiplier);
                    event BondingCurveStatusUpdate(ICurve bondingCurve, bool isAllowed);
                    event CallTargetStatusUpdate(address target, bool isAllowed);
                    event RouterStatusUpdate(LSSVMRouter router, bool isAllowed);
                    constructor(
                        LSSVMPairEnumerableETH _enumerableETHTemplate,
                        LSSVMPairMissingEnumerableETH _missingEnumerableETHTemplate,
                        LSSVMPairEnumerableERC20 _enumerableERC20Template,
                        LSSVMPairMissingEnumerableERC20 _missingEnumerableERC20Template,
                        address payable _protocolFeeRecipient,
                        uint256 _protocolFeeMultiplier
                    ) {
                        enumerableETHTemplate = _enumerableETHTemplate;
                        missingEnumerableETHTemplate = _missingEnumerableETHTemplate;
                        enumerableERC20Template = _enumerableERC20Template;
                        missingEnumerableERC20Template = _missingEnumerableERC20Template;
                        protocolFeeRecipient = _protocolFeeRecipient;
                        require(_protocolFeeMultiplier <= MAX_PROTOCOL_FEE, "Fee too large");
                        protocolFeeMultiplier = _protocolFeeMultiplier;
                    }
                    /**
                     * External functions
                     */
                    /**
                        @notice Creates a pair contract using EIP-1167.
                        @param _nft The NFT contract of the collection the pair trades
                        @param _bondingCurve The bonding curve for the pair to price NFTs, must be whitelisted
                        @param _assetRecipient The address that will receive the assets traders give during trades.
                                              If set to address(0), assets will be sent to the pool address.
                                              Not available to TRADE pools. 
                        @param _poolType TOKEN, NFT, or TRADE
                        @param _delta The delta value used by the bonding curve. The meaning of delta depends
                        on the specific curve.
                        @param _fee The fee taken by the LP in each trade. Can only be non-zero if _poolType is Trade.
                        @param _spotPrice The initial selling spot price
                        @param _initialNFTIDs The list of IDs of NFTs to transfer from the sender to the pair
                        @return pair The new pair
                     */
                    function createPairETH(
                        IERC721 _nft,
                        ICurve _bondingCurve,
                        address payable _assetRecipient,
                        LSSVMPair.PoolType _poolType,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice,
                        uint256[] calldata _initialNFTIDs
                    ) external payable returns (LSSVMPairETH pair) {
                        require(
                            bondingCurveAllowed[_bondingCurve],
                            "Bonding curve not whitelisted"
                        );
                        // Check to see if the NFT supports Enumerable to determine which template to use
                        address template;
                        try
                            IERC165(address(_nft)).supportsInterface(
                                INTERFACE_ID_ERC721_ENUMERABLE
                            )
                        returns (bool isEnumerable) {
                            template = isEnumerable
                                ? address(enumerableETHTemplate)
                                : address(missingEnumerableETHTemplate);
                        } catch {
                            template = address(missingEnumerableETHTemplate);
                        }
                        pair = LSSVMPairETH(
                            payable(
                                template.cloneETHPair(
                                    this,
                                    _bondingCurve,
                                    _nft,
                                    uint8(_poolType)
                                )
                            )
                        );
                        _initializePairETH(
                            pair,
                            _nft,
                            _assetRecipient,
                            _delta,
                            _fee,
                            _spotPrice,
                            _initialNFTIDs
                        );
                        emit NewPair(address(pair));
                    }
                    /**
                        @notice Creates a pair contract using EIP-1167.
                        @param _nft The NFT contract of the collection the pair trades
                        @param _bondingCurve The bonding curve for the pair to price NFTs, must be whitelisted
                        @param _assetRecipient The address that will receive the assets traders give during trades.
                                                If set to address(0), assets will be sent to the pool address.
                                                Not available to TRADE pools.
                        @param _poolType TOKEN, NFT, or TRADE
                        @param _delta The delta value used by the bonding curve. The meaning of delta depends
                        on the specific curve.
                        @param _fee The fee taken by the LP in each trade. Can only be non-zero if _poolType is Trade.
                        @param _spotPrice The initial selling spot price, in ETH
                        @param _initialNFTIDs The list of IDs of NFTs to transfer from the sender to the pair
                        @param _initialTokenBalance The initial token balance sent from the sender to the new pair
                        @return pair The new pair
                     */
                    struct CreateERC20PairParams {
                        ERC20 token;
                        IERC721 nft;
                        ICurve bondingCurve;
                        address payable assetRecipient;
                        LSSVMPair.PoolType poolType;
                        uint128 delta;
                        uint96 fee;
                        uint128 spotPrice;
                        uint256[] initialNFTIDs;
                        uint256 initialTokenBalance;
                    }
                    function createPairERC20(CreateERC20PairParams calldata params)
                        external
                        returns (LSSVMPairERC20 pair)
                    {
                        require(
                            bondingCurveAllowed[params.bondingCurve],
                            "Bonding curve not whitelisted"
                        );
                        // Check to see if the NFT supports Enumerable to determine which template to use
                        address template;
                        try
                            IERC165(address(params.nft)).supportsInterface(
                                INTERFACE_ID_ERC721_ENUMERABLE
                            )
                        returns (bool isEnumerable) {
                            template = isEnumerable
                                ? address(enumerableERC20Template)
                                : address(missingEnumerableERC20Template);
                        } catch {
                            template = address(missingEnumerableERC20Template);
                        }
                        pair = LSSVMPairERC20(
                            payable(
                                template.cloneERC20Pair(
                                    this,
                                    params.bondingCurve,
                                    params.nft,
                                    uint8(params.poolType),
                                    params.token
                                )
                            )
                        );
                        _initializePairERC20(
                            pair,
                            params.token,
                            params.nft,
                            params.assetRecipient,
                            params.delta,
                            params.fee,
                            params.spotPrice,
                            params.initialNFTIDs,
                            params.initialTokenBalance
                        );
                        emit NewPair(address(pair));
                    }
                    /**
                        @notice Checks if an address is a LSSVMPair. Uses the fact that the pairs are EIP-1167 minimal proxies.
                        @param potentialPair The address to check
                        @param variant The pair variant (NFT is enumerable or not, pair uses ETH or ERC20)
                        @return True if the address is the specified pair variant, false otherwise
                     */
                    function isPair(address potentialPair, PairVariant variant)
                        public
                        view
                        override
                        returns (bool)
                    {
                        if (variant == PairVariant.ENUMERABLE_ERC20) {
                            return
                                LSSVMPairCloner.isERC20PairClone(
                                    address(this),
                                    address(enumerableERC20Template),
                                    potentialPair
                                );
                        } else if (variant == PairVariant.MISSING_ENUMERABLE_ERC20) {
                            return
                                LSSVMPairCloner.isERC20PairClone(
                                    address(this),
                                    address(missingEnumerableERC20Template),
                                    potentialPair
                                );
                        } else if (variant == PairVariant.ENUMERABLE_ETH) {
                            return
                                LSSVMPairCloner.isETHPairClone(
                                    address(this),
                                    address(enumerableETHTemplate),
                                    potentialPair
                                );
                        } else if (variant == PairVariant.MISSING_ENUMERABLE_ETH) {
                            return
                                LSSVMPairCloner.isETHPairClone(
                                    address(this),
                                    address(missingEnumerableETHTemplate),
                                    potentialPair
                                );
                        } else {
                            // invalid input
                            return false;
                        }
                    }
                    /**
                        @notice Allows receiving ETH in order to receive protocol fees
                     */
                    receive() external payable {}
                    /**
                     * Admin functions
                     */
                    /**
                        @notice Withdraws the ETH balance to the protocol fee recipient.
                        Only callable by the owner.
                     */
                    function withdrawETHProtocolFees() external onlyOwner {
                        protocolFeeRecipient.safeTransferETH(address(this).balance);
                    }
                    /**
                        @notice Withdraws ERC20 tokens to the protocol fee recipient. Only callable by the owner.
                        @param token The token to transfer
                        @param amount The amount of tokens to transfer
                     */
                    function withdrawERC20ProtocolFees(ERC20 token, uint256 amount)
                        external
                        onlyOwner
                    {
                        token.safeTransfer(protocolFeeRecipient, amount);
                    }
                    /**
                        @notice Changes the protocol fee recipient address. Only callable by the owner.
                        @param _protocolFeeRecipient The new fee recipient
                     */
                    function changeProtocolFeeRecipient(address payable _protocolFeeRecipient)
                        external
                        onlyOwner
                    {
                        require(_protocolFeeRecipient != address(0), "0 address");
                        protocolFeeRecipient = _protocolFeeRecipient;
                        emit ProtocolFeeRecipientUpdate(_protocolFeeRecipient);
                    }
                    /**
                        @notice Changes the protocol fee multiplier. Only callable by the owner.
                        @param _protocolFeeMultiplier The new fee multiplier, 18 decimals
                     */
                    function changeProtocolFeeMultiplier(uint256 _protocolFeeMultiplier)
                        external
                        onlyOwner
                    {
                        require(_protocolFeeMultiplier <= MAX_PROTOCOL_FEE, "Fee too large");
                        protocolFeeMultiplier = _protocolFeeMultiplier;
                        emit ProtocolFeeMultiplierUpdate(_protocolFeeMultiplier);
                    }
                    /**
                        @notice Sets the whitelist status of a bonding curve contract. Only callable by the owner.
                        @param bondingCurve The bonding curve contract
                        @param isAllowed True to whitelist, false to remove from whitelist
                     */
                    function setBondingCurveAllowed(ICurve bondingCurve, bool isAllowed)
                        external
                        onlyOwner
                    {
                        bondingCurveAllowed[bondingCurve] = isAllowed;
                        emit BondingCurveStatusUpdate(bondingCurve, isAllowed);
                    }
                    /**
                        @notice Sets the whitelist status of a contract to be called arbitrarily by a pair.
                        Only callable by the owner.
                        @param target The target contract
                        @param isAllowed True to whitelist, false to remove from whitelist
                     */
                    function setCallAllowed(address payable target, bool isAllowed)
                        external
                        onlyOwner
                    {
                        // ensure target is not / was not ever a router
                        if (isAllowed) {
                            require(
                                !routerStatus[LSSVMRouter(target)].wasEverAllowed,
                                "Can't call router"
                            );
                        }
                        callAllowed[target] = isAllowed;
                        emit CallTargetStatusUpdate(target, isAllowed);
                    }
                    /**
                        @notice Updates the router whitelist. Only callable by the owner.
                        @param _router The router
                        @param isAllowed True to whitelist, false to remove from whitelist
                     */
                    function setRouterAllowed(LSSVMRouter _router, bool isAllowed)
                        external
                        onlyOwner
                    {
                        // ensure target is not arbitrarily callable by pairs
                        if (isAllowed) {
                            require(!callAllowed[address(_router)], "Can't call router");
                        }
                        routerStatus[_router] = RouterStatus({
                            allowed: isAllowed,
                            wasEverAllowed: true
                        });
                        emit RouterStatusUpdate(_router, isAllowed);
                    }
                    /**
                     * Internal functions
                     */
                    function _initializePairETH(
                        LSSVMPairETH _pair,
                        IERC721 _nft,
                        address payable _assetRecipient,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice,
                        uint256[] calldata _initialNFTIDs
                    ) internal {
                        // initialize pair
                        _pair.initialize(msg.sender, _assetRecipient, _delta, _fee, _spotPrice);
                        // transfer initial ETH to pair
                        payable(address(_pair)).safeTransferETH(msg.value);
                        // transfer initial NFTs from sender to pair
                        uint256 numNFTs = _initialNFTIDs.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(
                                msg.sender,
                                address(_pair),
                                _initialNFTIDs[i]
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    function _initializePairERC20(
                        LSSVMPairERC20 _pair,
                        ERC20 _token,
                        IERC721 _nft,
                        address payable _assetRecipient,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice,
                        uint256[] calldata _initialNFTIDs,
                        uint256 _initialTokenBalance
                    ) internal {
                        // initialize pair
                        _pair.initialize(msg.sender, _assetRecipient, _delta, _fee, _spotPrice);
                        // transfer initial tokens to pair
                        _token.safeTransferFrom(
                            msg.sender,
                            address(_pair),
                            _initialTokenBalance
                        );
                        // transfer initial NFTs from sender to pair
                        uint256 numNFTs = _initialNFTIDs.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(
                                msg.sender,
                                address(_pair),
                                _initialNFTIDs[i]
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /** 
                      @dev Used to deposit NFTs into a pair after creation and emit an event for indexing (if recipient is indeed a pair)
                    */
                    function depositNFTs(
                        IERC721 _nft,
                        uint256[] calldata ids,
                        address recipient
                    ) external {
                        // transfer NFTs from caller to recipient
                        uint256 numNFTs = ids.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(msg.sender, recipient, ids[i]);
                            unchecked {
                                ++i;
                            }
                        }
                        if (
                            isPair(recipient, PairVariant.ENUMERABLE_ERC20) ||
                            isPair(recipient, PairVariant.ENUMERABLE_ETH) ||
                            isPair(recipient, PairVariant.MISSING_ENUMERABLE_ERC20) ||
                            isPair(recipient, PairVariant.MISSING_ENUMERABLE_ETH)
                        ) {
                            emit NFTDeposit(recipient);
                        }
                    }
                    /**
                      @dev Used to deposit ERC20s into a pair after creation and emit an event for indexing (if recipient is indeed an ERC20 pair and the token matches)
                     */
                    function depositERC20(
                        ERC20 token,
                        address recipient,
                        uint256 amount
                    ) external {
                        token.safeTransferFrom(msg.sender, recipient, amount);
                        if (
                            isPair(recipient, PairVariant.ENUMERABLE_ERC20) ||
                            isPair(recipient, PairVariant.MISSING_ENUMERABLE_ERC20)
                        ) {
                            if (token == LSSVMPairERC20(recipient).token()) {
                                emit TokenDeposit(recipient);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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() {
                        _setOwner(_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 {
                        _setOwner(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"
                        );
                        _setOwner(newOwner);
                    }
                    function _setOwner(address newOwner) private {
                        address oldOwner = _owner;
                        _owner = newOwner;
                        emit OwnershipTransferred(oldOwner, newOwner);
                    }
                }
                // SPDX-License-Identifier: MIT
                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;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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`, 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 Returns the account approved for `tokenId` token.
                     *
                     * Requirements:
                     *
                     * - `tokenId` must exist.
                     */
                    function getApproved(uint256 tokenId)
                        external
                        view
                        returns (address operator);
                    /**
                     * @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 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);
                    /**
                     * @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;
                }
                // SPDX-License-Identifier: MIT
                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);
                }
                // SPDX-License-Identifier: MIT
                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 tokenId);
                    /**
                     * @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);
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                abstract contract ERC20 {
                    /*///////////////////////////////////////////////////////////////
                                                  EVENTS
                    //////////////////////////////////////////////////////////////*/
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 amount
                    );
                    /*///////////////////////////////////////////////////////////////
                                             METADATA STORAGE
                    //////////////////////////////////////////////////////////////*/
                    string public name;
                    string public symbol;
                    uint8 public immutable decimals;
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    uint256 public totalSupply;
                    mapping(address => uint256) public balanceOf;
                    mapping(address => mapping(address => uint256)) public allowance;
                    /*///////////////////////////////////////////////////////////////
                                           EIP-2612 STORAGE
                    //////////////////////////////////////////////////////////////*/
                    bytes32 public constant PERMIT_TYPEHASH =
                        keccak256(
                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                        );
                    uint256 internal immutable INITIAL_CHAIN_ID;
                    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                    mapping(address => uint256) public nonces;
                    /*///////////////////////////////////////////////////////////////
                                               CONSTRUCTOR
                    //////////////////////////////////////////////////////////////*/
                    constructor(
                        string memory _name,
                        string memory _symbol,
                        uint8 _decimals
                    ) {
                        name = _name;
                        symbol = _symbol;
                        decimals = _decimals;
                        INITIAL_CHAIN_ID = block.chainid;
                        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                    }
                    /*///////////////////////////////////////////////////////////////
                                              ERC20 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function approve(address spender, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        allowance[msg.sender][spender] = amount;
                        emit Approval(msg.sender, spender, amount);
                        return true;
                    }
                    function transfer(address to, uint256 amount)
                        public
                        virtual
                        returns (bool)
                    {
                        balanceOf[msg.sender] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(msg.sender, to, amount);
                        return true;
                    }
                    function transferFrom(
                        address from,
                        address to,
                        uint256 amount
                    ) public virtual returns (bool) {
                        if (allowance[from][msg.sender] != type(uint256).max) {
                            allowance[from][msg.sender] -= amount;
                        }
                        balanceOf[from] -= amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        return true;
                    }
                    /*///////////////////////////////////////////////////////////////
                                              EIP-2612 LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public virtual {
                        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                        // Unchecked because the only math done is incrementing
                        // the owner's nonce which cannot realistically overflow.
                        unchecked {
                            bytes32 digest = keccak256(
                                abi.encodePacked(
                                    "\\x19\\x01",
                                    DOMAIN_SEPARATOR(),
                                    keccak256(
                                        abi.encode(
                                            PERMIT_TYPEHASH,
                                            owner,
                                            spender,
                                            value,
                                            nonces[owner]++,
                                            deadline
                                        )
                                    )
                                )
                            );
                            address recoveredAddress = ecrecover(digest, v, r, s);
                            require(
                                recoveredAddress != address(0) && recoveredAddress == owner,
                                "INVALID_PERMIT_SIGNATURE"
                            );
                            allowance[recoveredAddress][spender] = value;
                        }
                        emit Approval(owner, spender, value);
                    }
                    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                        return
                            block.chainid == INITIAL_CHAIN_ID
                                ? INITIAL_DOMAIN_SEPARATOR
                                : computeDomainSeparator();
                    }
                    function computeDomainSeparator() internal view virtual returns (bytes32) {
                        return
                            keccak256(
                                abi.encode(
                                    keccak256(
                                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                                    ),
                                    keccak256(bytes(name)),
                                    keccak256(bytes("1")),
                                    block.chainid,
                                    address(this)
                                )
                            );
                    }
                    /*///////////////////////////////////////////////////////////////
                                       INTERNAL MINT/BURN LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function _mint(address to, uint256 amount) internal virtual {
                        totalSupply += amount;
                        // Cannot overflow because the sum of all user
                        // balances can't exceed the max uint256 value.
                        unchecked {
                            balanceOf[to] += amount;
                        }
                        emit Transfer(address(0), to, amount);
                    }
                    function _burn(address from, uint256 amount) internal virtual {
                        balanceOf[from] -= amount;
                        // Cannot underflow because a user's balance
                        // will never be larger than the total supply.
                        unchecked {
                            totalSupply -= amount;
                        }
                        emit Transfer(from, address(0), amount);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity >=0.8.0;
                import {ERC20} from "./ERC20.sol";
                /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
                /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
                library SafeTransferLib {
                    /*///////////////////////////////////////////////////////////////
                                            ETH OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferETH(address to, uint256 amount) internal {
                        bool callStatus;
                        assembly {
                            // Transfer the ETH and store if it succeeded or not.
                            callStatus := call(gas(), to, amount, 0, 0, 0, 0)
                        }
                        require(callStatus, "ETH_TRANSFER_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                           ERC20 OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                    function safeTransferFrom(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x23b872dd00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(from, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "from" argument.
                            mstore(
                                add(freeMemoryPointer, 36),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 100 because the calldata length is 4 + 32 * 3.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FROM_FAILED"
                        );
                    }
                    function safeTransfer(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0xa9059cbb00000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(
                            didLastOptionalReturnCallSucceed(callStatus),
                            "TRANSFER_FAILED"
                        );
                    }
                    function safeApprove(
                        ERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        bool callStatus;
                        assembly {
                            // Get a pointer to some free memory.
                            let freeMemoryPointer := mload(0x40)
                            // Write the abi-encoded calldata to memory piece by piece:
                            mstore(
                                freeMemoryPointer,
                                0x095ea7b300000000000000000000000000000000000000000000000000000000
                            ) // Begin with the function selector.
                            mstore(
                                add(freeMemoryPointer, 4),
                                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
                            ) // Mask and append the "to" argument.
                            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
                            // Call the token and store if it succeeded or not.
                            // We use 68 because the calldata length is 4 + 32 * 2.
                            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
                        }
                        require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
                    }
                    /*///////////////////////////////////////////////////////////////
                                         INTERNAL HELPER LOGIC
                    //////////////////////////////////////////////////////////////*/
                    function didLastOptionalReturnCallSucceed(bool callStatus)
                        private
                        pure
                        returns (bool success)
                    {
                        assembly {
                            // Get how many bytes the call returned.
                            let returnDataSize := returndatasize()
                            // If the call reverted:
                            if iszero(callStatus) {
                                // Copy the revert message into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Revert with the same message.
                                revert(0, returnDataSize)
                            }
                            switch returnDataSize
                            case 32 {
                                // Copy the return data into memory.
                                returndatacopy(0, 0, returnDataSize)
                                // Set success to whether it returned true.
                                success := iszero(iszero(mload(0)))
                            }
                            case 0 {
                                // There was no return data.
                                success := 1
                            }
                            default {
                                // It returned some malformed input.
                                success := 0
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {OwnableWithTransferCallback} from "./lib/OwnableWithTransferCallback.sol";
                import {ReentrancyGuard} from "./lib/ReentrancyGuard.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                import {IERC1155} from "./imports/IERC1155.sol";
                import {ERC1155Holder} from "./imports/ERC1155Holder.sol";
                /// @title The base contract for an NFT/TOKEN AMM pair
                /// @author boredGenius and 0xmons
                /// @notice This implements the core swap logic from NFT to TOKEN
                abstract contract LSSVMPair is
                    OwnableWithTransferCallback,
                    ReentrancyGuard,
                    ERC1155Holder
                {
                    enum PoolType {
                        TOKEN,
                        NFT,
                        TRADE
                    }
                    // 90%, must <= 1 - MAX_PROTOCOL_FEE (set in LSSVMPairFactory)
                    uint256 internal constant MAX_FEE = 0.90e18;
                    // The current price of the NFT
                    // @dev This is generally used to mean the immediate sell price for the next marginal NFT.
                    // However, this should NOT be assumed, as future bonding curves may use spotPrice in different ways.
                    // Use getBuyNFTQuote and getSellNFTQuote for accurate pricing info.
                    uint128 public spotPrice;
                    // The parameter for the pair's bonding curve.
                    // Units and meaning are bonding curve dependent.
                    uint128 public delta;
                    // The spread between buy and sell prices, set to be a multiplier we apply to the buy price
                    // Fee is only relevant for TRADE pools
                    // Units are in base 1e18
                    uint96 public fee;
                    // If set to 0, NFTs/tokens sent by traders during trades will be sent to the pair.
                    // Otherwise, assets will be sent to the set address. Not available for TRADE pools.
                    address payable public assetRecipient;
                    // Events
                    event SwapNFTInPair();
                    event SwapNFTOutPair();
                    event SpotPriceUpdate(uint128 newSpotPrice);
                    event TokenDeposit(uint256 amount);
                    event TokenWithdrawal(uint256 amount);
                    event NFTWithdrawal();
                    event DeltaUpdate(uint128 newDelta);
                    event FeeUpdate(uint96 newFee);
                    event AssetRecipientChange(address a);
                    // Parameterized Errors
                    error BondingCurveError(CurveErrorCodes.Error error);
                    /**
                      @notice Called during pair creation to set initial parameters
                      @dev Only called once by factory to initialize.
                      We verify this by making sure that the current owner is address(0). 
                      The Ownable library we use disallows setting the owner to be address(0), so this condition
                      should only be valid before the first initialize call. 
                      @param _owner The owner of the pair
                      @param _assetRecipient The address that will receive the TOKEN or NFT sent to this pair during swaps. NOTE: If set to address(0), they will go to the pair itself.
                      @param _delta The initial delta of the bonding curve
                      @param _fee The initial % fee taken, if this is a trade pair 
                      @param _spotPrice The initial price to sell an asset into the pair
                     */
                    function initialize(
                        address _owner,
                        address payable _assetRecipient,
                        uint128 _delta,
                        uint96 _fee,
                        uint128 _spotPrice
                    ) external payable {
                        require(owner() == address(0), "Initialized");
                        __Ownable_init(_owner);
                        __ReentrancyGuard_init();
                        ICurve _bondingCurve = bondingCurve();
                        PoolType _poolType = poolType();
                        if ((_poolType == PoolType.TOKEN) || (_poolType == PoolType.NFT)) {
                            require(_fee == 0, "Only Trade Pools can have nonzero fee");
                            assetRecipient = _assetRecipient;
                        } else if (_poolType == PoolType.TRADE) {
                            require(_fee < MAX_FEE, "Trade fee must be less than 90%");
                            require(
                                _assetRecipient == address(0),
                                "Trade pools can't set asset recipient"
                            );
                            fee = _fee;
                        }
                        require(_bondingCurve.validateDelta(_delta), "Invalid delta for curve");
                        require(
                            _bondingCurve.validateSpotPrice(_spotPrice),
                            "Invalid new spot price for curve"
                        );
                        delta = _delta;
                        spotPrice = _spotPrice;
                    }
                    /**
                     * External state-changing functions
                     */
                    /**
                        @notice Sends token to the pair in exchange for any `numNFTs` NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo.
                        This swap function is meant for users who are ID agnostic
                        @param numNFTs The number of NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForAnyNFTs(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        IERC721 _nft = nft();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(
                                (numNFTs > 0) && (numNFTs <= _nft.balanceOf(address(this))),
                                "Ask for > 0 and <= balanceOf NFTs"
                            );
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            numNFTs,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendAnyNFTsToRecipient(_nft, nftRecipient, numNFTs);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends token to the pair in exchange for a specific set of NFTs
                        @dev To compute the amount of token to send, call bondingCurve.getBuyInfo
                        This swap is meant for users who want specific IDs. Also higher chance of
                        reverting if some of the specified IDs leave the pool before the swap goes through.
                        @param nftIds The list of IDs of the NFTs to purchase
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param nftRecipient The recipient of the NFTs
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return inputAmount The amount of token used for purchase
                     */
                    function swapTokenForSpecificNFTs(
                        uint256[] calldata nftIds,
                        uint256 maxExpectedTokenInput,
                        address nftRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external payable virtual nonReentrant returns (uint256 inputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.NFT || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require((nftIds.length > 0), "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, inputAmount) = _calculateBuyInfoAndUpdatePoolParams(
                            nftIds.length,
                            maxExpectedTokenInput,
                            _bondingCurve,
                            _factory
                        );
                        _pullTokenInputAndPayProtocolFee(
                            inputAmount,
                            isRouter,
                            routerCaller,
                            _factory,
                            protocolFee
                        );
                        _sendSpecificNFTsToRecipient(nft(), nftRecipient, nftIds);
                        _refundTokenToSender(inputAmount);
                        emit SwapNFTOutPair();
                    }
                    /**
                        @notice Sends a set of NFTs to the pair in exchange for token
                        @dev To compute the amount of token to that will be received, call bondingCurve.getSellInfo.
                        @param nftIds The list of IDs of the NFTs to sell to the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param tokenRecipient The recipient of the token output
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                        @return outputAmount The amount of token received
                     */
                    function swapNFTsForToken(
                        uint256[] calldata nftIds,
                        uint256 minExpectedTokenOutput,
                        address payable tokenRecipient,
                        bool isRouter,
                        address routerCaller
                    ) external virtual nonReentrant returns (uint256 outputAmount) {
                        // Store locally to remove extra calls
                        ILSSVMPairFactoryLike _factory = factory();
                        ICurve _bondingCurve = bondingCurve();
                        // Input validation
                        {
                            PoolType _poolType = poolType();
                            require(
                                _poolType == PoolType.TOKEN || _poolType == PoolType.TRADE,
                                "Wrong Pool type"
                            );
                            require(nftIds.length > 0, "Must ask for > 0 NFTs");
                        }
                        // Call bonding curve for pricing information
                        uint256 protocolFee;
                        (protocolFee, outputAmount) = _calculateSellInfoAndUpdatePoolParams(
                            nftIds.length,
                            minExpectedTokenOutput,
                            _bondingCurve,
                            _factory
                        );
                        _sendTokenOutput(tokenRecipient, outputAmount);
                        _payProtocolFeeFromPair(_factory, protocolFee);
                        _takeNFTsFromSender(nft(), nftIds, _factory, isRouter, routerCaller);
                        emit SwapNFTInPair();
                    }
                    /**
                     * View functions
                     */
                    /**
                        @dev Used as read function to query the bonding curve for buy pricing info
                        @param numNFTs The number of NFTs to buy from the pair
                     */
                    function getBuyNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 inputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = bondingCurve().getBuyInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @dev Used as read function to query the bonding curve for sell pricing info
                        @param numNFTs The number of NFTs to sell to the pair
                     */
                    function getSellNFTQuote(uint256 numNFTs)
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint256 newSpotPrice,
                            uint256 newDelta,
                            uint256 outputAmount,
                            uint256 protocolFee
                        )
                    {
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = bondingCurve().getSellInfo(
                            spotPrice,
                            delta,
                            numNFTs,
                            fee,
                            factory().protocolFeeMultiplier()
                        );
                    }
                    /**
                        @notice Returns all NFT IDs held by the pool
                     */
                    function getAllHeldIds() external view virtual returns (uint256[] memory);
                    /**
                        @notice Returns the pair's variant (NFT is enumerable or not, pair uses ETH or ERC20)
                     */
                    function pairVariant()
                        public
                        pure
                        virtual
                        returns (ILSSVMPairFactoryLike.PairVariant);
                    function factory() public pure returns (ILSSVMPairFactoryLike _factory) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _factory := shr(
                                0x60,
                                calldataload(sub(calldatasize(), paramsLength))
                            )
                        }
                    }
                    /**
                        @notice Returns the type of bonding curve that parameterizes the pair
                     */
                    function bondingCurve() public pure returns (ICurve _bondingCurve) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _bondingCurve := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 20))
                            )
                        }
                    }
                    /**
                        @notice Returns the NFT collection that parameterizes the pair
                     */
                    function nft() public pure returns (IERC721 _nft) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _nft := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 40))
                            )
                        }
                    }
                    /**
                        @notice Returns the pair's type (TOKEN/NFT/TRADE)
                     */
                    function poolType() public pure returns (PoolType _poolType) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _poolType := shr(
                                0xf8,
                                calldataload(add(sub(calldatasize(), paramsLength), 60))
                            )
                        }
                    }
                    /**
                        @notice Returns the address that assets that receives assets when a swap is done with this pair
                        Can be set to another address by the owner, if set to address(0), defaults to the pair's own address
                     */
                    function getAssetRecipient()
                        public
                        view
                        returns (address payable _assetRecipient)
                    {
                        // If it's a TRADE pool, we know the recipient is 0 (TRADE pools can't set asset recipients)
                        // so just return address(this)
                        if (poolType() == PoolType.TRADE) {
                            return payable(address(this));
                        }
                        // Otherwise, we return the recipient if it's been set
                        // or replace it with address(this) if it's 0
                        _assetRecipient = assetRecipient;
                        if (_assetRecipient == address(0)) {
                            // Tokens will be transferred to address(this)
                            _assetRecipient = payable(address(this));
                        }
                    }
                    /**
                     * Internal functions
                     */
                    /**
                        @notice Calculates the amount needed to be sent into the pair for a buy and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to purchase from the pair
                        @param maxExpectedTokenInput The maximum acceptable cost from the sender. If the actual
                        amount is greater than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return inputAmount The amount of tokens total tokens receive
                     */
                    function _calculateBuyInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 maxExpectedTokenInput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 inputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            inputAmount,
                            protocolFee
                        ) = _bondingCurve.getBuyInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if input is more than expected
                        require(inputAmount <= maxExpectedTokenInput, "In too many tokens");
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Calculates the amount needed to be sent by the pair for a sell and adjusts spot price or delta if necessary
                        @param numNFTs The amount of NFTs to send to the the pair
                        @param minExpectedTokenOutput The minimum acceptable token received by the sender. If the actual
                        amount is less than this value, the transaction will be reverted.
                        @param protocolFee The percentage of protocol fee to be taken, as a percentage
                        @return protocolFee The amount of tokens to send as protocol fee
                        @return outputAmount The amount of tokens total tokens receive
                     */
                    function _calculateSellInfoAndUpdatePoolParams(
                        uint256 numNFTs,
                        uint256 minExpectedTokenOutput,
                        ICurve _bondingCurve,
                        ILSSVMPairFactoryLike _factory
                    ) internal returns (uint256 protocolFee, uint256 outputAmount) {
                        CurveErrorCodes.Error error;
                        // Save on 2 SLOADs by caching
                        uint128 currentSpotPrice = spotPrice;
                        uint128 newSpotPrice;
                        uint128 currentDelta = delta;
                        uint128 newDelta;
                        (
                            error,
                            newSpotPrice,
                            newDelta,
                            outputAmount,
                            protocolFee
                        ) = _bondingCurve.getSellInfo(
                            currentSpotPrice,
                            currentDelta,
                            numNFTs,
                            fee,
                            _factory.protocolFeeMultiplier()
                        );
                        // Revert if bonding curve had an error
                        if (error != CurveErrorCodes.Error.OK) {
                            revert BondingCurveError(error);
                        }
                        // Revert if output is too little
                        require(
                            outputAmount >= minExpectedTokenOutput,
                            "Out too little tokens"
                        );
                        // Consolidate writes to save gas
                        if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) {
                            spotPrice = newSpotPrice;
                            delta = newDelta;
                        }
                        // Emit spot price update if it has been updated
                        if (currentSpotPrice != newSpotPrice) {
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                        // Emit delta update if it has been updated
                        if (currentDelta != newDelta) {
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Pulls the token input of a trade from the trader and pays the protocol fee.
                        @param inputAmount The amount of tokens to be sent
                        @param isRouter Whether or not the caller is LSSVMRouter
                        @param routerCaller If called from LSSVMRouter, store the original caller
                        @param _factory The LSSVMPairFactory which stores LSSVMRouter allowlist info
                        @param protocolFee The protocol fee to be paid
                     */
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool isRouter,
                        address routerCaller,
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends excess tokens back to the caller (if applicable)
                        @dev We send ETH back to the caller even when called from LSSVMRouter because we do an aggregate slippage check for certain bulk swaps. (Instead of sending directly back to the router caller) 
                        Excess ETH sent for one swap can then be used to help pay for the next swap.
                     */
                    function _refundTokenToSender(uint256 inputAmount) internal virtual;
                    /**
                        @notice Sends protocol fee (if it exists) back to the LSSVMPairFactory from the pair
                     */
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal virtual;
                    /**
                        @notice Sends tokens to a recipient
                        @param tokenRecipient The address receiving the tokens
                        @param outputAmount The amount of tokens to send
                     */
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal virtual;
                    /**
                        @notice Sends some number of NFTs to a recipient address, ID agnostic
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param numNFTs The number of NFTs to send  
                     */
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal virtual;
                    /**
                        @notice Sends specific NFTs to a recipient address
                        @dev Even though we specify the NFT address here, this internal function is only 
                        used to send NFTs associated with this specific pool.
                        @param _nft The address of the NFT to send
                        @param nftRecipient The receiving address for the NFTs
                        @param nftIds The specific IDs of NFTs to send  
                     */
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal virtual;
                    /**
                        @notice Takes NFTs from the caller and sends them into the pair's asset recipient
                        @dev This is used by the LSSVMPair's swapNFTForToken function. 
                        @param _nft The NFT collection to take from
                        @param nftIds The specific NFT IDs to take
                        @param isRouter True if calling from LSSVMRouter, false otherwise. Not used for
                        ETH pairs.
                        @param routerCaller If isRouter is true, ERC20 tokens will be transferred from this address. Not used for
                        ETH pairs.
                     */
                    function _takeNFTsFromSender(
                        IERC721 _nft,
                        uint256[] calldata nftIds,
                        ILSSVMPairFactoryLike _factory,
                        bool isRouter,
                        address routerCaller
                    ) internal virtual {
                        {
                            address _assetRecipient = getAssetRecipient();
                            uint256 numNFTs = nftIds.length;
                            if (isRouter) {
                                // Verify if router is allowed
                                LSSVMRouter router = LSSVMRouter(payable(msg.sender));
                                (bool routerAllowed, ) = _factory.routerStatus(router);
                                require(routerAllowed, "Not router");
                                // Call router to pull NFTs
                                // If more than 1 NFT is being transfered, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection
                                if (numNFTs > 1) {
                                    uint256 beforeBalance = _nft.balanceOf(_assetRecipient);
                                    for (uint256 i = 0; i < numNFTs; ) {
                                        router.pairTransferNFTFrom(
                                            _nft,
                                            routerCaller,
                                            _assetRecipient,
                                            nftIds[i],
                                            pairVariant()
                                        );
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    require(
                                        (_nft.balanceOf(_assetRecipient) - beforeBalance) ==
                                            numNFTs,
                                        "NFTs not transferred"
                                    );
                                } else {
                                    router.pairTransferNFTFrom(
                                        _nft,
                                        routerCaller,
                                        _assetRecipient,
                                        nftIds[0],
                                        pairVariant()
                                    );
                                    require(
                                        _nft.ownerOf(nftIds[0]) == _assetRecipient,
                                        "NFT not transferred"
                                    );
                                }
                            } else {
                                // Pull NFTs directly from sender
                                for (uint256 i; i < numNFTs; ) {
                                    _nft.safeTransferFrom(
                                        msg.sender,
                                        _assetRecipient,
                                        nftIds[i]
                                    );
                                    unchecked {
                                        ++i;
                                    }
                                }
                            }
                        }
                    }
                    /**
                        @dev Used internally to grab pair parameters from calldata, see LSSVMPairCloner for technical details
                     */
                    function _immutableParamsLength() internal pure virtual returns (uint256);
                    /**
                     * Owner functions
                     */
                    /**
                        @notice Rescues a specified set of NFTs owned by the pair to the owner address.
                        @dev If the NFT is the pair's collection, we also remove it from the id tracking.
                        @param a The address of the NFT to transfer
                        @param nftIds The list of IDs of the NFTs to send to the owner
                     */
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        virtual;
                    /**
                        @notice Rescues ERC20 tokens from the pair to the owner. Only callable by the owner.
                        @param a The address of the token to transfer
                        @param amount The amount of tokens to send to the owner
                     */
                    function withdrawERC20(ERC20 a, uint256 amount) external virtual;
                    /**
                        @notice Rescues ERC1155 tokens from the pair to the owner. Only callable by the owner.
                        @param a The NFT to transfer
                        @param ids The NFT ids to transfer
                        @param amounts The amounts of each id to transfer
                     */
                    function withdrawERC1155(
                        IERC1155 a,
                        uint256[] calldata ids,
                        uint256[] calldata amounts
                    ) external onlyOwner {
                        a.safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
                    }
                    /**
                        @notice Updates the selling spot price. Only callable by the owner.
                        @param newSpotPrice The new selling spot price value, in Token
                     */
                    function changeSpotPrice(uint128 newSpotPrice) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateSpotPrice(newSpotPrice),
                            "Invalid new spot price for curve"
                        );
                        if (spotPrice != newSpotPrice) {
                            spotPrice = newSpotPrice;
                            emit SpotPriceUpdate(newSpotPrice);
                        }
                    }
                    /**
                        @notice Updates the delta parameter. Only callable by the owner.
                        @param newDelta The new delta parameter
                     */
                    function changeDelta(uint128 newDelta) external onlyOwner {
                        ICurve _bondingCurve = bondingCurve();
                        require(
                            _bondingCurve.validateDelta(newDelta),
                            "Invalid delta for curve"
                        );
                        if (delta != newDelta) {
                            delta = newDelta;
                            emit DeltaUpdate(newDelta);
                        }
                    }
                    /**
                        @notice Updates the fee taken by the LP. Only callable by the owner.
                        Only callable if the pool is a Trade pool. Reverts if the fee is >=
                        MAX_FEE.
                        @param newFee The new LP fee percentage, 18 decimals
                     */
                    function changeFee(uint96 newFee) external onlyOwner {
                        PoolType _poolType = poolType();
                        require(_poolType == PoolType.TRADE, "Only for Trade pools");
                        require(newFee < MAX_FEE, "Trade fee must be less than 90%");
                        if (fee != newFee) {
                            fee = newFee;
                            emit FeeUpdate(newFee);
                        }
                    }
                    /**
                        @notice Changes the address that will receive assets received from
                        trades. Only callable by the owner.
                        @param newRecipient The new asset recipient
                     */
                    function changeAssetRecipient(address payable newRecipient)
                        external
                        onlyOwner
                    {
                        PoolType _poolType = poolType();
                        require(_poolType != PoolType.TRADE, "Not for Trade pools");
                        if (assetRecipient != newRecipient) {
                            assetRecipient = newRecipient;
                            emit AssetRecipientChange(newRecipient);
                        }
                    }
                    /**
                        @notice Allows the pair to make arbitrary external calls to contracts
                        whitelisted by the protocol. Only callable by the owner.
                        @param target The contract to call
                        @param data The calldata to pass to the contract
                     */
                    function call(address payable target, bytes calldata data)
                        external
                        onlyOwner
                    {
                        ILSSVMPairFactoryLike _factory = factory();
                        require(_factory.callAllowed(target), "Target must be whitelisted");
                        (bool result, ) = target.call{value: 0}(data);
                        require(result, "Call failed");
                    }
                    /**
                        @notice Allows owner to batch multiple calls, forked from: https://github.com/boringcrypto/BoringSolidity/blob/master/contracts/BoringBatchable.sol 
                        @dev Intended for withdrawing/altering pool pricing in one tx, only callable by owner, cannot change owner
                        @param calls The calldata for each call to make
                        @param revertOnFail Whether or not to revert the entire tx if any of the calls fail
                     */
                    function multicall(bytes[] calldata calls, bool revertOnFail)
                        external
                        onlyOwner
                    {
                        for (uint256 i; i < calls.length; ) {
                            (bool success, bytes memory result) = address(this).delegatecall(
                                calls[i]
                            );
                            if (!success && revertOnFail) {
                                revert(_getRevertMsg(result));
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Prevent multicall from malicious frontend sneaking in ownership change
                        require(
                            owner() == msg.sender,
                            "Ownership cannot be changed in multicall"
                        );
                    }
                    /**
                      @param _returnData The data returned from a multicall result
                      @dev Used to grab the revert string from the underlying call
                     */
                    function _getRevertMsg(bytes memory _returnData)
                        internal
                        pure
                        returns (string memory)
                    {
                        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
                        if (_returnData.length < 68) return "Transaction reverted silently";
                        assembly {
                            // Slice the sighash.
                            _returnData := add(_returnData, 0x04)
                        }
                        return abi.decode(_returnData, (string)); // All that remains is the revert string
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                import {IOwnershipTransferCallback} from "./IOwnershipTransferCallback.sol";
                import {Address} from "../imports/Address.sol";
                abstract contract OwnableWithTransferCallback {
                    using Address for address;
                    bytes4 constant TRANSFER_CALLBACK =
                        type(IOwnershipTransferCallback).interfaceId;
                    error Ownable_NotOwner();
                    error Ownable_NewOwnerZeroAddress();
                    address private _owner;
                    event OwnershipTransferred(address indexed newOwner);
                    /// @dev Initializes the contract setting the deployer as the initial owner.
                    function __Ownable_init(address initialOwner) internal {
                        _owner = initialOwner;
                    }
                    /// @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() {
                        if (owner() != msg.sender) revert Ownable_NotOwner();
                        _;
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Disallows setting to the zero address as a way to more gas-efficiently avoid reinitialization
                    /// When ownership is transferred, if the new owner implements IOwnershipTransferCallback, we make a callback
                    /// Can only be called by the current owner.
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress();
                        _transferOwnership(newOwner);
                        // Call the on ownership transfer callback if it exists
                        // @dev try/catch is around 5k gas cheaper than doing ERC165 checking
                        if (newOwner.isContract()) {
                            try
                                IOwnershipTransferCallback(newOwner).onOwnershipTransfer(
                                    msg.sender
                                )
                            {} catch (bytes memory) {}
                        }
                    }
                    /// @dev Transfers ownership of the contract to a new account (`newOwner`).
                    /// Internal function without access restriction.
                    function _transferOwnership(address newOwner) internal virtual {
                        _owner = newOwner;
                        emit OwnershipTransferred(newOwner);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.4;
                interface IOwnershipTransferCallback {
                    function onOwnershipTransfer(address oldOwner) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @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
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                        uint256 size;
                        assembly {
                            size := extcodesize(account)
                        }
                        return size > 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);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                // Forked from OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol),
                // removed initializer check as we already do that in our modified Ownable
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    function __ReentrancyGuard_init() internal {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        // On the first call to nonReentrant, _notEntered will be true
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                        _;
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {CurveErrorCodes} from "./CurveErrorCodes.sol";
                interface ICurve {
                    /**
                        @notice Validates if a delta value is valid for the curve. The criteria for
                        validity can be different for each type of curve, for instance ExponentialCurve
                        requires delta to be greater than 1.
                        @param delta The delta value to be validated
                        @return valid True if delta is valid, false otherwise
                     */
                    function validateDelta(uint128 delta) external pure returns (bool valid);
                    /**
                        @notice Validates if a new spot price is valid for the curve. Spot price is generally assumed to be the immediate sell price of 1 NFT to the pool, in units of the pool's paired token.
                        @param newSpotPrice The new spot price to be set
                        @return valid True if the new spot price is valid, false otherwise
                     */
                    function validateSpotPrice(uint128 newSpotPrice)
                        external
                        view
                        returns (bool valid);
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should pay to purchase an NFT from the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is buying from the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return inputValue The amount that the user should pay, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getBuyInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 inputValue,
                            uint256 protocolFee
                        );
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should receive when selling NFTs to the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is selling to the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return outputValue The amount that the user should receive, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getSellInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 outputValue,
                            uint256 protocolFee
                        );
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                contract CurveErrorCodes {
                    enum Error {
                        OK, // No error
                        INVALID_NUMITEMS, // The numItem value is 0
                        SPOT_PRICE_OVERFLOW // The updated spot price doesn't fit into 128 bits
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721} from "./imports/IERC721.sol";
                import {ERC20} from "./imports/ERC20.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                contract LSSVMRouter {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    struct PairSwapAny {
                        LSSVMPair pair;
                        uint256 numItems;
                    }
                    struct PairSwapSpecific {
                        LSSVMPair pair;
                        uint256[] nftIds;
                    }
                    struct RobustPairSwapAny {
                        PairSwapAny swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecific {
                        PairSwapSpecific swapInfo;
                        uint256 maxCost;
                    }
                    struct RobustPairSwapSpecificForToken {
                        PairSwapSpecific swapInfo;
                        uint256 minOutput;
                    }
                    struct NFTsForAnyNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapAny[] tokenToNFTTrades;
                    }
                    struct NFTsForSpecificNFTsTrade {
                        PairSwapSpecific[] nftToTokenTrades;
                        PairSwapSpecific[] tokenToNFTTrades;
                    }
                    struct RobustPairNFTsFoTokenAndTokenforNFTsTrade {
                        RobustPairSwapSpecific[] tokenToNFTTrades;
                        RobustPairSwapSpecificForToken[] nftToTokenTrades;
                        uint256 inputAmount;
                        address payable tokenRecipient;
                        address nftRecipient;
                    }
                    modifier checkDeadline(uint256 deadline) {
                        _checkDeadline(deadline);
                        _;
                    }
                    ILSSVMPairFactoryLike public immutable factory;
                    constructor(ILSSVMPairFactoryLike _factory) {
                        factory = _factory;
                    }
                    /**
                        ETH swaps
                     */
                    /**
                        @notice Swaps ETH into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForAnyNFTs(swapList, msg.value, ethRecipient, nftRecipient);
                    }
                    /**
                        @notice Swaps ETH into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent ETH amount
                     */
                    function swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        return
                            _swapETHForSpecificNFTs(
                                swapList,
                                msg.value,
                                ethRecipient,
                                nftRecipient
                            );
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForAnyNFTsThroughETH(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for any NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        ETH as the intermediary.
                        @param trade The struct containing all NFT-to-ETH swaps and ETH-to-NFT swaps.
                        @param minOutput The minimum acceptable total excess ETH received
                        @param ethRecipient The address that will receive the ETH output
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH received
                     */
                    function swapNFTsForSpecificNFTsThroughETH(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 minOutput,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    ) external payable checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ETH
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(address(this))
                        );
                        // Add extra value to buy NFTs
                        outputAmount += msg.value;
                        // Swap ETH for specific NFTs
                        // cost <= inputValue = outputAmount - minOutput, so outputAmount' = (outputAmount - minOutput - cost) + minOutput >= minOutput
                        outputAmount =
                            _swapETHForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                ethRecipient,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        ERC20 swaps
                        Note: All ERC20 swaps assume that a single ERC20 token is used for all the pairs involved.
                        Swapping using multiple tokens in the same transaction is possible, but the slippage checks
                        & the return values will be meaningless, and may lead to undefined behavior.
                        Note: The sender should ideally grant infinite token approval to the router in order for NFT-to-NFT
                        swaps to work smoothly.
                     */
                    /**
                        @notice Swaps ERC20 tokens into NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForAnyNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps ERC20 tokens into specific NFTs using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        return _swapERC20ForSpecificNFTs(swapList, inputAmount, nftRecipient);
                    }
                    /**
                        @notice Swaps NFTs into ETH/ERC20 using multiple pairs.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param minOutput The minimum acceptable total tokens received
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total tokens received
                     */
                    function swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        return _swapNFTsForToken(swapList, minOutput, payable(tokenRecipient));
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForAnyNFTsThroughERC20(
                        NFTsForAnyNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for any NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForAnyNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        @notice Swaps one set of NFTs into another set of specific NFTs using multiple pairs, using
                        an ERC20 token as the intermediary.
                        @param trade The struct containing all NFT-to-ERC20 swaps and ERC20-to-NFT swaps.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param minOutput The minimum acceptable total excess tokens received
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ERC20 tokens received
                     */
                    function swapNFTsForSpecificNFTsThroughERC20(
                        NFTsForSpecificNFTsTrade calldata trade,
                        uint256 inputAmount,
                        uint256 minOutput,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Swap NFTs for ERC20
                        // minOutput of swap set to 0 since we're doing an aggregate slippage check
                        // output tokens are sent to msg.sender
                        outputAmount = _swapNFTsForToken(
                            trade.nftToTokenTrades,
                            0,
                            payable(msg.sender)
                        );
                        // Add extra value to buy NFTs
                        outputAmount += inputAmount;
                        // Swap ERC20 for specific NFTs
                        // cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput
                        // input tokens are taken directly from msg.sender
                        outputAmount =
                            _swapERC20ForSpecificNFTs(
                                trade.tokenToNFTTrades,
                                outputAmount - minOutput,
                                nftRecipient
                            ) +
                            minOutput;
                    }
                    /**
                        Robust Swaps
                        These are "robust" versions of the NFT<>Token swap functions which will never revert due to slippage
                        Instead, users specify a per-swap max cost. If the price changes more than the user specifies, no swap is attempted. This allows users to specify a batch of swaps, and execute as many of them as possible.
                     */
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @notice Swaps as much ETH for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        // Try doing each swap
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs{
                                    value: pairCost
                                }(
                                    swapList[i].swapInfo.numItems,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @dev We assume msg.value >= sum of values in maxCostPerPair
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param ethRecipient The address that will receive the unspent ETH input
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapETHForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        address payable ethRecipient,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = msg.value;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                // We know how much ETH to send because we already did the math above
                                // So we just send that much
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs{value: pairCost}(
                                    swapList[i].swapInfo.nftIds,
                                    pairCost,
                                    nftRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for any NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the number of NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                        
                     */
                    function robustSwapERC20ForAnyNFTs(
                        RobustPairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.numItems
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i].swapInfo.pair.swapTokenForAnyNFTs(
                                        swapList[i].swapInfo.numItems,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many ERC20 tokens for specific NFTs as possible, respecting the per-swap max cost.
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to buy from each.
                        @param inputAmount The amount of ERC20 tokens to add to the ERC20-to-NFT swaps
                        @param nftRecipient The address that will receive the NFT output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return remainingValue The unspent token amount
                     */
                    function robustSwapERC20ForSpecificNFTs(
                        RobustPairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient,
                        uint256 deadline
                    )
                        external
                        payable
                        checkDeadline(deadline)
                        returns (uint256 remainingValue)
                    {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate actual cost per swap
                            (error, , , pairCost, ) = swapList[i].swapInfo.pair.getBuyNFTQuote(
                                swapList[i].swapInfo.nftIds.length
                            );
                            // If within our maxCost and no error, proceed
                            if (
                                pairCost <= swapList[i].maxCost &&
                                error == CurveErrorCodes.Error.OK
                            ) {
                                remainingValue -= swapList[i]
                                    .swapInfo
                                    .pair
                                    .swapTokenForSpecificNFTs(
                                        swapList[i].swapInfo.nftIds,
                                        pairCost,
                                        nftRecipient,
                                        true,
                                        msg.sender
                                    );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps as many NFTs for tokens as possible, respecting the per-swap min output
                        @param swapList The list of pairs to trade with and the IDs of the NFTs to sell to each.
                        @param tokenRecipient The address that will receive the token output
                        @param deadline The Unix timestamp (in seconds) at/after which the swap will revert
                        @return outputAmount The total ETH/ERC20 received
                     */
                    function robustSwapNFTsForToken(
                        RobustPairSwapSpecificForToken[] calldata swapList,
                        address payable tokenRecipient,
                        uint256 deadline
                    ) external checkDeadline(deadline) returns (uint256 outputAmount) {
                        // Try doing each swap
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            uint256 pairOutput;
                            // Locally scoped to avoid stack too deep error
                            {
                                CurveErrorCodes.Error error;
                                (error, , , pairOutput, ) = swapList[i]
                                    .swapInfo
                                    .pair
                                    .getSellNFTQuote(swapList[i].swapInfo.nftIds.length);
                                if (error != CurveErrorCodes.Error.OK) {
                                    unchecked {
                                        ++i;
                                    }
                                    continue;
                                }
                            }
                            // If at least equal to our minOutput, proceed
                            if (pairOutput >= swapList[i].minOutput) {
                                // Do the swap and update outputAmount with how many tokens we got
                                outputAmount += swapList[i].swapInfo.pair.swapNFTsForToken(
                                    swapList[i].swapInfo.nftIds,
                                    0,
                                    tokenRecipient,
                                    true,
                                    msg.sender
                                );
                            }
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ETH and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapETHForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = msg.value;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    // We know how much ETH to send because we already did the math above
                                    // So we just send that much
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs{value: pairCost}(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds,
                                        pairCost,
                                        params.nftRecipient,
                                        true,
                                        msg.sender
                                    );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                            // Return remaining value to sender
                            if (remainingValue > 0) {
                                params.tokenRecipient.safeTransferETH(remainingValue);
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    /**
                        @notice Buys NFTs with ERC20, and sells them for tokens in one transaction
                        @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing:
                        - ethToNFTSwapList The list of NFTs to buy
                        - nftToTokenSwapList The list of NFTs to sell
                        - inputAmount The max amount of tokens to send (if ERC20)
                        - tokenRecipient The address that receives tokens from the NFTs sold
                        - nftRecipient The address that receives NFTs
                        - deadline UNIX timestamp deadline for the swap
                     */
                    function robustSwapERC20ForSpecificNFTsAndNFTsToToken(
                        RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params
                    ) external payable returns (uint256 remainingValue, uint256 outputAmount) {
                        {
                            remainingValue = params.inputAmount;
                            uint256 pairCost;
                            CurveErrorCodes.Error error;
                            // Try doing each swap
                            uint256 numSwaps = params.tokenToNFTTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                // Calculate actual cost per swap
                                (error, , , pairCost, ) = params
                                    .tokenToNFTTrades[i]
                                    .swapInfo
                                    .pair
                                    .getBuyNFTQuote(
                                        params.tokenToNFTTrades[i].swapInfo.nftIds.length
                                    );
                                // If within our maxCost and no error, proceed
                                if (
                                    pairCost <= params.tokenToNFTTrades[i].maxCost &&
                                    error == CurveErrorCodes.Error.OK
                                ) {
                                    remainingValue -= params
                                        .tokenToNFTTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapTokenForSpecificNFTs(
                                            params.tokenToNFTTrades[i].swapInfo.nftIds,
                                            pairCost,
                                            params.nftRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                        {
                            // Try doing each swap
                            uint256 numSwaps = params.nftToTokenTrades.length;
                            for (uint256 i; i < numSwaps; ) {
                                uint256 pairOutput;
                                // Locally scoped to avoid stack too deep error
                                {
                                    CurveErrorCodes.Error error;
                                    (error, , , pairOutput, ) = params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .getSellNFTQuote(
                                            params.nftToTokenTrades[i].swapInfo.nftIds.length
                                        );
                                    if (error != CurveErrorCodes.Error.OK) {
                                        unchecked {
                                            ++i;
                                        }
                                        continue;
                                    }
                                }
                                // If at least equal to our minOutput, proceed
                                if (pairOutput >= params.nftToTokenTrades[i].minOutput) {
                                    // Do the swap and update outputAmount with how many tokens we got
                                    outputAmount += params
                                        .nftToTokenTrades[i]
                                        .swapInfo
                                        .pair
                                        .swapNFTsForToken(
                                            params.nftToTokenTrades[i].swapInfo.nftIds,
                                            0,
                                            params.tokenRecipient,
                                            true,
                                            msg.sender
                                        );
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                    receive() external payable {}
                    /**
                        Restricted functions
                     */
                    /**
                        @dev Allows an ERC20 pair contract to transfer ERC20 tokens directly from
                        the sender, in order to minimize the number of token transfers. Only callable by an ERC20 pair.
                        @param token The ERC20 token to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param amount The amount of tokens to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferERC20From(
                        ERC20 token,
                        address from,
                        address to,
                        uint256 amount,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // verify caller is an ERC20 pair
                        require(
                            variant == ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ERC20 ||
                                variant ==
                                ILSSVMPairFactoryLike.PairVariant.MISSING_ENUMERABLE_ERC20,
                            "Not ERC20 pair"
                        );
                        // transfer tokens to pair
                        token.safeTransferFrom(from, to, amount);
                    }
                    /**
                        @dev Allows a pair contract to transfer ERC721 NFTs directly from
                        the sender, in order to minimize the number of token transfers. Only callable by a pair.
                        @param nft The ERC721 NFT to transfer
                        @param from The address to transfer tokens from
                        @param to The address to transfer tokens to
                        @param id The ID of the NFT to transfer
                        @param variant The pair variant of the pair contract
                     */
                    function pairTransferNFTFrom(
                        IERC721 nft,
                        address from,
                        address to,
                        uint256 id,
                        ILSSVMPairFactoryLike.PairVariant variant
                    ) external {
                        // verify caller is a trusted pair contract
                        require(factory.isPair(msg.sender, variant), "Not pair");
                        // transfer NFTs to pair
                        nft.safeTransferFrom(from, to, id);
                    }
                    /**
                        Internal functions
                     */
                    /**
                        @param deadline The last valid time for a swap
                     */
                    function _checkDeadline(uint256 deadline) internal view {
                        require(block.timestamp <= deadline, "Deadline passed");
                    }
                    /**
                        @notice Internal function used to swap ETH for any NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].numItems
                            );
                            // Require no error
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs{
                                value: pairCost
                            }(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap ETH for a specific set of NFTs
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ETH to send
                        @param ethRecipient The address receiving excess ETH
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapETHForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address payable ethRecipient,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        uint256 pairCost;
                        CurveErrorCodes.Error error;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Calculate the cost per swap first to send exact amount of ETH over, saves gas by avoiding the need to send back excess ETH
                            (error, , , pairCost, ) = swapList[i].pair.getBuyNFTQuote(
                                swapList[i].nftIds.length
                            );
                            // Require no errors
                            require(error == CurveErrorCodes.Error.OK, "Bonding curve error");
                            // Total ETH taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs{
                                value: pairCost
                            }(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Return remaining value to sender
                        if (remainingValue > 0) {
                            ethRecipient.safeTransferETH(remainingValue);
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for any NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForAnyNFTs(
                        PairSwapAny[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForAnyNFTs(
                                swapList[i].numItems,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Internal function used to swap an ERC20 token for specific NFTs
                        @dev Note that we don't need to query the pair's bonding curve first for pricing data because
                        we just calculate and take the required amount from the caller during swap time. 
                        However, we can't "pull" ETH, which is why for the ETH->NFT swaps, we need to calculate the pricing info
                        to figure out how much the router should send to the pool.
                        @param swapList The list of pairs and swap calldata
                        @param inputAmount The total amount of ERC20 tokens to send
                        @param nftRecipient The address receiving the NFTs from the pairs
                        @return remainingValue The unspent token amount
                     */
                    function _swapERC20ForSpecificNFTs(
                        PairSwapSpecific[] calldata swapList,
                        uint256 inputAmount,
                        address nftRecipient
                    ) internal returns (uint256 remainingValue) {
                        remainingValue = inputAmount;
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Tokens are transferred in by the pair calling router.pairTransferERC20From
                            // Total tokens taken from sender cannot exceed inputAmount
                            // because otherwise the deduction from remainingValue will fail
                            remainingValue -= swapList[i].pair.swapTokenForSpecificNFTs(
                                swapList[i].nftIds,
                                remainingValue,
                                nftRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /**
                        @notice Swaps NFTs for tokens, designed to be used for 1 token at a time
                        @dev Calling with multiple tokens is permitted, BUT minOutput will be 
                        far from enough of a safety check because different tokens almost certainly have different unit prices.
                        @param swapList The list of pairs and swap calldata 
                        @param minOutput The minimum number of tokens to be receieved frm the swaps 
                        @param tokenRecipient The address that receives the tokens
                        @return outputAmount The number of tokens to be received
                     */
                    function _swapNFTsForToken(
                        PairSwapSpecific[] calldata swapList,
                        uint256 minOutput,
                        address payable tokenRecipient
                    ) internal returns (uint256 outputAmount) {
                        // Do swaps
                        uint256 numSwaps = swapList.length;
                        for (uint256 i; i < numSwaps; ) {
                            // Do the swap for token and then update outputAmount
                            // Note: minExpectedTokenOutput is set to 0 since we're doing an aggregate slippage check below
                            outputAmount += swapList[i].pair.swapNFTsForToken(
                                swapList[i].nftIds,
                                0,
                                tokenRecipient,
                                true,
                                msg.sender
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        // Aggregate slippage check
                        require(outputAmount >= minOutput, "outputAmount too low");
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                interface ILSSVMPairFactoryLike {
                    enum PairVariant {
                        ENUMERABLE_ETH,
                        MISSING_ENUMERABLE_ETH,
                        ENUMERABLE_ERC20,
                        MISSING_ENUMERABLE_ERC20
                    }
                    function protocolFeeMultiplier() external view returns (uint256);
                    function protocolFeeRecipient() external view returns (address payable);
                    function callAllowed(address target) external view returns (bool);
                    function routerStatus(LSSVMRouter router)
                        external
                        view
                        returns (bool allowed, bool wasEverAllowed);
                    function isPair(address potentialPair, PairVariant variant)
                        external
                        view
                        returns (bool);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./ERC1155Receiver.sol";
                /**
                 * @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;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./IERC1155Receiver.sol";
                import "./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);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./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.
                        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. 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);
                }
                // SPDX-License-Identifier: MIT
                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;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports//IERC721.sol";
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                /**
                    @title An NFT/Token pair where the token is ETH
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairETH is LSSVMPair {
                    using SafeTransferLib for address payable;
                    using SafeTransferLib for ERC20;
                    uint256 internal constant IMMUTABLE_PARAMS_LENGTH = 61;
                    /// @inheritdoc LSSVMPair
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool, /*isRouter*/
                        address, /*routerCaller*/
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        require(msg.value >= inputAmount, "Sent too little ETH");
                        // Transfer inputAmount ETH to assetRecipient if it's been set
                        address payable _assetRecipient = getAssetRecipient();
                        if (_assetRecipient != address(this)) {
                            _assetRecipient.safeTransferETH(inputAmount - protocolFee);
                        }
                        // Take protocol fee
                        if (protocolFee > 0) {
                            // Round down to the actual ETH balance if there are numerical stability issues with the bonding curve calculations
                            if (protocolFee > address(this).balance) {
                                protocolFee = address(this).balance;
                            }
                            if (protocolFee > 0) {
                                payable(address(_factory)).safeTransferETH(protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _refundTokenToSender(uint256 inputAmount) internal override {
                        // Give excess ETH back to caller
                        if (msg.value > inputAmount) {
                            payable(msg.sender).safeTransferETH(msg.value - inputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        // Take protocol fee
                        if (protocolFee > 0) {
                            // Round down to the actual ETH balance if there are numerical stability issues with the bonding curve calculations
                            if (protocolFee > address(this).balance) {
                                protocolFee = address(this).balance;
                            }
                            if (protocolFee > 0) {
                                payable(address(_factory)).safeTransferETH(protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal override {
                        // Send ETH to caller
                        if (outputAmount > 0) {
                            tokenRecipient.safeTransferETH(outputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    // @dev see LSSVMPairCloner for params length calculation
                    function _immutableParamsLength() internal pure override returns (uint256) {
                        return IMMUTABLE_PARAMS_LENGTH;
                    }
                    /**
                        @notice Withdraws all token owned by the pair to the owner address.
                        @dev Only callable by the owner.
                     */
                    function withdrawAllETH() external onlyOwner {
                        withdrawETH(address(this).balance);
                    }
                    /**
                        @notice Withdraws a specified amount of token owned by the pair to the owner address.
                        @dev Only callable by the owner.
                        @param amount The amount of token to send to the owner. If the pair's balance is less than
                        this value, the transaction will be reverted.
                     */
                    function withdrawETH(uint256 amount) public onlyOwner {
                        payable(owner()).safeTransferETH(amount);
                        // emit event since ETH is the pair token
                        emit TokenWithdrawal(amount);
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC20(ERC20 a, uint256 amount)
                        external
                        override
                        onlyOwner
                    {
                        a.safeTransfer(msg.sender, amount);
                    }
                    /**
                        @dev All ETH transfers into the pair are accepted. This is the main method
                        for the owner to top up the pair's token reserves.
                     */
                    receive() external payable {
                        emit TokenDeposit(msg.value);
                    }
                    /**
                        @dev All ETH transfers into the pair are accepted. This is the main method
                        for the owner to top up the pair's token reserves.
                     */
                    fallback() external payable {
                        // Only allow calls without function selector
                        require(msg.data.length == _immutableParamsLength());
                        emit TokenDeposit(msg.value);
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {SafeTransferLib} from "./imports/SafeTransferLib.sol";
                import {ERC20} from "./imports/ERC20.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {ICurve} from "./bonding-curves/ICurve.sol";
                import {CurveErrorCodes} from "./bonding-curves/CurveErrorCodes.sol";
                /**
                    @title An NFT/Token pair where the token is an ERC20
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairERC20 is LSSVMPair {
                    using SafeTransferLib for ERC20;
                    uint256 internal constant IMMUTABLE_PARAMS_LENGTH = 81;
                    /**
                        @notice Returns the ERC20 token associated with the pair
                        @dev See LSSVMPairCloner for an explanation on how this works
                     */
                    function token() public pure returns (ERC20 _token) {
                        uint256 paramsLength = _immutableParamsLength();
                        assembly {
                            _token := shr(
                                0x60,
                                calldataload(add(sub(calldatasize(), paramsLength), 61))
                            )
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _pullTokenInputAndPayProtocolFee(
                        uint256 inputAmount,
                        bool isRouter,
                        address routerCaller,
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        require(msg.value == 0, "ERC20 pair");
                        ERC20 _token = token();
                        address _assetRecipient = getAssetRecipient();
                        if (isRouter) {
                            // Verify if router is allowed
                            LSSVMRouter router = LSSVMRouter(payable(msg.sender));
                            // Locally scoped to avoid stack too deep
                            {
                                (bool routerAllowed, ) = _factory.routerStatus(router);
                                require(routerAllowed, "Not router");
                            }
                            // Cache state and then call router to transfer tokens from user
                            uint256 beforeBalance = _token.balanceOf(_assetRecipient);
                            router.pairTransferERC20From(
                                _token,
                                routerCaller,
                                _assetRecipient,
                                inputAmount - protocolFee,
                                pairVariant()
                            );
                            // Verify token transfer (protect pair against malicious router)
                            require(
                                _token.balanceOf(_assetRecipient) - beforeBalance ==
                                    inputAmount - protocolFee,
                                "ERC20 not transferred in"
                            );
                            router.pairTransferERC20From(
                                _token,
                                routerCaller,
                                address(_factory),
                                protocolFee,
                                pairVariant()
                            );
                            // Note: no check for factory balance's because router is assumed to be set by factory owner
                            // so there is no incentive to *not* pay protocol fee
                        } else {
                            // Transfer tokens directly
                            _token.safeTransferFrom(
                                msg.sender,
                                _assetRecipient,
                                inputAmount - protocolFee
                            );
                            // Take protocol fee (if it exists)
                            if (protocolFee > 0) {
                                _token.safeTransferFrom(
                                    msg.sender,
                                    address(_factory),
                                    protocolFee
                                );
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _refundTokenToSender(uint256 inputAmount) internal override {
                        // Do nothing since we transferred the exact input amount
                    }
                    /// @inheritdoc LSSVMPair
                    function _payProtocolFeeFromPair(
                        ILSSVMPairFactoryLike _factory,
                        uint256 protocolFee
                    ) internal override {
                        // Take protocol fee (if it exists)
                        if (protocolFee > 0) {
                            ERC20 _token = token();
                            // Round down to the actual token balance if there are numerical stability issues with the bonding curve calculations
                            uint256 pairTokenBalance = _token.balanceOf(address(this));
                            if (protocolFee > pairTokenBalance) {
                                protocolFee = pairTokenBalance;
                            }
                            if (protocolFee > 0) {
                                _token.safeTransfer(address(_factory), protocolFee);
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendTokenOutput(
                        address payable tokenRecipient,
                        uint256 outputAmount
                    ) internal override {
                        // Send tokens to caller
                        if (outputAmount > 0) {
                            token().safeTransfer(tokenRecipient, outputAmount);
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    // @dev see LSSVMPairCloner for params length calculation
                    function _immutableParamsLength() internal pure override returns (uint256) {
                        return IMMUTABLE_PARAMS_LENGTH;
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC20(ERC20 a, uint256 amount)
                        external
                        override
                        onlyOwner
                    {
                        a.safeTransfer(msg.sender, amount);
                        if (a == token()) {
                            // emit event since it is the pair token
                            emit TokenWithdrawal(amount);
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import {IERC721} from "../imports/IERC721.sol";
                import {ERC20} from "../imports/ERC20.sol";
                import {ICurve} from "../bonding-curves/ICurve.sol";
                import {ILSSVMPairFactoryLike} from "../ILSSVMPairFactoryLike.sol";
                library LSSVMPairCloner {
                    /**
                     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
                     *
                     * This function uses the create opcode, which should never revert.
                     *
                     * During the delegate call, extra data is copied into the calldata which can then be
                     * accessed by the implementation contract.
                     */
                    function cloneETHPair(
                        address implementation,
                        ILSSVMPairFactoryLike factory,
                        ICurve bondingCurve,
                        IERC721 nft,
                        uint8 poolType
                    ) internal returns (address instance) {
                        assembly {
                            let ptr := mload(0x40)
                            // -------------------------------------------------------------------------------------------------------------
                            // CREATION (9 bytes)
                            // -------------------------------------------------------------------------------------------------------------
                            // creation size = 09
                            // runtime size = 72
                            // 60 runtime  | PUSH1 runtime (r)     | r                       | –
                            // 3d          | RETURNDATASIZE        | 0 r                     | –
                            // 81          | DUP2                  | r 0 r                   | –
                            // 60 creation | PUSH1 creation (c)    | c r 0 r                 | –
                            // 3d          | RETURNDATASIZE        | 0 c r 0 r               | –
                            // 39          | CODECOPY              | 0 r                     | [0-runSize): runtime code
                            // f3          | RETURN                |                         | [0-runSize): runtime code
                            // -------------------------------------------------------------------------------------------------------------
                            // RUNTIME (53 bytes of code + 61 bytes of extra data = 114 bytes)
                            // -------------------------------------------------------------------------------------------------------------
                            // extra data size = 3d
                            // 3d          | RETURNDATASIZE        | 0                       | –
                            // 3d          | RETURNDATASIZE        | 0 0                     | –
                            // 3d          | RETURNDATASIZE        | 0 0 0                   | –
                            // 3d          | RETURNDATASIZE        | 0 0 0 0                 | –
                            // 36          | CALLDATASIZE          | cds 0 0 0 0             | –
                            // 3d          | RETURNDATASIZE        | 0 cds 0 0 0 0           | –
                            // 3d          | RETURNDATASIZE        | 0 0 cds 0 0 0 0         | –
                            // 37          | CALLDATACOPY          | 0 0 0 0                 | [0, cds) = calldata
                            // 60 extra    | PUSH1 extra           | extra 0 0 0 0           | [0, cds) = calldata
                            // 60 0x35     | PUSH1 0x35            | 0x35 extra 0 0 0 0      | [0, cds) = calldata // 0x35 (53) is runtime size - data
                            // 36          | CALLDATASIZE          | cds 0x35 extra 0 0 0 0  | [0, cds) = calldata
                            // 39          | CODECOPY              | 0 0 0 0                 | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 36          | CALLDATASIZE          | cds 0 0 0 0             | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 60 extra    | PUSH1 extra           | extra cds 0 0 0 0       | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 01          | ADD                   | cds+extra 0 0 0 0       | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3d          | RETURNDATASIZE        | 0 cds 0 0 0 0           | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 73 addr     | PUSH20 0x123…         | addr 0 cds 0 0 0 0      | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            mstore(
                                ptr,
                                hex"60_72_3d_81_60_09_3d_39_f3_3d_3d_3d_3d_36_3d_3d_37_60_3d_60_35_36_39_36_60_3d_01_3d_73_00_00_00"
                            )
                            mstore(add(ptr, 0x1d), shl(0x60, implementation))
                            // 5a          | GAS                   | gas addr 0 cds 0 0 0 0  | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // f4          | DELEGATECALL          | success 0 0             | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3d          | RETURNDATASIZE        | rds success 0 0         | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3d          | RETURNDATASIZE        | rds rds success 0 0     | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 93          | SWAP4                 | 0 rds success 0 rds     | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 80          | DUP1                  | 0 0 rds success 0 rds   | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3e          | RETURNDATACOPY        | success 0 rds           | [0, rds) = return data (there might be some irrelevant leftovers in memory [rds, cds+0x37) when rds < cds+0x37)
                            // 60 0x33     | PUSH1 0x33            | 0x33 sucess 0 rds       | [0, rds) = return data
                            // 57          | JUMPI                 | 0 rds                   | [0, rds) = return data
                            // fd          | REVERT                | –                       | [0, rds) = return data
                            // 5b          | JUMPDEST              | 0 rds                   | [0, rds) = return data
                            // f3          | RETURN                | –                       | [0, rds) = return data
                            mstore(
                                add(ptr, 0x31),
                                hex"5a_f4_3d_3d_93_80_3e_60_33_57_fd_5b_f3_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00"
                            )
                            // -------------------------------------------------------------------------------------------------------------
                            // EXTRA DATA (61 bytes)
                            // -------------------------------------------------------------------------------------------------------------
                            mstore(add(ptr, 0x3e), shl(0x60, factory))
                            mstore(add(ptr, 0x52), shl(0x60, bondingCurve))
                            mstore(add(ptr, 0x66), shl(0x60, nft))
                            mstore8(add(ptr, 0x7a), poolType)
                            instance := create(0, ptr, 0x7b)
                        }
                    }
                    /**
                     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
                     *
                     * This function uses the create opcode, which should never revert.
                     *
                     * During the delegate call, extra data is copied into the calldata which can then be
                     * accessed by the implementation contract.
                     */
                    function cloneERC20Pair(
                        address implementation,
                        ILSSVMPairFactoryLike factory,
                        ICurve bondingCurve,
                        IERC721 nft,
                        uint8 poolType,
                        ERC20 token
                    ) internal returns (address instance) {
                        assembly {
                            let ptr := mload(0x40)
                            // -------------------------------------------------------------------------------------------------------------
                            // CREATION (9 bytes)
                            // -------------------------------------------------------------------------------------------------------------
                            // creation size = 09
                            // runtime size = 86
                            // 60 runtime  | PUSH1 runtime (r)     | r                       | –
                            // 3d          | RETURNDATASIZE        | 0 r                     | –
                            // 81          | DUP2                  | r 0 r                   | –
                            // 60 creation | PUSH1 creation (c)    | c r 0 r                 | –
                            // 3d          | RETURNDATASIZE        | 0 c r 0 r               | –
                            // 39          | CODECOPY              | 0 r                     | [0-runSize): runtime code
                            // f3          | RETURN                |                         | [0-runSize): runtime code
                            // -------------------------------------------------------------------------------------------------------------
                            // RUNTIME (53 bytes of code + 81 bytes of extra data = 134 bytes)
                            // -------------------------------------------------------------------------------------------------------------
                            // extra data size = 51
                            // 3d          | RETURNDATASIZE        | 0                       | –
                            // 3d          | RETURNDATASIZE        | 0 0                     | –
                            // 3d          | RETURNDATASIZE        | 0 0 0                   | –
                            // 3d          | RETURNDATASIZE        | 0 0 0 0                 | –
                            // 36          | CALLDATASIZE          | cds 0 0 0 0             | –
                            // 3d          | RETURNDATASIZE        | 0 cds 0 0 0 0           | –
                            // 3d          | RETURNDATASIZE        | 0 0 cds 0 0 0 0         | –
                            // 37          | CALLDATACOPY          | 0 0 0 0                 | [0, cds) = calldata
                            // 60 extra    | PUSH1 extra           | extra 0 0 0 0           | [0, cds) = calldata
                            // 60 0x35     | PUSH1 0x35            | 0x35 extra 0 0 0 0      | [0, cds) = calldata // 0x35 (53) is runtime size - data
                            // 36          | CALLDATASIZE          | cds 0x35 extra 0 0 0 0  | [0, cds) = calldata
                            // 39          | CODECOPY              | 0 0 0 0                 | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 36          | CALLDATASIZE          | cds 0 0 0 0             | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 60 extra    | PUSH1 extra           | extra cds 0 0 0 0       | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 01          | ADD                   | cds+extra 0 0 0 0       | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3d          | RETURNDATASIZE        | 0 cds 0 0 0 0           | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 73 addr     | PUSH20 0x123…         | addr 0 cds 0 0 0 0      | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            mstore(
                                ptr,
                                hex"60_86_3d_81_60_09_3d_39_f3_3d_3d_3d_3d_36_3d_3d_37_60_51_60_35_36_39_36_60_51_01_3d_73_00_00_00"
                            )
                            mstore(add(ptr, 0x1d), shl(0x60, implementation))
                            // 5a          | GAS                   | gas addr 0 cds 0 0 0 0  | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // f4          | DELEGATECALL          | success 0 0             | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3d          | RETURNDATASIZE        | rds success 0 0         | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3d          | RETURNDATASIZE        | rds rds success 0 0     | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 93          | SWAP4                 | 0 rds success 0 rds     | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 80          | DUP1                  | 0 0 rds success 0 rds   | [0, cds) = calldata, [cds, cds+0x35) = extraData
                            // 3e          | RETURNDATACOPY        | success 0 rds           | [0, rds) = return data (there might be some irrelevant leftovers in memory [rds, cds+0x37) when rds < cds+0x37)
                            // 60 0x33     | PUSH1 0x33            | 0x33 sucess 0 rds       | [0, rds) = return data
                            // 57          | JUMPI                 | 0 rds                   | [0, rds) = return data
                            // fd          | REVERT                | –                       | [0, rds) = return data
                            // 5b          | JUMPDEST              | 0 rds                   | [0, rds) = return data
                            // f3          | RETURN                | –                       | [0, rds) = return data
                            mstore(
                                add(ptr, 0x31),
                                hex"5a_f4_3d_3d_93_80_3e_60_33_57_fd_5b_f3_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00"
                            )
                            // -------------------------------------------------------------------------------------------------------------
                            // EXTRA DATA (81 bytes)
                            // -------------------------------------------------------------------------------------------------------------
                            mstore(add(ptr, 0x3e), shl(0x60, factory))
                            mstore(add(ptr, 0x52), shl(0x60, bondingCurve))
                            mstore(add(ptr, 0x66), shl(0x60, nft))
                            mstore8(add(ptr, 0x7a), poolType)
                            mstore(add(ptr, 0x7b), shl(0x60, token))
                            instance := create(0, ptr, 0x8f)
                        }
                    }
                    /**
                     * @notice Checks if a contract is a clone of a LSSVMPairETH.
                     * @dev Only checks the runtime bytecode, does not check the extra data.
                     * @param factory the factory that deployed the clone
                     * @param implementation the LSSVMPairETH implementation contract
                     * @param query the contract to check
                     * @return result True if the contract is a clone, false otherwise
                     */
                    function isETHPairClone(
                        address factory,
                        address implementation,
                        address query
                    ) internal view returns (bool result) {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let ptr := mload(0x40)
                            mstore(
                                ptr,
                                hex"3d_3d_3d_3d_36_3d_3d_37_60_3d_60_35_36_39_36_60_3d_01_3d_73_00_00_00_00_00_00_00_00_00_00_00_00"
                            )
                            mstore(add(ptr, 0x14), shl(0x60, implementation))
                            mstore(
                                add(ptr, 0x28),
                                hex"5a_f4_3d_3d_93_80_3e_60_33_57_fd_5b_f3_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00"
                            )
                            mstore(add(ptr, 0x35), shl(0x60, factory))
                            // compare expected bytecode with that of the queried contract
                            let other := add(ptr, 0x49)
                            extcodecopy(query, other, 0, 0x49)
                            result := and(
                                eq(mload(ptr), mload(other)),
                                and(
                                    eq(mload(add(ptr, 0x20)), mload(add(other, 0x20))),
                                    eq(mload(add(ptr, 0x29)), mload(add(other, 0x29)))
                                )
                            )
                        }
                    }
                    /**
                     * @notice Checks if a contract is a clone of a LSSVMPairERC20.
                     * @dev Only checks the runtime bytecode, does not check the extra data.
                     * @param implementation the LSSVMPairERC20 implementation contract
                     * @param query the contract to check
                     * @return result True if the contract is a clone, false otherwise
                     */
                    function isERC20PairClone(
                        address factory,
                        address implementation,
                        address query
                    ) internal view returns (bool result) {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let ptr := mload(0x40)
                            mstore(
                                ptr,
                                hex"3d_3d_3d_3d_36_3d_3d_37_60_51_60_35_36_39_36_60_51_01_3d_73_00_00_00_00_00_00_00_00_00_00_00_00"
                            )
                            mstore(add(ptr, 0x14), shl(0x60, implementation))
                            mstore(
                                add(ptr, 0x28),
                                hex"5a_f4_3d_3d_93_80_3e_60_33_57_fd_5b_f3_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00"
                            )
                            mstore(add(ptr, 0x35), shl(0x60, factory))
                            // compare expected bytecode with that of the queried contract
                            let other := add(ptr, 0x49)
                            extcodecopy(query, other, 0, 0x49)
                            result := and(
                                eq(mload(ptr), mload(other)),
                                and(
                                    eq(mload(add(ptr, 0x20)), mload(add(other, 0x20))),
                                    eq(mload(add(ptr, 0x29)), mload(add(other, 0x29)))
                                )
                            )
                        }
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMPairETH} from "./LSSVMPairETH.sol";
                import {LSSVMPairEnumerable} from "./LSSVMPairEnumerable.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair where the NFT implements ERC721Enumerable, and the token is ETH
                    @author boredGenius and 0xmons
                 */
                contract LSSVMPairEnumerableETH is LSSVMPairEnumerable, LSSVMPairETH {
                    /**
                        @notice Returns the LSSVMPair type
                     */
                    function pairVariant()
                        public
                        pure
                        override
                        returns (ILSSVMPairFactoryLike.PairVariant)
                    {
                        return ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ETH;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721Enumerable} from "./imports/IERC721Enumerable.sol";
                import {IERC721} from "./imports/IERC721.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair for an NFT that implements ERC721Enumerable
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairEnumerable is LSSVMPair {
                    /// @inheritdoc LSSVMPair
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal override {
                        // Send NFTs to recipient
                        // (we know NFT implements IERC721Enumerable so we just iterate)
                        uint256 lastIndex = _nft.balanceOf(address(this)) - 1;
                        for (uint256 i = 0; i < numNFTs; ) {
                            uint256 nftId = IERC721Enumerable(address(_nft))
                                .tokenOfOwnerByIndex(address(this), lastIndex);
                            _nft.safeTransferFrom(address(this), nftRecipient, nftId);
                            unchecked {
                                --lastIndex;
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal override {
                        // Send NFTs to recipient
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(address(this), nftRecipient, nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function getAllHeldIds() external view override returns (uint256[] memory) {
                        IERC721 _nft = nft();
                        uint256 numNFTs = _nft.balanceOf(address(this));
                        uint256[] memory ids = new uint256[](numNFTs);
                        for (uint256 i; i < numNFTs; ) {
                            ids[i] = IERC721Enumerable(address(_nft)).tokenOfOwnerByIndex(
                                address(this),
                                i
                            );
                            unchecked {
                                ++i;
                            }
                        }
                        return ids;
                    }
                    function onERC721Received(
                        address,
                        address,
                        uint256,
                        bytes memory
                    ) public virtual returns (bytes4) {
                        return this.onERC721Received.selector;
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        override
                        onlyOwner
                    {
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            a.safeTransferFrom(address(this), msg.sender, nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                        emit NFTWithdrawal();
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMPairERC20} from "./LSSVMPairERC20.sol";
                import {LSSVMPairEnumerable} from "./LSSVMPairEnumerable.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair where the NFT implements ERC721Enumerable, and the token is an ERC20
                    @author boredGenius and 0xmons
                 */
                contract LSSVMPairEnumerableERC20 is LSSVMPairEnumerable, LSSVMPairERC20 {
                    /**
                        @notice Returns the LSSVMPair type
                     */
                    function pairVariant()
                        public
                        pure
                        override
                        returns (ILSSVMPairFactoryLike.PairVariant)
                    {
                        return ILSSVMPairFactoryLike.PairVariant.ENUMERABLE_ERC20;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMPairETH} from "./LSSVMPairETH.sol";
                import {LSSVMPairMissingEnumerable} from "./LSSVMPairMissingEnumerable.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                contract LSSVMPairMissingEnumerableETH is
                    LSSVMPairMissingEnumerable,
                    LSSVMPairETH
                {
                    function pairVariant()
                        public
                        pure
                        override
                        returns (ILSSVMPairFactoryLike.PairVariant)
                    {
                        return ILSSVMPairFactoryLike.PairVariant.MISSING_ENUMERABLE_ETH;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {IERC721} from "./imports/IERC721.sol";
                import {EnumerableSet} from "./imports/EnumerableSet.sol";
                import {LSSVMPair} from "./LSSVMPair.sol";
                import {LSSVMRouter} from "./LSSVMRouter.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                /**
                    @title An NFT/Token pair for an NFT that does not implement ERC721Enumerable
                    @author boredGenius and 0xmons
                 */
                abstract contract LSSVMPairMissingEnumerable is LSSVMPair {
                    using EnumerableSet for EnumerableSet.UintSet;
                    // Used for internal ID tracking
                    EnumerableSet.UintSet private idSet;
                    /// @inheritdoc LSSVMPair
                    function _sendAnyNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256 numNFTs
                    ) internal override {
                        // Send NFTs to recipient
                        // We're missing enumerable, so we also update the pair's own ID set
                        // NOTE: We start from last index to first index to save on gas
                        uint256 lastIndex = idSet.length() - 1;
                        for (uint256 i; i < numNFTs; ) {
                            uint256 nftId = idSet.at(lastIndex);
                            _nft.safeTransferFrom(address(this), nftRecipient, nftId);
                            idSet.remove(nftId);
                            unchecked {
                                --lastIndex;
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function _sendSpecificNFTsToRecipient(
                        IERC721 _nft,
                        address nftRecipient,
                        uint256[] calldata nftIds
                    ) internal override {
                        // Send NFTs to caller
                        // If missing enumerable, update pool's own ID set
                        uint256 numNFTs = nftIds.length;
                        for (uint256 i; i < numNFTs; ) {
                            _nft.safeTransferFrom(address(this), nftRecipient, nftIds[i]);
                            // Remove from id set
                            idSet.remove(nftIds[i]);
                            unchecked {
                                ++i;
                            }
                        }
                    }
                    /// @inheritdoc LSSVMPair
                    function getAllHeldIds() external view override returns (uint256[] memory) {
                        uint256 numNFTs = idSet.length();
                        uint256[] memory ids = new uint256[](numNFTs);
                        for (uint256 i; i < numNFTs; ) {
                            ids[i] = idSet.at(i);
                            unchecked {
                                ++i;
                            }
                        }
                        return ids;
                    }
                    /**
                        @dev When safeTransfering an ERC721 in, we add ID to the idSet
                        if it's the same collection used by pool. (As it doesn't auto-track because no ERC721Enumerable)
                     */
                    function onERC721Received(
                        address,
                        address,
                        uint256 id,
                        bytes memory
                    ) public virtual returns (bytes4) {
                        IERC721 _nft = nft();
                        // If it's from the pair's NFT, add the ID to ID set
                        if (msg.sender == address(_nft)) {
                            idSet.add(id);
                        }
                        return this.onERC721Received.selector;
                    }
                    /// @inheritdoc LSSVMPair
                    function withdrawERC721(IERC721 a, uint256[] calldata nftIds)
                        external
                        override
                        onlyOwner
                    {
                        IERC721 _nft = nft();
                        uint256 numNFTs = nftIds.length;
                        // If it's not the pair's NFT, just withdraw normally
                        if (a != _nft) {
                            for (uint256 i; i < numNFTs; ) {
                                a.safeTransferFrom(address(this), msg.sender, nftIds[i]);
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                        // Otherwise, withdraw and also remove the ID from the ID set
                        else {
                            for (uint256 i; i < numNFTs; ) {
                                _nft.safeTransferFrom(address(this), msg.sender, nftIds[i]);
                                idSet.remove(nftIds[i]);
                                unchecked {
                                    ++i;
                                }
                            }
                            emit NFTWithdrawal();
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev Library for managing
                 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                 * types.
                 *
                 * Sets have the following properties:
                 *
                 * - Elements are added, removed, and checked for existence in constant time
                 * (O(1)).
                 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                 *
                 * ```
                 * contract Example {
                 *     // Add the library methods
                 *     using EnumerableSet for EnumerableSet.AddressSet;
                 *
                 *     // Declare a set state variable
                 *     EnumerableSet.AddressSet private mySet;
                 * }
                 * ```
                 *
                 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                 * and `uint256` (`UintSet`) are supported.
                 */
                library EnumerableSet {
                    // To implement this library for multiple types with as little code
                    // repetition as possible, we write it in terms of a generic Set type with
                    // bytes32 values.
                    // The Set implementation uses private functions, and user-facing
                    // implementations (such as AddressSet) are just wrappers around the
                    // underlying Set.
                    // This means that we can only create new EnumerableSets for types that fit
                    // in bytes32.
                    struct Set {
                        // Storage of set values
                        bytes32[] _values;
                        // Position of the value in the `values` array, plus 1 because index 0
                        // means a value is not in the set.
                        mapping(bytes32 => uint256) _indexes;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function _add(Set storage set, bytes32 value) private returns (bool) {
                        if (!_contains(set, value)) {
                            set._values.push(value);
                            // The value is stored at length-1, but we add 1 to all indexes
                            // and use 0 as a sentinel value
                            set._indexes[value] = set._values.length;
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function _remove(Set storage set, bytes32 value) private returns (bool) {
                        // We read and store the value's index to prevent multiple reads from the same storage slot
                        uint256 valueIndex = set._indexes[value];
                        if (valueIndex != 0) {
                            // Equivalent to contains(set, value)
                            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                            // the array, and then remove the last element (sometimes called as 'swap and pop').
                            // This modifies the order of the array, as noted in {at}.
                            uint256 toDeleteIndex = valueIndex - 1;
                            uint256 lastIndex = set._values.length - 1;
                            if (lastIndex != toDeleteIndex) {
                                bytes32 lastvalue = set._values[lastIndex];
                                // Move the last value to the index where the value to delete is
                                set._values[toDeleteIndex] = lastvalue;
                                // Update the index for the moved value
                                set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
                            }
                            // Delete the slot where the moved value was stored
                            set._values.pop();
                            // Delete the index for the deleted slot
                            delete set._indexes[value];
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function _contains(Set storage set, bytes32 value)
                        private
                        view
                        returns (bool)
                    {
                        return set._indexes[value] != 0;
                    }
                    /**
                     * @dev Returns the number of values on the set. O(1).
                     */
                    function _length(Set storage set) private view returns (uint256) {
                        return set._values.length;
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function _at(Set storage set, uint256 index)
                        private
                        view
                        returns (bytes32)
                    {
                        return set._values[index];
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function _values(Set storage set) private view returns (bytes32[] memory) {
                        return set._values;
                    }
                    // Bytes32Set
                    struct Bytes32Set {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(Bytes32Set storage set, bytes32 value)
                        internal
                        returns (bool)
                    {
                        return _add(set._inner, value);
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(Bytes32Set storage set, bytes32 value)
                        internal
                        returns (bool)
                    {
                        return _remove(set._inner, value);
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(Bytes32Set storage set, bytes32 value)
                        internal
                        view
                        returns (bool)
                    {
                        return _contains(set._inner, value);
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(Bytes32Set storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(Bytes32Set storage set, uint256 index)
                        internal
                        view
                        returns (bytes32)
                    {
                        return _at(set._inner, index);
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(Bytes32Set storage set)
                        internal
                        view
                        returns (bytes32[] memory)
                    {
                        return _values(set._inner);
                    }
                    // AddressSet
                    struct AddressSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(AddressSet storage set, address value)
                        internal
                        returns (bool)
                    {
                        return _add(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(AddressSet storage set, address value)
                        internal
                        returns (bool)
                    {
                        return _remove(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(AddressSet storage set, address value)
                        internal
                        view
                        returns (bool)
                    {
                        return _contains(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(AddressSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(AddressSet storage set, uint256 index)
                        internal
                        view
                        returns (address)
                    {
                        return address(uint160(uint256(_at(set._inner, index))));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(AddressSet storage set)
                        internal
                        view
                        returns (address[] memory)
                    {
                        bytes32[] memory store = _values(set._inner);
                        address[] memory result;
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // UintSet
                    struct UintSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(UintSet storage set, uint256 value) internal returns (bool) {
                        return _add(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(UintSet storage set, uint256 value)
                        internal
                        returns (bool)
                    {
                        return _remove(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(UintSet storage set, uint256 value)
                        internal
                        view
                        returns (bool)
                    {
                        return _contains(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns the number of values on the set. O(1).
                     */
                    function length(UintSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(UintSet storage set, uint256 index)
                        internal
                        view
                        returns (uint256)
                    {
                        return uint256(_at(set._inner, index));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(UintSet storage set)
                        internal
                        view
                        returns (uint256[] memory)
                    {
                        bytes32[] memory store = _values(set._inner);
                        uint256[] memory result;
                        assembly {
                            result := store
                        }
                        return result;
                    }
                }
                // SPDX-License-Identifier: AGPL-3.0
                pragma solidity ^0.8.0;
                import {LSSVMPairERC20} from "./LSSVMPairERC20.sol";
                import {LSSVMPairMissingEnumerable} from "./LSSVMPairMissingEnumerable.sol";
                import {ILSSVMPairFactoryLike} from "./ILSSVMPairFactoryLike.sol";
                contract LSSVMPairMissingEnumerableERC20 is
                    LSSVMPairMissingEnumerable,
                    LSSVMPairERC20
                {
                    function pairVariant()
                        public
                        pure
                        override
                        returns (ILSSVMPairFactoryLike.PairVariant)
                    {
                        return ILSSVMPairFactoryLike.PairVariant.MISSING_ENUMERABLE_ERC20;
                    }
                }
                

                File 8 of 8: LinearCurve
                // File: contracts/bonding-curves/CurveErrorCodes.sol
                
                
                // SPDX-License-Identifier: AGPL-3.0-only
                pragma solidity ^0.8.0;
                
                contract CurveErrorCodes {
                    enum Error {
                        OK, // No error
                        INVALID_NUMITEMS, // The numItem value is 0
                        SPOT_PRICE_OVERFLOW // The updated spot price doesn't fit into 128 bits
                    }
                }
                
                // File: contracts/bonding-curves/ICurve.sol
                
                pragma solidity ^0.8.0;
                
                interface ICurve {
                    /**
                        @notice Validates if a delta value is valid for the curve. The criteria for
                        validity can be different for each type of curve, for instance ExponentialCurve
                        requires delta to be greater than 1.
                        @param delta The delta value to be validated
                        @return valid True if delta is valid, false otherwise
                     */
                    function validateDelta(uint128 delta) external pure returns (bool valid);
                
                    /**
                        @notice Validates if a new spot price is valid for the curve. Spot price is generally assumed to be the immediate sell price of 1 NFT to the pool, in units of the pool's paired token.
                        @param newSpotPrice The new spot price to be set
                        @return valid True if the new spot price is valid, false otherwise
                     */
                    function validateSpotPrice(uint128 newSpotPrice)
                        external
                        view
                        returns (bool valid);
                
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should pay to purchase an NFT from the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is buying from the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return inputValue The amount that the user should pay, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getBuyInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 inputValue,
                            uint256 protocolFee
                        );
                
                    /**
                        @notice Given the current state of the pair and the trade, computes how much the user
                        should receive when selling NFTs to the pair, the new spot price, and other values.
                        @param spotPrice The current selling spot price of the pair, in tokens
                        @param delta The delta parameter of the pair, what it means depends on the curve
                        @param numItems The number of NFTs the user is selling to the pair
                        @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
                        @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
                        @return error Any math calculation errors, only Error.OK means the returned values are valid
                        @return newSpotPrice The updated selling spot price, in tokens
                        @return newDelta The updated delta, used to parameterize the bonding curve
                        @return outputValue The amount that the user should receive, in tokens
                        @return protocolFee The amount of fee to send to the protocol, in tokens
                     */
                    function getSellInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        view
                        returns (
                            CurveErrorCodes.Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 outputValue,
                            uint256 protocolFee
                        );
                }
                
                // File: contracts/imports/FixedPointMathLib.sol
                
                pragma solidity >=0.8.0;
                
                /// @notice Arithmetic library with operations for fixed-point numbers.
                /// @author Modified from Dappsys V2 (https://github.com/dapp-org/dappsys-v2/blob/main/src/math.sol)
                /// and ABDK (https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol)
                library FixedPointMathLib {
                    /*///////////////////////////////////////////////////////////////
                                            COMMON BASE UNITS
                    //////////////////////////////////////////////////////////////*/
                
                    uint256 internal constant YAD = 1e8;
                    uint256 internal constant WAD = 1e18;
                    uint256 internal constant RAY = 1e27;
                    uint256 internal constant RAD = 1e45;
                
                    /*///////////////////////////////////////////////////////////////
                                         FIXED POINT OPERATIONS
                    //////////////////////////////////////////////////////////////*/
                
                    function fmul(
                        uint256 x,
                        uint256 y,
                        uint256 baseUnit
                    ) internal pure returns (uint256 z) {
                        assembly {
                            // Store x * y in z for now.
                            z := mul(x, y)
                
                            // Equivalent to require(x == 0 || (x * y) / x == y)
                            if iszero(or(iszero(x), eq(div(z, x), y))) {
                                revert(0, 0)
                            }
                
                            // If baseUnit is zero this will return zero instead of reverting.
                            z := div(z, baseUnit)
                        }
                    }
                
                    function fdiv(
                        uint256 x,
                        uint256 y,
                        uint256 baseUnit
                    ) internal pure returns (uint256 z) {
                        assembly {
                            // Store x * baseUnit in z for now.
                            z := mul(x, baseUnit)
                
                            if or(
                                // Revert if y is zero to ensure we don't divide by zero below.
                                iszero(y),
                                // Equivalent to require(x == 0 || (x * baseUnit) / x == baseUnit)
                                iszero(or(iszero(x), eq(div(z, x), baseUnit)))
                            ) {
                                revert(0, 0)
                            }
                
                            // We ensure y is not zero above, so there is never division by zero here.
                            z := div(z, y)
                        }
                    }
                
                    function fpow(
                        uint256 x,
                        uint256 n,
                        uint256 baseUnit
                    ) internal pure returns (uint256 z) {
                        assembly {
                            switch x
                            case 0 {
                                switch n
                                case 0 {
                                    z := baseUnit
                                }
                                default {
                                    z := 0
                                }
                            }
                            default {
                                switch mod(n, 2)
                                case 0 {
                                    z := baseUnit
                                }
                                default {
                                    z := x
                                }
                                let half := div(baseUnit, 2)
                                for {
                                    n := div(n, 2)
                                } n {
                                    n := div(n, 2)
                                } {
                                    let xx := mul(x, x)
                                    if iszero(eq(div(xx, x), x)) {
                                        revert(0, 0)
                                    }
                                    let xxRound := add(xx, half)
                                    if lt(xxRound, xx) {
                                        revert(0, 0)
                                    }
                                    x := div(xxRound, baseUnit)
                                    if mod(n, 2) {
                                        let zx := mul(z, x)
                                        if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
                                            revert(0, 0)
                                        }
                                        let zxRound := add(zx, half)
                                        if lt(zxRound, zx) {
                                            revert(0, 0)
                                        }
                                        z := div(zxRound, baseUnit)
                                    }
                                }
                            }
                        }
                    }
                
                    /*///////////////////////////////////////////////////////////////
                                        GENERAL NUMBER UTILITIES
                    //////////////////////////////////////////////////////////////*/
                
                    function sqrt(uint256 x) internal pure returns (uint256 result) {
                        if (x == 0) return 0;
                
                        result = 1;
                
                        uint256 xAux = x;
                
                        if (xAux >= 0x100000000000000000000000000000000) {
                            xAux >>= 128;
                            result <<= 64;
                        }
                
                        if (xAux >= 0x10000000000000000) {
                            xAux >>= 64;
                            result <<= 32;
                        }
                
                        if (xAux >= 0x100000000) {
                            xAux >>= 32;
                            result <<= 16;
                        }
                
                        if (xAux >= 0x10000) {
                            xAux >>= 16;
                            result <<= 8;
                        }
                
                        if (xAux >= 0x100) {
                            xAux >>= 8;
                            result <<= 4;
                        }
                
                        if (xAux >= 0x10) {
                            xAux >>= 4;
                            result <<= 2;
                        }
                
                        if (xAux >= 0x8) result <<= 1;
                
                        unchecked {
                            result = (result + x / result) >> 1;
                            result = (result + x / result) >> 1;
                            result = (result + x / result) >> 1;
                            result = (result + x / result) >> 1;
                            result = (result + x / result) >> 1;
                            result = (result + x / result) >> 1;
                            result = (result + x / result) >> 1;
                
                            uint256 roundedDownResult = x / result;
                
                            if (result > roundedDownResult) result = roundedDownResult;
                        }
                    }
                
                    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                        return x < y ? x : y;
                    }
                
                    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
                        return x > y ? x : y;
                    }
                }
                
                // File: contracts/bonding-curves/LinearCurve.sol
                
                pragma solidity ^0.8.0;
                
                
                
                /*
                    @author 0xmons and boredGenius
                    @notice Bonding curve logic for a linear curve, where each buy/sell changes spot price by adding/substracting delta
                */
                contract LinearCurve is ICurve, CurveErrorCodes {
                    using FixedPointMathLib for uint256;
                
                    /**
                        @dev See {ICurve-validateDelta}
                     */
                    function validateDelta(
                        uint128 /*delta*/
                    ) external pure override returns (bool valid) {
                        // For a linear curve, all values of delta are valid
                        return true;
                    }
                
                    /**
                        @dev See {ICurve-validateSpotPrice}
                     */
                    function validateSpotPrice(
                        uint128 /* newSpotPrice */
                    ) external pure override returns (bool) {
                        // For a linear curve, all values of spot price are valid
                        return true;
                    }
                
                    /**
                        @dev See {ICurve-getBuyInfo}
                     */
                    function getBuyInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        pure
                        override
                        returns (
                            Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 inputValue,
                            uint256 protocolFee
                        )
                    {
                        // We only calculate changes for buying 1 or more NFTs
                        if (numItems == 0) {
                            return (Error.INVALID_NUMITEMS, 0, 0, 0, 0);
                        }
                
                        // For a linear curve, the spot price increases by delta for each item bought
                        uint256 newSpotPrice_ = spotPrice + delta * numItems;
                        if (newSpotPrice_ > type(uint128).max) {
                            return (Error.SPOT_PRICE_OVERFLOW, 0, 0, 0, 0);
                        }
                        newSpotPrice = uint128(newSpotPrice_);
                
                        // Spot price is assumed to be the instant sell price. To avoid arbitraging LPs, we adjust the buy price upwards.
                        // If spot price for buy and sell were the same, then someone could buy 1 NFT and then sell for immediate profit.
                        // EX: Let S be spot price. Then buying 1 NFT costs S ETH, now new spot price is (S+delta).
                        // The same person could then sell for (S+delta) ETH, netting them delta ETH profit.
                        // If spot price for buy and sell differ by delta, then buying costs (S+delta) ETH.
                        // The new spot price would become (S+delta), so selling would also yield (S+delta) ETH.
                        uint256 buySpotPrice = spotPrice + delta;
                
                        // If we buy n items, then the total cost is equal to:
                        // (buy spot price) + (buy spot price + 1*delta) + (buy spot price + 2*delta) + ... + (buy spot price + (n-1)*delta)
                        // This is equal to n*(buy spot price) + (delta)*(n*(n-1))/2
                        // because we have n instances of buy spot price, and then we sum up from delta to (n-1)*delta
                        inputValue =
                            numItems *
                            buySpotPrice +
                            (numItems * (numItems - 1) * delta) /
                            2;
                
                        // Account for the protocol fee, a flat percentage of the buy amount
                        protocolFee = inputValue.fmul(
                            protocolFeeMultiplier,
                            FixedPointMathLib.WAD
                        );
                
                        // Account for the trade fee, only for Trade pools
                        inputValue += inputValue.fmul(feeMultiplier, FixedPointMathLib.WAD);
                
                        // Add the protocol fee to the required input amount
                        inputValue += protocolFee;
                
                        // Keep delta the same
                        newDelta = delta;
                
                        // If we got all the way here, no math error happened
                        error = Error.OK;
                    }
                
                    /**
                        @dev See {ICurve-getSellInfo}
                     */
                    function getSellInfo(
                        uint128 spotPrice,
                        uint128 delta,
                        uint256 numItems,
                        uint256 feeMultiplier,
                        uint256 protocolFeeMultiplier
                    )
                        external
                        pure
                        override
                        returns (
                            Error error,
                            uint128 newSpotPrice,
                            uint128 newDelta,
                            uint256 outputValue,
                            uint256 protocolFee
                        )
                    {
                        // We only calculate changes for selling 1 or more NFTs
                        if (numItems == 0) {
                            return (Error.INVALID_NUMITEMS, 0, 0, 0, 0);
                        }
                
                        // We first calculate the change in spot price after selling all of the items
                        uint256 totalPriceDecrease = delta * numItems;
                
                        // If the current spot price is less than the total amount that the spot price should change by...
                        if (spotPrice < totalPriceDecrease) {
                            // Then we set the new spot price to be 0. (Spot price is never negative)
                            newSpotPrice = 0;
                
                            // We calculate how many items we can sell into the linear curve until the spot price reaches 0, rounding up
                            uint256 numItemsTillZeroPrice = spotPrice / delta + 1;
                            numItems = numItemsTillZeroPrice;
                        }
                        // Otherwise, the current spot price is greater than or equal to the total amount that the spot price changes
                        // Thus we don't need to calculate the maximum number of items until we reach zero spot price, so we don't modify numItems
                        else {
                            // The new spot price is just the change between spot price and the total price change
                            newSpotPrice = spotPrice - uint128(totalPriceDecrease);
                        }
                
                        // If we sell n items, then the total sale amount is:
                        // (spot price) + (spot price - 1*delta) + (spot price - 2*delta) + ... + (spot price - (n-1)*delta)
                        // This is equal to n*(spot price) - (delta)*(n*(n-1))/2
                        outputValue =
                            numItems *
                            spotPrice -
                            (numItems * (numItems - 1) * delta) /
                            2;
                
                        // Account for the protocol fee, a flat percentage of the sell amount
                        protocolFee = outputValue.fmul(
                            protocolFeeMultiplier,
                            FixedPointMathLib.WAD
                        );
                
                        // Account for the trade fee, only for Trade pools
                        outputValue -= outputValue.fmul(feeMultiplier, FixedPointMathLib.WAD);
                
                        // Subtract the protocol fee from the output amount to the seller
                        outputValue -= protocolFee;
                
                        // Keep delta the same
                        newDelta = delta;
                
                        // If we reached here, no math errors
                        error = Error.OK;
                    }
                }