ETH Price: $2,903.62 (+2.90%)
 

Overview

TokenID

1985

Total Transfers

-

Market

Onchain Market Cap

$0.00

Circulating Supply Market Cap

-
Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
# Exchange Pair Price  24H Volume % Volume

Contract Source Code Verified (Exact Match)

Contract Name:
Wheyfu

Compiler Version
v0.8.16+commit.07a7930e

Optimization Enabled:
Yes with 1000 runs

Other Settings:
default evmVersion
File 1 of 50 : Wheyfu.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import {ERC721, ERC721TokenReceiver} from "solmate/tokens/ERC721.sol";
import {ERC721A} from "ERC721A/ERC721A.sol";
import {Owned} from "solmate/auth/Owned.sol";
import {LSSVMPairMissingEnumerableETH} from "lssvm/LSSVMPairMissingEnumerableETH.sol";
import {PuttyV2} from "putty-v2/PuttyV2.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";

import {MintBurnToken} from "./lib/MintBurnToken.sol";
import {OptionBonding} from "./OptionBonding.sol";
import {FeeBonding} from "./FeeBonding.sol";

/**
 * @notice hiya! ~~ welcome to wheyfus :3 ~
 * General overview:
 *
 * Wheyfus is an NFT collection with a max supply of 30,000.
 * 9000 is distributed via a free mint.
 * 18000 is reserved for yield farming (distributed over 900 days).
 * 3000 is minted to the team.
 *
 * Yield farming works by LP'ing into a shared xyk curve sudo pool then locking up the LP tokens for a fixed bond duration.
 * The duration is variable (0 days, 30 days, 90 days etc.). The longer you bond for, the higher your yield boost.
 * The bonds yield call option tokens which can be converted 1:1 for putty call options on wheyfus. Each call option
 * expires in 5 years and has a strike of 0.1 eth.
 *
 * There is also LP fee farming. This works similarly by LP'ing into a shared xyk curve sudo pool and also locking up LP
 * tokens for a fixed bond duration. Except this time, instead of yield farming call option tokens, you yield farm the fees
 * generated from the sudoswap pool. Fees are distributed pro rata based on the amount already staked and your yield boost.
 *
 * So there are 2 farms. 1 yielding call option tokens and 1 yielding sudoswap LP fees.
 *
 * note: The yield from the LP farm is boosted by the yield from the staked LP tokens in the call option farm. This is because
 * LPs in the call option farm don't receive any LP fees; instead opting for call option yield.
 *
 * thanks for reading *blush* uwu
 *
 * @author 0xacedia
 */
contract Wheyfu is FeeBonding, OptionBonding, ERC721, ERC721TokenReceiver {
    /// @notice The max supply of wheyfus.
    /// @dev 18k for yield farming, 9k for free mint, 3k for team.
    uint256 public constant MAX_SUPPLY = 30_000;

    /// @notice The total minted supply.
    uint256 public totalSupply;

    /// @notice Whether or not the whitelist can be modified.
    bool public closedWhitelist = false;

    /// @notice The total whitelisted supply.
    /// @dev This should never exceed the max supply.
    uint256 public whitelistedSupply;

    /// @notice Mapping of address -> whitelist amount.
    mapping(address => uint256) public mintWhitelist;

    LSSVMPairMissingEnumerableETH public pair;
    ERC721 public tokenUri;

    /**
     * @notice Emitted when liquidity is added.
     * @param tokenAmount The amount of eth that was added.
     * @param nftAmount The amount of nfts that were added.
     * @param shares The amount of shares that were minted.
     */
    event AddLiquidity(uint256 tokenAmount, uint256 nftAmount, uint256 shares);

    /**
     * @notice Emitted when liquidity is removed.
     * @param tokenAmount The amount of eth that was removed.
     * @param nftAmount The amount of nfts that were removed.
     * @param shares The amount of shares that were burned.
     */
    event RemoveLiquidity(uint256 tokenAmount, uint256 nftAmount, uint256 shares);

    // solhint-disable-next-line
    receive() external payable {}

    constructor(address _lpToken, address _callOptionToken, address _putty, address _weth)
        ERC721("Wheyfus anonymous :3", "UwU")
        OptionBonding(_lpToken, _callOptionToken, _putty, _weth)
        FeeBonding(_lpToken)
    {}

    /**
     * @notice Sets the sudoswap pool address.
     * @param _pair The sudoswap pool.
     */
    function setPair(address payable _pair) public onlyOwner {
        require(address(pair) == address(0), "Pair already set");

        pair = LSSVMPairMissingEnumerableETH(_pair);
        _setPair(_pair);
    }

    /**
     * ~~~~~~~~~~~~~~~
     * ADMIN FUNCTIONS
     * ~~~~~~~~~~~~~~~
     */

    /**
     * @notice Sets the tokenURI contract.
     * @param _tokenUri The tokenURI contract.
     */
    function setTokenUri(address _tokenUri) public onlyOwner {
        tokenUri = ERC721(_tokenUri);
    }

    /**
     * @notice Closes the whitelist.
     * @dev After this point the whitelist can no longer be modified.
     */
    function closeWhitelist() public onlyOwner {
        closedWhitelist = true;
    }

    /**
     * ~~~~~~~~~~~~~~~~~
     * MINTING FUNCTIONS
     * ~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Whitelists a minter so that they can mint a certain amount.
     * @param target The address to whitelist.
     * @param amount The amount to whitelist them for.
     */
    function whitelistMinter(address target, uint256 amount) public onlyOwner {
        // check whitelist is not closed
        require(!closedWhitelist, "Whitelist has been closed");

        // increment/decrement the new whitelistedSupply
        uint256 oldAmount = mintWhitelist[target];
        whitelistedSupply -= oldAmount;
        whitelistedSupply += amount;

        // check whitelisted supply is less than the max supply
        require(whitelistedSupply <= MAX_SUPPLY, "Max supply already reached");

        // save the new whitelist amount to the target
        mintWhitelist[target] = amount;
    }

    /**
     * @notice Mints a certain amount of nfts to msg.sender.
     * @param amount The amount of nfts to mint.
     */
    function mint(uint256 amount) public returns (uint256) {
        mintTo(amount, msg.sender);

        return totalSupply;
    }

    /**
     * @notice Mints a certain amount of nfts to an address.
     * @param amount The amount of nfts to mint.
     * @param to Who to mint the nfts to.
     */
    function mintTo(uint256 amount, address to) public returns (uint256) {
        return _mintTo(amount, to, msg.sender);
    }

    /**
     * @notice Mints a certain amount of nfts to an address from an account.
     * @param amount The amount of nfts to mint.
     * @param to Who to mint the nfts to.
     * @param from Who to mint the nfts from.
     */
    function _mintTo(uint256 amount, address to, address from) internal returns (uint256) {
        // check that the from account is whitelisted to mint the amount
        require(mintWhitelist[from] >= amount, "Not whitelisted for this amount");

        // loop through and mint N nfts to the to account
        for (uint256 i = totalSupply; i < totalSupply + amount; i++) {
            _mint(to, i + 1);
        }

        // increase the balance of the to account
        _balanceOf[to] += amount;

        // increase the total supply
        totalSupply += amount;

        // decrease the whitelisted amount from the from account
        mintWhitelist[from] -= amount;

        return totalSupply;
    }

    /**
     * @notice Mints a particular nft to an account.
     * @param to Who to mint the nft to.
     * @param id The id of the nft to mint.
     */
    function _mint(address to, uint256 id) internal override {
        require(to != address(0), "INVALID_RECIPIENT");
        require(_ownerOf[id] == address(0), "ALREADY_MINTED");

        _ownerOf[id] = to;

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

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~
     * SUDOSWAP POOL FUNCTIONS
     * ~~~~~~~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Adds liquidity to the shared sudoswap pool and mints lp tokens.
     * @dev Updates the sudo reserves.
     * @param tokenIds The tokenIds of the nfts to send to the sudoswap pool.
     * @param minPrice The min price to lp at.
     * @param maxPrice The max price to lp at.
     */
    function addLiquidity(uint256[] calldata tokenIds, uint256 minPrice, uint256 maxPrice)
        public
        payable
        returns (uint256 shares)
    {
        // check current price is in between min and max
        uint256 _tokenReserves = tokenReserves();
        uint256 _nftReserves = nftReserves();
        uint256 _price = _tokenReserves > 0 && _nftReserves > 0 ? _tokenReserves / _nftReserves : 0;
        require(_price <= maxPrice && _price >= minPrice, "Price slippage");

        // check min eth amount was sent
        require(msg.value > 0.0001 ether, "Must send at least 0.0001 ether");

        // update sudoswap reserves
        _updateReserves(_tokenReserves + msg.value, _nftReserves + tokenIds.length);

        // mint shares to sender
        uint256 _totalSupply = lpToken.totalSupply();
        shares =
            _totalSupply == 0
            ? msg.value * tokenIds.length
            : Math.min((_totalSupply * msg.value) / _tokenReserves, (_totalSupply * tokenIds.length) / _nftReserves);
        lpToken.mint(msg.sender, shares);

        // deposit tokens to sudoswap pool
        for (uint256 i = 0; i < tokenIds.length;) {
            _safeTransferFrom(msg.sender, address(pair), tokenIds[i]);

            unchecked {
                i++;
            }
        }

        // deposit eth to sudoswap pool
        SafeTransferLib.safeTransferETH(address(pair), msg.value);

        emit AddLiquidity(msg.value, tokenIds.length, shares);
    }

    /**
     * @notice Removes liquidity from the shared sudoswap pool and burns lp tokens.
     * @dev Updates the sudo reserves.
     * @param tokenIds The tokenIds of the nfts to remove from the sudoswap pool.
     * @param minPrice The min price to remove the lp at.
     * @param maxPrice The max price to remove lp at.
     */
    function removeLiquidity(uint256[] calldata tokenIds, uint256 minPrice, uint256 maxPrice) public {
        // check current price is in between min and max
        uint256 _price = price();
        require(_price <= maxPrice && _price >= minPrice, "Price slippage");

        // update sudoswap reserves
        uint256 _tokenReserves = tokenReserves();
        uint256 _nftReserves = nftReserves();
        uint256 tokenAmount = (_tokenReserves * tokenIds.length) / _nftReserves;
        _updateReserves(_tokenReserves - tokenAmount, _nftReserves - tokenIds.length);

        // withdraw liquidity
        pair.withdrawETH(tokenAmount);
        pair.withdrawERC721(IERC721(address(this)), tokenIds);

        // burn shares
        uint256 _totalSupply = lpToken.totalSupply();
        uint256 shares = (_totalSupply * tokenIds.length) / _nftReserves;
        lpToken.burn(msg.sender, shares);

        // send tokens to user
        for (uint256 i = 0; i < tokenIds.length;) {
            _safeTransferFrom(address(this), msg.sender, tokenIds[i]);

            unchecked {
                i++;
            }
        }

        // send eth to user
        SafeTransferLib.safeTransferETH(msg.sender, tokenAmount);

        emit RemoveLiquidity(tokenAmount, tokenIds.length, shares);
    }

    /**
     * @notice Getter for the token reserves in the sudoswap pool.
     */
    function tokenReserves() public view returns (uint256) {
        return pair.spotPrice();
    }

    /**
     * @notice Getter for the nft reserves in the sudoswap pool.
     */
    function nftReserves() public view returns (uint256) {
        return pair.delta();
    }

    /**
     * @notice Getter for the price in the sudoswap pool.
     */
    function price() public view returns (uint256) {
        uint256 _tokenReserves = tokenReserves();
        uint256 _nftReserves = nftReserves();

        return _tokenReserves > 0 && _nftReserves > 0 ? _tokenReserves / _nftReserves : 0;
    }

    /**
     * @notice Updates the sudoswap pool's virtual reserves.
     * @param _tokenReserves The new token reserves.
     * @param _nftReserves The new nft reserves.
     */
    function _updateReserves(uint256 _tokenReserves, uint256 _nftReserves) internal {
        pair.changeSpotPrice(uint128(_tokenReserves));
        pair.changeDelta(uint128(_nftReserves));
    }

    /**
     * ~~~~~~~~~~~~~~~~~~~
     * PERIPHERY FUNCTIONS
     * ~~~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Wrapper around addLiquidity() and optionStake()
     * @param tokenIds The tokenIds of the nfts to send to the sudoswap pool.
     * @param minPrice The min price to lp at.
     * @param maxPrice The max price to lp at.
     * @param termIndex Index into the terms array which tells how long to stake for.
     */
    function addLiquidityAndOptionStake(
        uint256[] calldata tokenIds,
        uint256 minPrice,
        uint256 maxPrice,
        uint256 termIndex
    )
        public
        payable
        returns (uint256 tokenId)
    {
        uint256 shares = addLiquidity(tokenIds, minPrice, maxPrice);
        tokenId = optionStake(uint128(shares), termIndex);
    }

    /**
     * @notice Wrapper around addLiquidity() and feeStake()
     * @param tokenIds The tokenIds of the nfts to send to the sudoswap pool.
     * @param minPrice The min price to lp at.
     * @param maxPrice The max price to lp at.
     * @param termIndex Index into the terms array which tells how long to stake for.
     */
    function addLiquidityAndFeeStake(uint256[] calldata tokenIds, uint256 minPrice, uint256 maxPrice, uint256 termIndex)
        public
        payable
        returns (uint256 tokenId)
    {
        uint256 shares = addLiquidity(tokenIds, minPrice, maxPrice);
        tokenId = feeStake(uint128(shares), termIndex);
    }

    /**
     * ~~~~~~~~~~~~~~~~~~
     * OVERRIDE FUNCTIONS
     * ~~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Tells putty that we support the handler interface.
     */
    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Internal _safeTransferFrom() that ignores the authorized checks.
     * Skips checking that from == msg.sender, approvals etc.
     */
    function _safeTransferFrom(address from, address to, uint256 id) internal virtual {
        require(from == _ownerOf[id], "WRONG_FROM");

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

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

            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        delete getApproved[id];

        emit Transfer(from, to, id);

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

    /**
     * @dev safeTransferFrom() skips transfers if `mintingOption` is set to true.
     * And also skips transfers if putty is trying to transfer on exercise.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public override {
        // if minting an option then no need to transfer
        // (means that we need to mint onExercise instead)
        if (mintingOption == 2) {
            return;
        }

        // if putty is trying to send tokens for a tokenId greater than max supply
        // then mint tokens. the only way this should ever be reachable is if the bonding contract
        // minted an option. otherwise putty should never have received tokens with ids greater
        // than the max supply. When the call option is exercised putty will call this function. it
        // mints nfts to the exerciser. Should only be callable by putty. We defer the mint to here
        // instead of on call option creation to save gas.
        if (from == address(putty) && tokenId > MAX_SUPPLY && msg.sender == address(putty)) {
            _mintTo(type(uint256).max - tokenId, to, address(putty));
            return;
        }

        super.safeTransferFrom(from, to, tokenId);
    }

    /**
     * @notice Returns the tokenURI of a particular token.
     * This method can be "edited" by changing the tokenUri contract variable.
     */
    function tokenURI(uint256 id) public view virtual override returns (string memory) {
        return tokenUri.tokenURI(id);
    }
}

File 2 of 50 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`.
        // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
        // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
        // Using an algorithm similar to the msb computation, we are able to compute `result = 2**(k/2)` which is a
        // good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1;
        uint256 x = a;
        if (x >> 128 > 0) {
            x >>= 128;
            result <<= 64;
        }
        if (x >> 64 > 0) {
            x >>= 64;
            result <<= 32;
        }
        if (x >> 32 > 0) {
            x >>= 32;
            result <<= 16;
        }
        if (x >> 16 > 0) {
            x >>= 16;
            result <<= 8;
        }
        if (x >> 8 > 0) {
            x >>= 8;
            result <<= 4;
        }
        if (x >> 4 > 0) {
            x >>= 4;
            result <<= 2;
        }
        if (x >> 2 > 0) {
            result <<= 1;
        }

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

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

File 3 of 50 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

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

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

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

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

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

pragma solidity ^0.8.0;

import "../IERC721.sol";

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

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

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

File 5 of 50 : ERC721.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

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

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

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

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

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

    string public name;

    string public symbol;

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

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

    mapping(uint256 => address) internal _ownerOf;

    mapping(address => uint256) internal _balanceOf;

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

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

        return _balanceOf[owner];
    }

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

    mapping(uint256 => address) public getApproved;

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

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

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

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

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

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

        getApproved[id] = spender;

        emit Approval(owner, spender, id);
    }

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

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

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

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

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

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

            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        delete getApproved[id];

        emit Transfer(from, to, id);
    }

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

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

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

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

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

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

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

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

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

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

        _ownerOf[id] = to;

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

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

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

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

        delete _ownerOf[id];

        delete getApproved[id];

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

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

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

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

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

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

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

File 6 of 50 : ERC721A.sol
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.2
// Creator: Chiru Labs

pragma solidity ^0.8.4;

import './IERC721A.sol';

/**
 * @dev Interface of ERC721 token receiver.
 */
interface ERC721A__IERC721Receiver {
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

/**
 * @title ERC721A
 *
 * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
 * Non-Fungible Token Standard, including the Metadata extension.
 * Optimized for lower gas during batch mints.
 *
 * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
 * starting from `_startTokenId()`.
 *
 * Assumptions:
 *
 * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
 * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
 */
contract ERC721A is IERC721A {
    // Reference type for token approval.
    struct TokenApprovalRef {
        address value;
    }

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

    // Mask of an entry in packed address data.
    uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;

    // The bit position of `numberMinted` in packed address data.
    uint256 private constant _BITPOS_NUMBER_MINTED = 64;

    // The bit position of `numberBurned` in packed address data.
    uint256 private constant _BITPOS_NUMBER_BURNED = 128;

    // The bit position of `aux` in packed address data.
    uint256 private constant _BITPOS_AUX = 192;

    // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
    uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;

    // The bit position of `startTimestamp` in packed ownership.
    uint256 private constant _BITPOS_START_TIMESTAMP = 160;

    // The bit mask of the `burned` bit in packed ownership.
    uint256 private constant _BITMASK_BURNED = 1 << 224;

    // The bit position of the `nextInitialized` bit in packed ownership.
    uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;

    // The bit mask of the `nextInitialized` bit in packed ownership.
    uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;

    // The bit position of `extraData` in packed ownership.
    uint256 private constant _BITPOS_EXTRA_DATA = 232;

    // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
    uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;

    // The mask of the lower 160 bits for addresses.
    uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;

    // The maximum `quantity` that can be minted with {_mintERC2309}.
    // This limit is to prevent overflows on the address data entries.
    // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
    // is required to cause an overflow, which is unrealistic.
    uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;

    // The `Transfer` event signature is given by:
    // `keccak256(bytes("Transfer(address,address,uint256)"))`.
    bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

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

    // The next token ID to be minted.
    uint256 private _currentIndex;

    // The number of tokens burned.
    uint256 private _burnCounter;

    // 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 {_packedOwnershipOf} implementation for details.
    //
    // Bits Layout:
    // - [0..159]   `addr`
    // - [160..223] `startTimestamp`
    // - [224]      `burned`
    // - [225]      `nextInitialized`
    // - [232..255] `extraData`
    mapping(uint256 => uint256) private _packedOwnerships;

    // Mapping owner address to address data.
    //
    // Bits Layout:
    // - [0..63]    `balance`
    // - [64..127]  `numberMinted`
    // - [128..191] `numberBurned`
    // - [192..255] `aux`
    mapping(address => uint256) private _packedAddressData;

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

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

    // =============================================================
    //                          CONSTRUCTOR
    // =============================================================

    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _currentIndex = _startTokenId();
    }

    // =============================================================
    //                   TOKEN COUNTING OPERATIONS
    // =============================================================

    /**
     * @dev Returns the starting token ID.
     * To change the starting token ID, please override this function.
     */
    function _startTokenId() internal view virtual returns (uint256) {
        return 0;
    }

    /**
     * @dev Returns the next token ID to be minted.
     */
    function _nextTokenId() internal view virtual returns (uint256) {
        return _currentIndex;
    }

    /**
     * @dev Returns the total number of tokens in existence.
     * Burned tokens will reduce the count.
     * To get the total number of tokens minted, please see {_totalMinted}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        // Counter underflow is impossible as _burnCounter cannot be incremented
        // more than `_currentIndex - _startTokenId()` times.
        unchecked {
            return _currentIndex - _burnCounter - _startTokenId();
        }
    }

    /**
     * @dev Returns the total amount of tokens minted in the contract.
     */
    function _totalMinted() internal view virtual returns (uint256) {
        // Counter underflow is impossible as `_currentIndex` does not decrement,
        // and it is initialized to `_startTokenId()`.
        unchecked {
            return _currentIndex - _startTokenId();
        }
    }

    /**
     * @dev Returns the total number of tokens burned.
     */
    function _totalBurned() internal view virtual returns (uint256) {
        return _burnCounter;
    }

    // =============================================================
    //                    ADDRESS DATA OPERATIONS
    // =============================================================

    /**
     * @dev Returns the number of tokens in `owner`'s account.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        if (owner == address(0)) revert BalanceQueryForZeroAddress();
        return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
    }

    /**
     * Returns the number of tokens minted by `owner`.
     */
    function _numberMinted(address owner) internal view returns (uint256) {
        return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
    }

    /**
     * Returns the number of tokens burned by or on behalf of `owner`.
     */
    function _numberBurned(address owner) internal view returns (uint256) {
        return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
    }

    /**
     * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
     */
    function _getAux(address owner) internal view returns (uint64) {
        return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
    }

    /**
     * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
     * If there are multiple variables, please pack them into a uint64.
     */
    function _setAux(address owner, uint64 aux) internal virtual {
        uint256 packed = _packedAddressData[owner];
        uint256 auxCasted;
        // Cast `aux` with assembly to avoid redundant masking.
        assembly {
            auxCasted := aux
        }
        packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
        _packedAddressData[owner] = packed;
    }

    // =============================================================
    //                            IERC165
    // =============================================================

    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30000 gas.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        // The interface IDs are constants representing the first 4 bytes
        // of the XOR of all function selectors in the interface.
        // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
        // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
        return
            interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
            interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
            interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
    }

    // =============================================================
    //                        IERC721Metadata
    // =============================================================

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

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        if (!_exists(tokenId)) revert URIQueryForNonexistentToken();

        string memory baseURI = _baseURI();
        return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
    }

    /**
     * @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, it can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return '';
    }

    // =============================================================
    //                     OWNERSHIPS OPERATIONS
    // =============================================================

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        return address(uint160(_packedOwnershipOf(tokenId)));
    }

    /**
     * @dev Gas spent here starts off proportional to the maximum mint batch size.
     * It gradually moves to O(1) as tokens get transferred around over time.
     */
    function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
        return _unpackedOwnership(_packedOwnershipOf(tokenId));
    }

    /**
     * @dev Returns the unpacked `TokenOwnership` struct at `index`.
     */
    function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
        return _unpackedOwnership(_packedOwnerships[index]);
    }

    /**
     * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
     */
    function _initializeOwnershipAt(uint256 index) internal virtual {
        if (_packedOwnerships[index] == 0) {
            _packedOwnerships[index] = _packedOwnershipOf(index);
        }
    }

    /**
     * Returns the packed ownership data of `tokenId`.
     */
    function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
        uint256 curr = tokenId;

        unchecked {
            if (_startTokenId() <= curr)
                if (curr < _currentIndex) {
                    uint256 packed = _packedOwnerships[curr];
                    // If not burned.
                    if (packed & _BITMASK_BURNED == 0) {
                        // Invariant:
                        // There will always be an initialized ownership slot
                        // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                        // before an unintialized ownership slot
                        // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                        // Hence, `curr` will not underflow.
                        //
                        // We can directly compare the packed value.
                        // If the address is zero, packed will be zero.
                        while (packed == 0) {
                            packed = _packedOwnerships[--curr];
                        }
                        return packed;
                    }
                }
        }
        revert OwnerQueryForNonexistentToken();
    }

    /**
     * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
     */
    function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
        ownership.addr = address(uint160(packed));
        ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
        ownership.burned = packed & _BITMASK_BURNED != 0;
        ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
    }

    /**
     * @dev Packs ownership data into a single uint256.
     */
    function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
        assembly {
            // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
            owner := and(owner, _BITMASK_ADDRESS)
            // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
            result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
        }
    }

    /**
     * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
     */
    function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
        // For branchless setting of the `nextInitialized` flag.
        assembly {
            // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
            result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
        }
    }

    // =============================================================
    //                      APPROVAL OPERATIONS
    // =============================================================

    /**
     * @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) public virtual override {
        address owner = ownerOf(tokenId);

        if (_msgSenderERC721A() != owner)
            if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                revert ApprovalCallerNotOwnerNorApproved();
            }

        _tokenApprovals[tokenId].value = to;
        emit Approval(owner, to, tokenId);
    }

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();

        return _tokenApprovals[tokenId].value;
    }

    /**
     * @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) public virtual override {
        if (operator == _msgSenderERC721A()) revert ApproveToCaller();

        _operatorApprovals[_msgSenderERC721A()][operator] = approved;
        emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
    }

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

    /**
     * @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. See {_mint}.
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return
            _startTokenId() <= tokenId &&
            tokenId < _currentIndex && // If within bounds,
            _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
    }

    /**
     * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
     */
    function _isSenderApprovedOrOwner(
        address approvedAddress,
        address owner,
        address msgSender
    ) private pure returns (bool result) {
        assembly {
            // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
            owner := and(owner, _BITMASK_ADDRESS)
            // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
            msgSender := and(msgSender, _BITMASK_ADDRESS)
            // `msgSender == owner || msgSender == approvedAddress`.
            result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
        }
    }

    /**
     * @dev Returns the storage slot and value for the approved address of `tokenId`.
     */
    function _getApprovedSlotAndAddress(uint256 tokenId)
        private
        view
        returns (uint256 approvedAddressSlot, address approvedAddress)
    {
        TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
        // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
        assembly {
            approvedAddressSlot := tokenApproval.slot
            approvedAddress := sload(approvedAddressSlot)
        }
    }

    // =============================================================
    //                      TRANSFER OPERATIONS
    // =============================================================

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *
     * 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
    ) public virtual override {
        uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

        if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();

        (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);

        // The nested ifs save around 20+ gas over a compound boolean condition.
        if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
            if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();

        if (to == address(0)) revert TransferToZeroAddress();

        _beforeTokenTransfers(from, to, tokenId, 1);

        // Clear approvals from the previous owner.
        assembly {
            if approvedAddress {
                // This is equivalent to `delete _tokenApprovals[tokenId]`.
                sstore(approvedAddressSlot, 0)
            }
        }

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
        unchecked {
            // We can directly increment and decrement the balances.
            --_packedAddressData[from]; // Updates: `balance -= 1`.
            ++_packedAddressData[to]; // Updates: `balance += 1`.

            // Updates:
            // - `address` to the next owner.
            // - `startTimestamp` to the timestamp of transfering.
            // - `burned` to `false`.
            // - `nextInitialized` to `true`.
            _packedOwnerships[tokenId] = _packOwnershipData(
                to,
                _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
            );

            // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
            if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                uint256 nextTokenId = tokenId + 1;
                // If the next slot's address is zero and not burned (i.e. packed value is zero).
                if (_packedOwnerships[nextTokenId] == 0) {
                    // If the next slot is within bounds.
                    if (nextTokenId != _currentIndex) {
                        // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                        _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                    }
                }
            }
        }

        emit Transfer(from, to, tokenId);
        _afterTokenTransfers(from, to, tokenId, 1);
    }

    /**
     * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, '');
    }

    /**
     * @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 memory _data
    ) public virtual override {
        transferFrom(from, to, tokenId);
        if (to.code.length != 0)
            if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                revert TransferToNonERC721ReceiverImplementer();
            }
    }

    /**
     * @dev Hook that is called before a set of serially-ordered token IDs
     * are about to be transferred. This includes minting.
     * And also called before burning one token.
     *
     * `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`.
     * - When `to` is zero, `tokenId` will be burned by `from`.
     * - `from` and `to` are never both zero.
     */
    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.
     * And also called after one token has been burned.
     *
     * `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` has been
     * transferred to `to`.
     * - When `from` is zero, `tokenId` has been minted for `to`.
     * - When `to` is zero, `tokenId` has been burned by `from`.
     * - `from` and `to` are never both zero.
     */
    function _afterTokenTransfers(
        address from,
        address to,
        uint256 startTokenId,
        uint256 quantity
    ) internal virtual {}

    /**
     * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
     *
     * `from` - Previous owner of the given token ID.
     * `to` - Target address that will receive the token.
     * `tokenId` - Token ID to be transferred.
     * `_data` - Optional data to send along with the call.
     *
     * Returns whether the call correctly returned the expected magic value.
     */
    function _checkContractOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
            bytes4 retval
        ) {
            return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
        } catch (bytes memory reason) {
            if (reason.length == 0) {
                revert TransferToNonERC721ReceiverImplementer();
            } else {
                assembly {
                    revert(add(32, reason), mload(reason))
                }
            }
        }
    }

    // =============================================================
    //                        MINT OPERATIONS
    // =============================================================

    /**
     * @dev Mints `quantity` tokens and transfers them to `to`.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `quantity` must be greater than 0.
     *
     * Emits a {Transfer} event for each mint.
     */
    function _mint(address to, uint256 quantity) internal virtual {
        uint256 startTokenId = _currentIndex;
        if (quantity == 0) revert MintZeroQuantity();

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        // Overflows are incredibly unrealistic.
        // `balance` and `numberMinted` have a maximum limit of 2**64.
        // `tokenId` has a maximum limit of 2**256.
        unchecked {
            // Updates:
            // - `balance += quantity`.
            // - `numberMinted += quantity`.
            //
            // We can directly add to the `balance` and `numberMinted`.
            _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);

            // Updates:
            // - `address` to the owner.
            // - `startTimestamp` to the timestamp of minting.
            // - `burned` to `false`.
            // - `nextInitialized` to `quantity == 1`.
            _packedOwnerships[startTokenId] = _packOwnershipData(
                to,
                _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
            );

            uint256 toMasked;
            uint256 end = startTokenId + quantity;

            // Use assembly to loop and emit the `Transfer` event for gas savings.
            // The duplicated `log4` removes an extra check and reduces stack juggling.
            // The assembly, together with the surrounding Solidity code, have been
            // delicately arranged to nudge the compiler into producing optimized opcodes.
            assembly {
                // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                toMasked := and(to, _BITMASK_ADDRESS)
                // Emit the `Transfer` event.
                log4(
                    0, // Start of data (0, since no data).
                    0, // End of data (0, since no data).
                    _TRANSFER_EVENT_SIGNATURE, // Signature.
                    0, // `address(0)`.
                    toMasked, // `to`.
                    startTokenId // `tokenId`.
                )

                for {
                    let tokenId := add(startTokenId, 1)
                } iszero(eq(tokenId, end)) {
                    tokenId := add(tokenId, 1)
                } {
                    // Emit the `Transfer` event. Similar to above.
                    log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                }
            }
            if (toMasked == 0) revert MintToZeroAddress();

            _currentIndex = end;
        }
        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }

    /**
     * @dev Mints `quantity` tokens and transfers them to `to`.
     *
     * This function is intended for efficient minting only during contract creation.
     *
     * It emits only one {ConsecutiveTransfer} as defined in
     * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
     * instead of a sequence of {Transfer} event(s).
     *
     * Calling this function outside of contract creation WILL make your contract
     * non-compliant with the ERC721 standard.
     * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
     * {ConsecutiveTransfer} event is only permissible during contract creation.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `quantity` must be greater than 0.
     *
     * Emits a {ConsecutiveTransfer} event.
     */
    function _mintERC2309(address to, uint256 quantity) internal virtual {
        uint256 startTokenId = _currentIndex;
        if (to == address(0)) revert MintToZeroAddress();
        if (quantity == 0) revert MintZeroQuantity();
        if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
        unchecked {
            // Updates:
            // - `balance += quantity`.
            // - `numberMinted += quantity`.
            //
            // We can directly add to the `balance` and `numberMinted`.
            _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);

            // Updates:
            // - `address` to the owner.
            // - `startTimestamp` to the timestamp of minting.
            // - `burned` to `false`.
            // - `nextInitialized` to `quantity == 1`.
            _packedOwnerships[startTokenId] = _packOwnershipData(
                to,
                _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
            );

            emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);

            _currentIndex = startTokenId + quantity;
        }
        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }

    /**
     * @dev Safely mints `quantity` tokens and transfers them to `to`.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement
     * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
     * - `quantity` must be greater than 0.
     *
     * See {_mint}.
     *
     * Emits a {Transfer} event for each mint.
     */
    function _safeMint(
        address to,
        uint256 quantity,
        bytes memory _data
    ) internal virtual {
        _mint(to, quantity);

        unchecked {
            if (to.code.length != 0) {
                uint256 end = _currentIndex;
                uint256 index = end - quantity;
                do {
                    if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                        revert TransferToNonERC721ReceiverImplementer();
                    }
                } while (index < end);
                // Reentrancy protection.
                if (_currentIndex != end) revert();
            }
        }
    }

    /**
     * @dev Equivalent to `_safeMint(to, quantity, '')`.
     */
    function _safeMint(address to, uint256 quantity) internal virtual {
        _safeMint(to, quantity, '');
    }

    // =============================================================
    //                        BURN OPERATIONS
    // =============================================================

    /**
     * @dev Equivalent to `_burn(tokenId, false)`.
     */
    function _burn(uint256 tokenId) internal virtual {
        _burn(tokenId, false);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
        uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

        address from = address(uint160(prevOwnershipPacked));

        (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);

        if (approvalCheck) {
            // The nested ifs save around 20+ gas over a compound boolean condition.
            if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
        }

        _beforeTokenTransfers(from, address(0), tokenId, 1);

        // Clear approvals from the previous owner.
        assembly {
            if approvedAddress {
                // This is equivalent to `delete _tokenApprovals[tokenId]`.
                sstore(approvedAddressSlot, 0)
            }
        }

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
        unchecked {
            // Updates:
            // - `balance -= 1`.
            // - `numberBurned += 1`.
            //
            // We can directly decrement the balance, and increment the number burned.
            // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
            _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;

            // Updates:
            // - `address` to the last owner.
            // - `startTimestamp` to the timestamp of burning.
            // - `burned` to `true`.
            // - `nextInitialized` to `true`.
            _packedOwnerships[tokenId] = _packOwnershipData(
                from,
                (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
            );

            // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
            if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                uint256 nextTokenId = tokenId + 1;
                // If the next slot's address is zero and not burned (i.e. packed value is zero).
                if (_packedOwnerships[nextTokenId] == 0) {
                    // If the next slot is within bounds.
                    if (nextTokenId != _currentIndex) {
                        // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                        _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                    }
                }
            }
        }

        emit Transfer(from, address(0), tokenId);
        _afterTokenTransfers(from, address(0), tokenId, 1);

        // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
        unchecked {
            _burnCounter++;
        }
    }

    // =============================================================
    //                     EXTRA DATA OPERATIONS
    // =============================================================

    /**
     * @dev Directly sets the extra data for the ownership data `index`.
     */
    function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
        uint256 packed = _packedOwnerships[index];
        if (packed == 0) revert OwnershipNotInitializedForExtraData();
        uint256 extraDataCasted;
        // Cast `extraData` with assembly to avoid redundant masking.
        assembly {
            extraDataCasted := extraData
        }
        packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
        _packedOwnerships[index] = packed;
    }

    /**
     * @dev Called during each token transfer to set the 24bit `extraData` field.
     * Intended to be overridden by the cosumer contract.
     *
     * `previousExtraData` - the value of `extraData` before transfer.
     *
     * 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`.
     * - When `to` is zero, `tokenId` will be burned by `from`.
     * - `from` and `to` are never both zero.
     */
    function _extraData(
        address from,
        address to,
        uint24 previousExtraData
    ) internal view virtual returns (uint24) {}

    /**
     * @dev Returns the next extra data for the packed ownership data.
     * The returned result is shifted into position.
     */
    function _nextExtraData(
        address from,
        address to,
        uint256 prevOwnershipPacked
    ) private view returns (uint256) {
        uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
        return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
    }

    // =============================================================
    //                       OTHER OPERATIONS
    // =============================================================

    /**
     * @dev Returns the message sender (defaults to `msg.sender`).
     *
     * If you are writing GSN compatible contracts, you need to override this function.
     */
    function _msgSenderERC721A() internal view virtual returns (address) {
        return msg.sender;
    }

    /**
     * @dev Converts a uint256 to its ASCII string decimal representation.
     */
    function _toString(uint256 value) internal pure virtual returns (string memory str) {
        assembly {
            // The maximum value of a uint256 contains 78 digits (1 byte per digit),
            // but we allocate 0x80 bytes to keep the free memory pointer 32-byte word aligned.
            // We will need 1 32-byte word to store the length,
            // and 3 32-byte words to store a maximum of 78 digits. Total: 0x20 + 3 * 0x20 = 0x80.
            str := add(mload(0x40), 0x80)
            // Update the free memory pointer to allocate.
            mstore(0x40, str)

            // Cache the end of the memory to calculate the length later.
            let end := str

            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            // prettier-ignore
            for { let temp := value } 1 {} {
                str := sub(str, 1)
                // Write the character to the pointer.
                // The ASCII index of the '0' character is 48.
                mstore8(str, add(48, mod(temp, 10)))
                // Keep dividing `temp` until zero.
                temp := div(temp, 10)
                // prettier-ignore
                if iszero(temp) { break }
            }

            let length := sub(end, str)
            // Move the pointer 32 bytes leftwards to make room for the length.
            str := sub(str, 0x20)
            // Store the length.
            mstore(str, length)
        }
    }
}

File 7 of 50 : Owned.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OwnerUpdated(address indexed user, address indexed newOwner);

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

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

    constructor(address _owner) {
        owner = _owner;

        emit OwnerUpdated(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

    function setOwner(address newOwner) public virtual onlyOwner {
        owner = newOwner;

        emit OwnerUpdated(msg.sender, newOwner);
    }
}

File 8 of 50 : LSSVMPairMissingEnumerableETH.sol
// 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;
    }
}

File 9 of 50 : PuttyV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

/**

    ██████╗ ██╗   ██╗████████╗████████╗██╗   ██╗    ██╗   ██╗██████╗ 
    ██╔══██╗██║   ██║╚══██╔══╝╚══██╔══╝╚██╗ ██╔╝    ██║   ██║╚════██╗
    ██████╔╝██║   ██║   ██║      ██║    ╚████╔╝     ██║   ██║ █████╔╝
    ██╔═══╝ ██║   ██║   ██║      ██║     ╚██╔╝      ╚██╗ ██╔╝██╔═══╝ 
    ██║     ╚██████╔╝   ██║      ██║      ██║        ╚████╔╝ ███████╗
    ╚═╝      ╚═════╝    ╚═╝      ╚═╝      ╚═╝         ╚═══╝  ╚══════╝
    
                                
            _..._               
          .'     '.      _       
         /    .-""-\   _/ \ 
       .-|   /:.   |  |   |   bussin
       |  \  |:.   /.-'-./
       | .-'-;:__.'    =/
       .'=  *=|     _.='
      /   _.  |    ;        minister you satoshi
     ;-.-'|    \   |
    /   | \    _\  _\
    \__/'._;.  ==' ==\
             \    \   |
             /    /   / 
             /-._/-._/
      jgs    \   `\  \
              `-._/._/


    this is a public good.
    by out.eth and tamagoyaki
    
 */

import "./lib/IWETH.sol";

import "openzeppelin/utils/cryptography/SignatureChecker.sol";
import "openzeppelin/utils/cryptography/draft-EIP712.sol";
import "openzeppelin/utils/Strings.sol";
import "openzeppelin/utils/introspection/ERC165Checker.sol";
import "openzeppelin/access/Ownable.sol";
import "solmate/utils/SafeTransferLib.sol";
import "solmate/tokens/ERC721.sol";

import "./PuttyV2Nft.sol";
import "./PuttyV2Handler.sol";

/**
    @title PuttyV2
    @author out.eth
    @notice An otc erc721 and erc20 option market.
 */
contract PuttyV2 is PuttyV2Nft, EIP712("Putty", "2.0"), ERC721TokenReceiver, Ownable {
    /* ~~~ TYPES ~~~ */

    using SafeTransferLib for ERC20;

    /**
        @notice ERC20 asset details.
        @param token The token address for the erc20 asset.
        @param tokenAmount The amount of erc20 tokens.
     */
    struct ERC20Asset {
        address token;
        uint256 tokenAmount;
    }

    /**
        @notice ERC721 asset details.
        @param token The token address for the erc721 asset.
        @param tokenId The token id of the erc721 assset.
     */
    struct ERC721Asset {
        address token;
        uint256 tokenId;
    }

    /**
        @notice Order details.
        @param maker The maker of the order.
        @param isCall Whether or not the order is for a call or put option.
        @param isLong Whether or not the order is long or short.
        @param baseAsset The erc20 contract to use for the strike and premium.
        @param strike The strike amount.
        @param premium The premium amount.
        @param duration The duration of the option contract (in seconds).
        @param expiration The timestamp after which the order is no longer (unix).
        @param nonce A random number for each order to prevent hash collisions and also check order validity.
        @param whitelist A list of addresses that are allowed to fill this order - if empty then anyone can fill.
        @param floorTokens A list of erc721 contract addresses for the underlying.
        @param erc20Assets A list of erc20 assets for the underlying.
        @param erc721Assets A list of erc721 assets for the underlying.
     */
    struct Order {
        address maker;
        bool isCall;
        bool isLong;
        address baseAsset;
        uint256 strike;
        uint256 premium;
        uint256 duration;
        uint256 expiration;
        uint256 nonce;
        address[] whitelist;
        address[] floorTokens;
        ERC20Asset[] erc20Assets;
        ERC721Asset[] erc721Assets;
    }

    /* ~~~ STATE VARIABLES ~~~ */

    /**
        @dev ERC721Asset type hash used for EIP-712 encoding.
     */
    bytes32 public constant ERC721ASSET_TYPE_HASH = keccak256("ERC721Asset(address token,uint256 tokenId)");

    /**
        @dev ERC20Asset type hash used for EIP-712 encoding.
     */
    bytes32 public constant ERC20ASSET_TYPE_HASH = keccak256("ERC20Asset(address token,uint256 tokenAmount)");

    /**
        @dev ORDER_TYPE_HASH type hash used for EIP-712 encoding.
     */
    bytes32 public constant ORDER_TYPE_HASH =
        keccak256(
            "Order("
            "address maker,"
            "bool isCall,"
            "bool isLong,"
            "address baseAsset,"
            "uint256 strike,"
            "uint256 premium,"
            "uint256 duration,"
            "uint256 expiration,"
            "uint256 nonce,"
            "address[] whitelist,"
            "address[] floorTokens,"
            "ERC20Asset[] erc20Assets,"
            "ERC721Asset[] erc721Assets"
            ")"
            "ERC20Asset(address token,uint256 tokenAmount)"
            "ERC721Asset(address token,uint256 tokenId)"
        );

    /**
        @dev Contract address for Wrapped Ethereum.
     */
    address public immutable weth;

    /**
        @dev baseURI used to generate the tokenURI for PuttyV2 NFTs.
    */
    string public baseURI;

    /**
        @notice Fee rate that is applied on premiums.
    */
    uint256 public fee;

    /**
        @notice Whether or not an order has been cancelled. Maps 
                from orderHash to isCancelled.
    */
    mapping(bytes32 => bool) public cancelledOrders;

    /**
        @notice The current expiration timestamp of a position. Maps 
                from positionId to an expiration unix timestamp.
    */
    mapping(uint256 => uint256) public positionExpirations;

    /**
        @notice Whether or not a position has been exercised. Maps 
                from positionId to isExercised.
    */
    mapping(uint256 => bool) public exercisedPositions;

    /**
        @notice The floor asset token ids for a position. Maps from 
                positionId to floor asset token ids. This should only 
                be set for a long call position in `fillOrder`, or for 
                a short put position in `exercise`.
    */
    mapping(uint256 => uint256[]) public positionFloorAssetTokenIds;

    /**
        @notice The total unclaimed premium fees for each asset.
    */
    mapping(address => uint256) public unclaimedFees;

    /**
        @notice The minimum valid nonce for each address.
    */
    mapping(address => uint256) public minimumValidNonce;

    /* ~~~ EVENTS ~~~ */

    /**
        @notice Emitted when a new base URI is set.
        @param baseURI The new baseURI.
     */
    event NewBaseURI(string baseURI);

    /**
        @notice Emitted when a new fee is set.
        @param fee The new fee.
     */
    event NewFee(uint256 fee);

    /**
        @notice Emitted when fees are withdrawn.
        @param asset The asset which fees are being withdrawn for.
        @param fees The amount of fees that are being withdrawn.
        @param recipient The recipient address for the fees.
     */
    event WithdrewFees(address indexed asset, uint256 fees, address recipient);

    /**
        @notice Emitted when an order is filled.
        @param orderHash The hash of the order that was filled.
        @param floorAssetTokenIds The floor asset token ids that were used.
        @param order The order that was filled.
     */
    event FilledOrder(bytes32 indexed orderHash, uint256[] floorAssetTokenIds, Order order);

    /**
        @notice Emitted when an order is exercised.
        @param orderHash The hash of the order that was exercised.
        @param floorAssetTokenIds The floor asset token ids that were used.
        @param order The order that was exercised.
     */
    event ExercisedOrder(bytes32 indexed orderHash, uint256[] floorAssetTokenIds, Order order);

    /**
        @notice Emitted when an order is withdrawn.
        @param orderHash The hash of the order that was withdrawn.
        @param order The order that was withdrawn.
     */
    event WithdrawOrder(bytes32 indexed orderHash, Order order);

    /**
        @notice Emitted when an order is cancelled.
        @param orderHash The hash of the order that was cancelled.
        @param order The order that was cancelled.
     */
    event CancelledOrder(bytes32 indexed orderHash, Order order);

    /**
        @notice Emitted when a user sets their minimum valid nonce.
        @param minimumValidNonce The new minimum valid nonce.
     */
    event SetMinimumValidNonce(uint256 minimumValidNonce);

    constructor(
        string memory _baseURI,
        uint256 _fee,
        address _weth
    ) {
        require(_weth != address(0), "Must set weth address");

        setBaseURI(_baseURI);
        setFee(_fee);
        weth = _weth;
    }

    /* ~~~ ADMIN FUNCTIONS ~~~ */

    /**
        @notice Sets a new baseURI that is used in the construction
                of the tokenURI for each NFT position. Admin/DAO only.
        @param _baseURI The new base URI to use.
     */
    function setBaseURI(string memory _baseURI) public payable onlyOwner {
        baseURI = _baseURI;

        emit NewBaseURI(_baseURI);
    }

    /**
        @notice Sets a new fee rate that is applied on premiums. The
                fee has a precision of 1 decimal. e.g. 1000 = 100%,
                100 = 10%, 1 = 0.1%. Admin/DAO only.
        @param _fee The new fee rate to use.
     */
    function setFee(uint256 _fee) public payable onlyOwner {
        require(_fee < 30, "fee must be less than 3%");

        fee = _fee;

        emit NewFee(_fee);
    }

    /**
        @notice Withdraws the fees that have been collected from premiums for a particular asset.
        @param asset The asset to collect fees for.
        @param recipient The recipient address for the unclaimed fees.
     */
    function withdrawFees(address asset, address recipient) public payable onlyOwner {
        uint256 fees = unclaimedFees[asset];

        // reset the fees
        unclaimedFees[asset] = 0;

        emit WithdrewFees(asset, fees, recipient);

        // send the fees to the recipient
        ERC20(asset).transfer(recipient, fees);
    }

    /*
        ~~~ MAIN LOGIC FUNCTIONS ~~~

        Standard lifecycle:
            [1] fillOrder()
            [2] exercise()
            [3] withdraw()

            * It is also possible to cancel() an order before fillOrder()
    */

    /**
        @notice Fills an offchain order and settles it onchain. Mints two
                NFTs that represent the long and short position for the order.
        @param order The order to fill.
        @param signature The signature for the order. Signature must recover to order.maker.
        @param floorAssetTokenIds The floor asset token ids to use. Should only be set 
               when filling a long call order.
        @return positionId The id of the position NFT that the msg.sender receives.
     */
    function fillOrder(
        Order memory order,
        bytes calldata signature,
        uint256[] memory floorAssetTokenIds
    ) public payable returns (uint256 positionId) {
        /* ~~~ CHECKS ~~~ */

        bytes32 orderHash = hashOrder(order);

        // check signature is valid using EIP-712
        require(SignatureChecker.isValidSignatureNow(order.maker, orderHash, signature), "Invalid signature");

        // check order is not cancelled
        require(!cancelledOrders[orderHash], "Order has been cancelled");

        // check order nonce is valid
        require(order.nonce >= minimumValidNonce[order.maker], "Nonce is smaller than min");

        // check msg.sender is allowed to fill the order
        require(order.whitelist.length == 0 || isWhitelisted(order.whitelist, msg.sender), "Not whitelisted");

        // check duration is not too long
        require(order.duration <= 10_000 days, "Duration too long");

        // check duration is not too short
        require(order.duration >= 15 minutes, "Duration too short");

        // check order has not expired
        require(block.timestamp < order.expiration, "Order has expired");

        // check base asset exists
        require(order.baseAsset.code.length > 0, "baseAsset is not contract");

        // check short call doesn't have floor tokens
        if (order.isCall && !order.isLong) {
            require(order.floorTokens.length == 0, "Short call cant have floorTokens");
        }

        // check native eth is only used if baseAsset is weth
        require(msg.value == 0 || order.baseAsset == address(weth), "Cannot use native ETH");

        // check floor asset token ids length is 0 unless the order type is call and side is long
        order.isCall && order.isLong
            ? require(floorAssetTokenIds.length == order.floorTokens.length, "Wrong amount of floor tokenIds")
            : require(floorAssetTokenIds.length == 0, "Invalid floor tokens length");

        /*  ~~~ EFFECTS ~~~ */

        // create long/short position for maker
        _mint(order.maker, uint256(orderHash));

        // create opposite long/short position for taker
        bytes32 oppositeOrderHash = hashOppositeOrder(order);
        positionId = uint256(oppositeOrderHash);
        _mint(msg.sender, positionId);

        // save floorAssetTokenIds if filling a long call order
        if (order.isLong && order.isCall) {
            positionFloorAssetTokenIds[uint256(orderHash)] = floorAssetTokenIds;
        }

        // save the long position expiration
        positionExpirations[order.isLong ? uint256(orderHash) : positionId] = block.timestamp + order.duration;

        emit FilledOrder(orderHash, floorAssetTokenIds, order);

        /* ~~~ INTERACTIONS ~~~ */

        // calculate the fee amount
        uint256 feeAmount = 0;
        if (fee > 0) {
            feeAmount = (order.premium * fee) / 1000;
            unclaimedFees[order.baseAsset] += feeAmount;
        }

        // transfer premium to whoever is short from whomever is long
        if (order.premium > 0) {
            if (order.isLong) {
                // transfer premium to taker
                ERC20(order.baseAsset).safeTransferFrom(order.maker, msg.sender, order.premium - feeAmount);

                // collect fees
                if (feeAmount > 0) {
                    ERC20(order.baseAsset).safeTransferFrom(order.maker, address(this), feeAmount);
                }
            } else {
                // handle the case where the user uses native ETH instead of WETH to pay the premium
                if (msg.value > 0) {
                    // check enough ETH was sent to cover the premium
                    require(msg.value == order.premium, "Incorrect ETH amount sent");

                    // convert ETH to WETH and send premium to maker
                    // converting to WETH instead of forwarding native ETH to the maker has two benefits;
                    // 1) active market makers will mostly be using WETH not native ETH
                    // 2) attack surface for re-entrancy is reduced
                    IWETH(weth).deposit{value: order.premium}();

                    // collect fees and transfer to premium to maker
                    IWETH(weth).transfer(order.maker, order.premium - feeAmount);
                } else {
                    // transfer premium to maker
                    ERC20(order.baseAsset).safeTransferFrom(msg.sender, order.maker, order.premium - feeAmount);

                    // collect fees
                    if (feeAmount > 0) {
                        ERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), feeAmount);
                    }
                }
            }
        }

        if (!order.isLong && !order.isCall) {
            // filling short put: transfer strike from maker to contract
            ERC20(order.baseAsset).safeTransferFrom(order.maker, address(this), order.strike);
        } else if (order.isLong && !order.isCall) {
            // filling long put: transfer strike from taker to contract
            // handle the case where the taker uses native ETH instead of WETH to deposit the strike
            if (msg.value > 0) {
                // check enough ETH was sent to cover the strike
                require(msg.value == order.strike, "Incorrect ETH amount sent");

                // convert ETH to WETH
                // we convert the strike ETH to WETH so that the logic in exercise() works
                // - because exercise() assumes an ERC20 interface on the base asset.
                IWETH(weth).deposit{value: msg.value}();
            } else {
                ERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);
            }
        } else if (!order.isLong && order.isCall) {
            // filling short call: transfer assets from maker to contract
            _transferERC20sIn(order.erc20Assets, order.maker);
            _transferERC721sIn(order.erc721Assets, order.maker);
        } else if (order.isLong && order.isCall) {
            // filling long call: transfer assets from taker to contract
            // long calls never need native ETH
            require(msg.value == 0, "Long call can't use native ETH");

            _transferERC20sIn(order.erc20Assets, msg.sender);
            _transferERC721sIn(order.erc721Assets, msg.sender);
            _transferFloorsIn(order.floorTokens, floorAssetTokenIds, msg.sender);
        }

        if (ERC165Checker.supportsInterface(order.maker, type(IPuttyV2Handler).interfaceId)) {
            // callback the maker with onFillOrder - save 15k gas in case of revert
            order.maker.call{gas: gasleft() - 15_000}(
                abi.encodeWithSelector(PuttyV2Handler.onFillOrder.selector, order, msg.sender, floorAssetTokenIds)
            );
        }
    }

    /**
        @notice Exercises a long order and also burns the long position NFT which 
                represents it.
        @param order The order of the position to exercise.
        @param floorAssetTokenIds The floor asset token ids to use. Should only be set 
               when exercising a put order.
     */
    function exercise(Order memory order, uint256[] calldata floorAssetTokenIds) public payable {
        /* ~~~ CHECKS ~~~ */

        bytes32 orderHash = hashOrder(order);

        // check user owns the position
        require(ownerOf(uint256(orderHash)) == msg.sender, "Not owner");

        // check position is long
        require(order.isLong, "Can only exercise long positions");

        // check position has not expired
        require(block.timestamp < positionExpirations[uint256(orderHash)], "Position has expired");

        // check native eth is only used if baseAsset is weth
        require(msg.value == 0 || order.baseAsset == address(weth), "Cannot use native ETH");

        // check floor asset token ids length is 0 unless the position type is put
        !order.isCall
            ? require(floorAssetTokenIds.length == order.floorTokens.length, "Wrong amount of floor tokenIds")
            : require(floorAssetTokenIds.length == 0, "Invalid floor tokenIds length");

        /* ~~~ EFFECTS ~~~ */

        // send the long position to 0xdead.
        // instead of doing a standard burn by sending to 0x000...000, sending
        // to 0xdead ensures that the same position id cannot be minted again.
        transferFrom(msg.sender, address(0xdead), uint256(orderHash));

        // mark the position as exercised
        exercisedPositions[uint256(orderHash)] = true;

        emit ExercisedOrder(orderHash, floorAssetTokenIds, order);

        /* ~~~ INTERACTIONS ~~~ */

        uint256 shortPositionId = uint256(hashOppositeOrder(order));
        if (order.isCall) {
            // -- exercising a call option

            // transfer strike from exerciser to putty
            // handle the case where the taker uses native ETH instead of WETH to pay the strike
            if (order.strike > 0) {
                if (msg.value > 0) {
                    // check enough ETH was sent to cover the strike
                    require(msg.value == order.strike, "Incorrect ETH amount sent");

                    // convert ETH to WETH
                    // we convert the strike ETH to WETH so that the logic in withdraw() works
                    // - because withdraw() assumes an ERC20 interface on the base asset.
                    IWETH(weth).deposit{value: msg.value}();
                } else {
                    ERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);
                }
            }

            // transfer assets from putty to exerciser
            _transferERC20sOut(order.erc20Assets);
            _transferERC721sOut(order.erc721Assets);
            _transferFloorsOut(order.floorTokens, positionFloorAssetTokenIds[uint256(orderHash)]);
        } else {
            // -- exercising a put option
            // exercising a put never needs native ETH
            require(msg.value == 0, "Puts can't use native ETH");

            // save the floor asset token ids to the short position
            positionFloorAssetTokenIds[shortPositionId] = floorAssetTokenIds;

            // transfer strike from putty to exerciser
            ERC20(order.baseAsset).safeTransfer(msg.sender, order.strike);

            // transfer assets from exerciser to putty
            _transferERC20sIn(order.erc20Assets, msg.sender);
            _transferERC721sIn(order.erc721Assets, msg.sender);
            _transferFloorsIn(order.floorTokens, floorAssetTokenIds, msg.sender);
        }

        // attempt call onExercise on the short position owner
        address shortOwner = ownerOf(shortPositionId);
        order.isLong = false;
        if (ERC165Checker.supportsInterface(shortOwner, type(IPuttyV2Handler).interfaceId)) {
            // callback the short owner with onExercise - save 15k gas in case of revert
            order.maker.call{gas: gasleft() - 15_000}(
                abi.encodeWithSelector(PuttyV2Handler.onExercise.selector, order, msg.sender, floorAssetTokenIds)
            );
        }
    }

    /**
        @notice Withdraws the assets from a short order and also burns the short position 
                that represents it. The assets that are withdrawn are dependent on whether 
                the order is exercised or expired and if the order is a put or call.
        @param order The order to withdraw.
     */
    function withdraw(Order memory order) public {
        /* ~~~ CHECKS ~~~ */

        // check order is short
        require(!order.isLong, "Must be short position");

        bytes32 orderHash = hashOrder(order);

        // check msg.sender owns the position
        require(ownerOf(uint256(orderHash)) == msg.sender, "Not owner");

        uint256 longPositionId = uint256(hashOppositeOrder(order));
        bool isExercised = exercisedPositions[longPositionId];

        // check long position has either been exercised or is expired
        require(isExercised || block.timestamp > positionExpirations[longPositionId], "Must be exercised or expired");

        /* ~~~ EFFECTS ~~~ */

        // send the short position to 0xdead.
        // instead of doing a standard burn by sending to 0x000...000, sending
        // to 0xdead ensures that the same position id cannot be minted again.
        transferFrom(msg.sender, address(0xdead), uint256(orderHash));

        emit WithdrawOrder(orderHash, order);

        /* ~~~ INTERACTIONS ~~~ */

        // transfer strike to owner if put is expired or call is exercised
        if ((order.isCall && isExercised) || (!order.isCall && !isExercised)) {
            ERC20(order.baseAsset).safeTransfer(msg.sender, order.strike);
            return;
        }

        // transfer assets from putty to owner if put is exercised or call is expired
        if ((order.isCall && !isExercised) || (!order.isCall && isExercised)) {
            _transferERC20sOut(order.erc20Assets);
            _transferERC721sOut(order.erc721Assets);

            // for call options the floor token ids are saved in the long position in fillOrder(),
            // and for put options the floor tokens ids are saved in the short position in exercise()
            uint256 floorPositionId = order.isCall ? longPositionId : uint256(orderHash);
            _transferFloorsOut(order.floorTokens, positionFloorAssetTokenIds[floorPositionId]);

            return;
        }
    }

    /**
        @notice Cancels an order which prevents it from being filled in the future.
        @param order The order to cancel.
     */
    function cancel(Order memory order) public {
        require(msg.sender == order.maker, "Not your order");

        bytes32 orderHash = hashOrder(order);
        require(_ownerOf[uint256(orderHash)] == address(0), "Order already filled");

        // mark the order as cancelled
        cancelledOrders[orderHash] = true;

        emit CancelledOrder(orderHash, order);
    }

    /* ~~~ PERIPHERY LOGIC FUNCTIONS ~~~ */

    /**
        @notice Batch fills multiple orders.
        @dev Purposefully marked as non-payable otherwise the msg.value can be used multiple times in fillOrder.
        @param orders The orders to fill.
        @param signatures The signatures to use for each respective order.
        @param floorAssetTokenIds The floorAssetTokenIds to use for each respective order.
        @return positionIds The ids of the position NFT that the msg.sender receives.
     */
    function batchFillOrder(
        Order[] memory orders,
        bytes[] calldata signatures,
        uint256[][] memory floorAssetTokenIds
    ) public returns (uint256[] memory positionIds) {
        require(
            orders.length == signatures.length && signatures.length == floorAssetTokenIds.length,
            "Length mismatch in input"
        );

        positionIds = new uint256[](orders.length);

        for (uint256 i = 0; i < orders.length; i++) {
            positionIds[i] = fillOrder(orders[i], signatures[i], floorAssetTokenIds[i]);
        }
    }

    /**
        @notice Accepts a counter offer for an order. It cancels the original order that the counter 
                offer was made for and then it fills the counter offer.
        @dev There is no need for floorTokenIds here because there is no situation in which
             it makes sense to have them when accepting counter offers; When accepting a counter 
             offer for a short call order, the complementary long call order already knows what 
             tokenIds are used in the short call so floorTokens should always be empty.
        @param order The counter offer to accept.
        @param signature The signature for the counter offer.
        @param originalOrder The original order that the counter was made for.
        @return positionId The id of the position NFT that the msg.sender receives.
     */
    function acceptCounterOffer(
        Order memory order,
        bytes calldata signature,
        Order memory originalOrder
    ) public payable returns (uint256 positionId) {
        // cancel the original order
        cancel(originalOrder);

        // accept the counter offer
        uint256[] memory floorAssetTokenIds = new uint256[](0);
        positionId = fillOrder(order, signature, floorAssetTokenIds);
    }

    /**
        @notice Sets the minimum valid nonce for a user. Any unfilled orders with a nonce 
                smaller than this minimum will no longer be valid and will unable to be filled.
        @param _minimumValidNonce The new minimum valid nonce.
     */
    function setMinimumValidNonce(uint256 _minimumValidNonce) public {
        minimumValidNonce[msg.sender] = _minimumValidNonce;

        emit SetMinimumValidNonce(_minimumValidNonce);
    }

    /* ~~~ HELPER FUNCTIONS ~~~ */

    /**
        @notice Transfers an array of erc20s into the contract from an address.
        @param assets The erc20 tokens and amounts to transfer in.
        @param from Who to transfer the erc20 assets from.
     */
    function _transferERC20sIn(ERC20Asset[] memory assets, address from) internal {
        for (uint256 i = 0; i < assets.length; i++) {
            address token = assets[i].token;
            uint256 tokenAmount = assets[i].tokenAmount;

            require(token.code.length > 0, "ERC20: Token is not contract");

            if (tokenAmount > 0) {
                ERC20(token).safeTransferFrom(from, address(this), tokenAmount);
            }
        }
    }

    /**
        @notice Transfers an array of erc721s into the contract from an address.
        @param assets The erc721 tokens and token ids to transfer in.
        @param from Who to transfer the erc721 assets from.
     */
    function _transferERC721sIn(ERC721Asset[] memory assets, address from) internal {
        for (uint256 i = 0; i < assets.length; i++) {
            ERC721(assets[i].token).safeTransferFrom(from, address(this), assets[i].tokenId);
        }
    }

    /**
        @notice Transfers an array of erc721 floor tokens into the contract from an address.
        @param floorTokens The contract addresses of each erc721.
        @param floorTokenIds The token id of each erc721.
        @param from Who to transfer the floor tokens from.
     */
    function _transferFloorsIn(
        address[] memory floorTokens,
        uint256[] memory floorTokenIds,
        address from
    ) internal {
        for (uint256 i = 0; i < floorTokens.length; i++) {
            ERC721(floorTokens[i]).safeTransferFrom(from, address(this), floorTokenIds[i]);
        }
    }

    /**
        @notice Transfers an array of erc20 tokens to the msg.sender.
        @param assets The erc20 tokens and amounts to send.
     */
    function _transferERC20sOut(ERC20Asset[] memory assets) internal {
        for (uint256 i = 0; i < assets.length; i++) {
            if (assets[i].tokenAmount > 0) {
                ERC20(assets[i].token).safeTransfer(msg.sender, assets[i].tokenAmount);
            }
        }
    }

    /**
        @notice Transfers an array of erc721 tokens to the msg.sender.
        @param assets The erc721 tokens and token ids to send.
     */
    function _transferERC721sOut(ERC721Asset[] memory assets) internal {
        for (uint256 i = 0; i < assets.length; i++) {
            ERC721(assets[i].token).safeTransferFrom(address(this), msg.sender, assets[i].tokenId);
        }
    }

    /**
        @notice Transfers an array of erc721 floor tokens to the msg.sender.
        @param floorTokens The contract addresses for each floor token.
        @param floorTokenIds The token id of each floor token.
     */
    function _transferFloorsOut(address[] memory floorTokens, uint256[] memory floorTokenIds) internal {
        for (uint256 i = 0; i < floorTokens.length; i++) {
            ERC721(floorTokens[i]).safeTransferFrom(address(this), msg.sender, floorTokenIds[i]);
        }
    }

    /**
        @notice Checks whether or not an address exists in the whitelist.
        @param whitelist The whitelist to check against.
        @param target The target address to check.
        @return If it exists in the whitelist or not.
     */
    function isWhitelisted(address[] memory whitelist, address target) public pure returns (bool) {
        for (uint256 i = 0; i < whitelist.length; i++) {
            if (target == whitelist[i]) return true;
        }

        return false;
    }

    /**
        @notice Get the orderHash for a complementary short/long order - e.g for a long order,
                this returns the hash of its opposite short order.
        @param order The order to find the complementary long/short hash for.
        @return orderHash The hash of the opposite order.
     */
    function hashOppositeOrder(Order memory order) public view returns (bytes32 orderHash) {
        // use decode/encode to get a copy instead of reference
        Order memory oppositeOrder = abi.decode(abi.encode(order), (Order));

        // get the opposite side of the order (short/long)
        oppositeOrder.isLong = !order.isLong;
        orderHash = hashOrder(oppositeOrder);
    }

    /* ~~~ EIP-712 HELPERS ~~~ */

    /**
        @notice Hashes an order based on the eip-712 encoding scheme.
        @param order The order to hash.
        @return orderHash The eip-712 compliant hash of the order.
     */
    function hashOrder(Order memory order) public view returns (bytes32 orderHash) {
        orderHash = keccak256(
            abi.encode(
                ORDER_TYPE_HASH,
                order.maker,
                order.isCall,
                order.isLong,
                order.baseAsset,
                order.strike,
                order.premium,
                order.duration,
                order.expiration,
                order.nonce,
                keccak256(abi.encodePacked(order.whitelist)),
                keccak256(abi.encodePacked(order.floorTokens)),
                keccak256(encodeERC20Assets(order.erc20Assets)),
                keccak256(encodeERC721Assets(order.erc721Assets))
            )
        );

        orderHash = _hashTypedDataV4(orderHash);
    }

    /**
        @notice Encodes an array of erc20 assets following the eip-712 encoding scheme.
        @param arr Array of erc20 assets to hash.
        @return encoded The eip-712 encoded array of erc20 assets.
     */
    function encodeERC20Assets(ERC20Asset[] memory arr) public pure returns (bytes memory encoded) {
        for (uint256 i = 0; i < arr.length; i++) {
            encoded = abi.encodePacked(
                encoded,
                keccak256(abi.encode(ERC20ASSET_TYPE_HASH, arr[i].token, arr[i].tokenAmount))
            );
        }
    }

    /**
        @notice Encodes an array of erc721 assets following the eip-712 encoding scheme.
        @param arr Array of erc721 assets to hash.
        @return encoded The eip-712 encoded array of erc721 assets.
     */
    function encodeERC721Assets(ERC721Asset[] memory arr) public pure returns (bytes memory encoded) {
        for (uint256 i = 0; i < arr.length; i++) {
            encoded = abi.encodePacked(
                encoded,
                keccak256(abi.encode(ERC721ASSET_TYPE_HASH, arr[i].token, arr[i].tokenId))
            );
        }
    }

    /**
        @return The domain separator used when calculating the eip-712 hash.
     */
    function domainSeparatorV4() public view returns (bytes32) {
        return _domainSeparatorV4();
    }

    /* ~~~ OVERRIDES ~~~ */

    /**
        @notice Gets the token URI for an NFT.
        @param id The id of the position NFT.
        @return The tokenURI of the position NFT.
     */
    function tokenURI(uint256 id) public view override returns (string memory) {
        require(_ownerOf[id] != address(0), "URI query for NOT_MINTED token");

        return string.concat(baseURI, Strings.toString(id));
    }
}

File 10 of 50 : SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

File 11 of 50 : MintBurnToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import {ERC20} from "solmate/tokens/ERC20.sol";
import {Owned} from "solmate/auth/Owned.sol";

contract MintBurnToken is ERC20, Owned {
    mapping(address => bool) public whitelistedMinterBurner;

    constructor(string memory _name, string memory _symbol, uint8 _decimals)
        ERC20(_name, _symbol, _decimals)
        Owned(msg.sender)
    {}

    modifier onlyMinterBurner() virtual {
        require(whitelistedMinterBurner[msg.sender], "UNAUTHORIZED");
        _;
    }

    function setMinterBurner(address target, bool authorized) public onlyOwner {
        whitelistedMinterBurner[target] = authorized;
    }

    function mint(address to, uint256 amount) public onlyMinterBurner {
        _mint(to, amount);
    }

    function burn(address from, uint256 amount) public onlyMinterBurner {
        _burn(from, amount);
    }

    /**
     * @notice Override transferFrom to allow the owner to transfer tokens from any account (owner should be wheyfu contract).
     * This prevents the need for the LP token to be approved for the wheyfu contract.
     */
    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        // allow the owner to transfer tokens from any account (owner should be wheyfu contract)
        uint256 allowed = msg.sender == owner ? type(uint256).max : allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) {
            allowance[from][msg.sender] = allowed - 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;
    }
}

File 12 of 50 : OptionBonding.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {Owned} from "solmate/auth/Owned.sol";
import {PuttyV2} from "putty-v2/PuttyV2.sol";

import {MintBurnToken} from "./lib/MintBurnToken.sol";
import {BondingNft} from "./lib/BondingNft.sol";

/**
 * @notice Option bonding stufffff.
 *
 * LP's stake their LP tokens for preset bond durations. In return they receive
 * call option token rewards which are distributed linearly over time. Option token
 * rewards can be claimed after the bond matures. The longer the bond duration, the
 * higher the yield boost.
 *
 * The option ERC20 tokens can be converted for actual call option contracts on putty via the
 * convertToOption() method. Each call option has a strike of 0.1 ether per NFT and expires
 * in 5 years from now. When the option is exercised, the wheyfus are minted to your wallet.
 *
 * @author 0xacedia
 */
contract OptionBonding is IERC1271, Owned {
    /**
     * @notice Bond details.
     * @param rewardPerTokenCheckpoint The total rewards per token at bond creation.
     * @param depositAmount The amount of lp tokens deposited into the bond.
     * @param depositTimestamp The unix timestamp of the deposit.
     * @param termIndex The index into the terms array for the bond term.
     */
    struct OptionBond {
        uint256 rewardPerTokenCheckpoint;
        uint128 depositAmount;
        uint32 depositTimestamp;
        uint8 termIndex;
    }

    /// @notice The term duration options for bonds.
    uint256[] public terms = [0, 7 days, 30 days, 90 days, 180 days, 365 days];

    /// @notice The yield boost options for corresponding to each term.
    uint256[] public termBoosters = [1e18, 1.1e18, 1.2e18, 1.5e18, 2e18, 3e18];

    /// @notice The total amount of call option tokens to give out in bond rewards.
    uint256 public constant TOTAL_REWARDS = 18_000 * 1e18;

    /// @notice The duration over which bond rewards are distributed.
    uint256 public constant REWARD_DURATION = 900 days;

    /// @notice The emission rate for call option tokens.
    /// @dev Calculated by taking the total rewards and dividing it by the reward duration.
    uint256 public immutable rewardRate = TOTAL_REWARDS / REWARD_DURATION;

    /// @notice The strike price for each call option.
    uint256 public constant STRIKE = 0.1 ether;

    /// @notice The expiration date of each option.
    /// @dev The expiration date is set to be 1825 days from the deployment date (approx. 5 years).
    uint256 public immutable optionExpiration = block.timestamp + 1825 days;

    /// @notice The date at which rewards will stop being distributed.
    /// @dev Set to be the deploy timestamp + the reward duration.
    uint256 public immutable finishAt = block.timestamp + REWARD_DURATION;

    /// @notice The date at which rewards started being distributed.
    uint256 public immutable startAt = block.timestamp;

    /// @notice The last calculated amount of rewards per token.
    uint256 public optionRewardPerTokenStored;

    /// @notice The last time at which staking rewards were calculated.
    uint32 public lastUpdateTime = uint32(block.timestamp);

    /// @notice The total amount of bonds in existence.
    uint32 public optionBondTotalSupply;

    /// @notice The total amount of synthetic supply being staked.
    /// @dev Calculated by summing total lp tokens staked * yield booster.
    uint128 public optionStakedTotalSupply;

    /// @notice Mapping of bondId to bond details.
    mapping(uint256 => OptionBond) private _bonds;

    MintBurnToken public immutable callOptionToken;
    MintBurnToken public immutable lpToken;
    BondingNft public immutable optionBondingNft;
    PuttyV2 public immutable putty;
    IERC20 public immutable weth;

    /**
     * @notice Emitted when LP tokens are staked.
     * @param bondId The tokenId of the new bond.
     * @param bond The bond details.
     */
    event OptionStake(uint256 bondId, OptionBond bond);

    /**
     * @notice Emitted when LP tokens are unstaked.
     * @param bondId The tokenId of the bond being unstaked.
     * @param bond The bond details.
     */
    event OptionUnstake(uint256 bondId, OptionBond bond);

    constructor(address _lpToken, address _callOptionToken, address _putty, address _weth) Owned(msg.sender) {
        lpToken = MintBurnToken(_lpToken);
        callOptionToken = MintBurnToken(_callOptionToken);
        putty = PuttyV2(_putty);
        weth = IERC20(_weth);
        optionBondingNft = new BondingNft("Wheyfu LP Option Bonds", "WLPOB");
    }

    /**
     * ~~~~~~~~~~~~~~~~~
     * STAKING FUNCTIONS
     * ~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Stakes an amount of lp tokens for a given term.
     * @param amount Amount of lp tokens to stake.
     * @param termIndex Index into the terms array which tells how long to stake for.
     */
    function optionStake(uint128 amount, uint256 termIndex) public returns (uint256 tokenId) {
        // update the rewards for everyone
        optionRewardPerTokenStored = uint256(rewardPerToken());

        // update bond supply
        optionBondTotalSupply += 1;
        tokenId = optionBondTotalSupply;

        // set the bond parameters
        OptionBond storage bond = _bonds[tokenId];
        bond.rewardPerTokenCheckpoint = uint256(optionRewardPerTokenStored);
        bond.depositAmount = amount;
        bond.depositTimestamp = uint32(block.timestamp);
        bond.termIndex = uint8(termIndex);

        // update last update time and staked total supply
        lastUpdateTime = uint32(block.timestamp);
        optionStakedTotalSupply += uint128((uint256(amount) * termBoosters[termIndex]) / 1e18);

        // transfer lp tokens from sender
        lpToken.transferFrom(msg.sender, address(this), amount);

        // mint the bond
        optionBondingNft.mint(msg.sender, tokenId);

        emit OptionStake(tokenId, bond);
    }

    /**
     * @notice Unstakes a bond, returns lp tokens and mints call option tokens.
     * @param tokenId The tokenId of the bond to unstake.
     */
    function optionUnstake(uint256 tokenId) public returns (uint256 callOptionAmount) {
        // check that the user owns the bond
        require(msg.sender == optionBondingNft.ownerOf(tokenId), "Not owner");

        // check that the bond has matured
        OptionBond memory bond = _bonds[tokenId];
        require(block.timestamp >= bond.depositTimestamp + terms[bond.termIndex], "Bond not matured");

        // update the rewards for everyone
        optionRewardPerTokenStored = uint256(rewardPerToken());

        // burn the bond
        optionBondingNft.burn(tokenId);

        // update last update time and staked total supply
        lastUpdateTime = uint32(block.timestamp);
        uint256 amount = bond.depositAmount;
        optionStakedTotalSupply -= uint128((uint256(amount) * termBoosters[bond.termIndex]) / 1e18);

        // send lp tokens back to sender
        lpToken.transfer(msg.sender, amount);

        // mint call option rewards to sender
        callOptionAmount = optionEarned(tokenId);
        callOptionToken.mint(msg.sender, callOptionAmount);

        emit OptionUnstake(tokenId, bond);
    }

    /**
     * @notice Gets the total amount of token rewards earned per token staked.
     * Should not accrue any more rewards if we are past the finishAt timestamp.
     */
    function rewardPerToken() public view returns (uint256) {
        if (optionStakedTotalSupply == 0) {
            return optionRewardPerTokenStored;
        }

        uint256 delta = Math.min(block.timestamp, finishAt) - Math.min(lastUpdateTime, finishAt);

        return optionRewardPerTokenStored + ((delta * rewardRate * 1e18) / optionStakedTotalSupply);
    }

    /**
     * @notice Gets the total amount of option tokens earned for a bond.
     * @param tokenId The id of the bond.
     */
    function optionEarned(uint256 tokenId) public view returns (uint256) {
        OptionBond storage bond = _bonds[tokenId];
        uint256 boostedAmount = bond.depositAmount * termBoosters[bond.termIndex];

        return (boostedAmount * (rewardPerToken() - bond.rewardPerTokenCheckpoint)) / 1e36;
    }

    /**
     * ~~~~~~~~~~~~~~~~
     * OPTION FUNCTIONS
     * ~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Burns call option tokens and converts them into an actual call option contract via putty.
     * @param numAssets The amount of assets to put into the call option.
     * @param nonce The nonce for the call option (prevents hash collisions).
     */
    function convertToOption(uint256 numAssets, uint256 nonce)
        public
        returns (uint256 longTokenId, PuttyV2.Order memory shortOrder)
    {
        require(numAssets > 0, "Must convert at least one asset");
        require(numAssets <= 50, "Must convert 50 or less assets");

        // set the option parameters
        shortOrder.maker = address(this);
        shortOrder.isCall = true;
        shortOrder.isLong = false;
        shortOrder.baseAsset = address(weth);
        shortOrder.strike = STRIKE * numAssets;
        shortOrder.duration = optionExpiration - block.timestamp;
        shortOrder.expiration = block.timestamp + 1;
        shortOrder.nonce = nonce;
        shortOrder.erc721Assets = new PuttyV2.ERC721Asset[](1);
        shortOrder.erc721Assets[0] = PuttyV2.ERC721Asset({
            token: address(this),
            tokenId: type(uint256).max - numAssets // this value is used to determine how many tokens to mint in onExercise
        });

        // burn the call option tokens from the sender
        callOptionToken.burn(msg.sender, numAssets * 1e18);

        // mint the option and send the long option to the sender
        longTokenId = _mintOption(shortOrder);
        putty.transferFrom(address(this), msg.sender, longTokenId);
    }

    // @notice Guard variable that tells us whether or not we are minting an option.
    uint256 public mintingOption = 1;

    /**
     * @notice Whether or not an order from putty can be filled.
     * @dev This should only return true when mintingOption is set to 2.
     */
    function isValidSignature(bytes32, bytes memory) external view returns (bytes4 magicValue) {
        magicValue = mintingOption == 2 ? IERC1271.isValidSignature.selector : bytes4(0);
    }

    /**
     * @notice Mints a new putty option.
     * @param order The order details to mint.
     */
    function _mintOption(PuttyV2.Order memory order) internal returns (uint256 tokenId) {
        mintingOption = 2;
        uint256[] memory empty = new uint256[](0);
        bytes memory signature;

        tokenId = putty.fillOrder(order, signature, empty);
        mintingOption = 1;
    }

    /**
     * @notice Withdraws the eth earned from exercised call options.
     * @param orders The options that were exercised.
     * @param recipient Who to send the weth to.
     */
    function withdrawWeth(PuttyV2.Order[] memory orders, address recipient) public onlyOwner {
        for (uint256 i = 0; i < orders.length; i++) {
            // withdraw all the strike weth form exercised options
            putty.withdraw(orders[i]);
        }

        // transfer all of the earned weth to the recipient
        weth.transfer(recipient, weth.balanceOf(address(this)));
    }

    /**
     * ~~~~~~~~~~~~~~~~~
     * MISC. FUNCTIONS
     * ~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Getter for bond details.
     * @param tokenId The tokenId to fetch info for.
     * @return bondDetails The bond details.
     */
    function bonds(uint256 tokenId) public view returns (OptionBond memory) {
        return _bonds[tokenId];
    }
}

File 13 of 50 : FeeBonding.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {ERC721} from "solmate/tokens/ERC721.sol";
import {Owned} from "solmate/auth/Owned.sol";
import {PuttyV2} from "putty-v2/PuttyV2.sol";
import {LSSVMPairMissingEnumerableETH} from "lssvm/LSSVMPairMissingEnumerableETH.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";

import {MintBurnToken} from "./lib/MintBurnToken.sol";
import {BondingNft} from "./lib/BondingNft.sol";

/**
 * @notice Fee bonding stuff.
 *
 * LP's stake their LP tokens for preset bond durations. In return they receive
 * fee rewards from the shared sudo xyk pool. Fees can be claimed after the bond matures.
 * The longer the bond duration, the higher the yield boost. Fees are distributed via the
 * skim() method.
 *
 * @author 0xacedia
 */
contract FeeBonding {
    /**
     * @notice Bond details.
     * @param rewardPerTokenCheckpoint The total rewards per token at bond creation.
     * @param depositAmount The amount of lp tokens deposited into the bond.
     * @param depositTimestamp The unix timestamp of the deposit.
     * @param termIndex The index into the terms array for the bond term.
     */
    struct FeeBond {
        uint256 rewardPerTokenCheckpoint;
        uint128 depositAmount;
        uint32 depositTimestamp;
        uint8 termIndex;
    }

    /// @notice The term duration options for bonds.
    uint256[] private terms = [0 days, 7 days, 30 days, 90 days, 180 days, 365 days];

    /// @notice The yield boost options for corresponding to each term.
    uint256[] private termBoosters = [1e18, 1.1e18, 1.2e18, 1.5e18, 2e18, 3e18];

    /// @notice The last calculated amount of rewards per token.
    uint256 public feeRewardPerTokenStored;

    /// @notice The total amount of bonds in existence.
    uint32 public feeTotalBondSupply;

    /// @notice The total amount of synthetic supply being staked.
    /// @dev Calculated by summing total lp tokens staked * yield booster.
    uint128 public feeStakedTotalSupply;

    /// @notice Mapping of bondId to bond details.
    mapping(uint256 => FeeBond) private _bonds;

    BondingNft public immutable feeBondingNft;
    MintBurnToken private immutable lpToken;
    LSSVMPairMissingEnumerableETH private pair;

    /**
     * @notice Emitted when LP tokens are staked.
     * @param bondId The tokenId of the new bond.
     * @param bond The bond details.
     */
    event FeeStake(uint256 bondId, FeeBond bond);

    /**
     * @notice Emitted when LP tokens are unstaked.
     * @param bondId The tokenId of the bond being unstaked.
     * @param bond The bond details.
     */
    event FeeUnstake(uint256 bondId, FeeBond bond);

    constructor(address _lpToken) {
        lpToken = MintBurnToken(_lpToken);
        feeBondingNft = new BondingNft("Wheyfu LP Fee Bonds", "WLPFB");
    }

    /**
     * @notice Sets the sudoswap pool address.
     * @param _pair The sudoswap pool.
     */
    function _setPair(address payable _pair) internal {
        pair = LSSVMPairMissingEnumerableETH(_pair);
    }

    /**
     * ~~~~~~~~~~~~~~~~~
     * STAKING FUNCTIONS
     * ~~~~~~~~~~~~~~~~~
     */

    /**
     * @notice Skims the fees from the sudoswap pool and distributes them to fee stakers.
     */
    function skim() public returns (uint256) {
        // skim the fees
        uint256 tokenReserves = pair.spotPrice();
        uint256 fees = address(pair).balance > tokenReserves ? address(pair).balance - tokenReserves : 0;
        pair.withdrawETH(fees);

        // distribute the fees to stakers
        if (fees > 0 && feeStakedTotalSupply > 0) {
            feeRewardPerTokenStored += (fees * 1e18) / feeStakedTotalSupply;
        }

        return fees;
    }

    /**
     * @notice Stakes an amount of lp tokens for a given term.
     * @param amount Amount of lp tokens to stake.
     * @param termIndex Index into the terms array which tells how long to stake for.
     */
    function feeStake(uint128 amount, uint256 termIndex) public returns (uint256 tokenId) {
        // update the rewards for everyone
        skim();

        // update the bond supply
        feeTotalBondSupply += 1;
        tokenId = feeTotalBondSupply;

        // set the bond parameters
        FeeBond storage bond = _bonds[tokenId];
        bond.rewardPerTokenCheckpoint = uint256(feeRewardPerTokenStored);
        bond.depositAmount = amount;
        bond.depositTimestamp = uint32(block.timestamp);
        bond.termIndex = uint8(termIndex);

        // update the staked total supply
        feeStakedTotalSupply += uint128((uint256(amount) * termBoosters[termIndex]) / 1e18);

        // transfer lp tokens from sender
        lpToken.transferFrom(msg.sender, address(this), amount);

        // mint the bond
        feeBondingNft.mint(msg.sender, tokenId);

        emit FeeStake(tokenId, bond);
    }

    /**
     * @notice Unstakes a bond, returns lp tokens and mints call option tokens.
     * @param tokenId The tokenId of the bond to unstake.
     */
    function feeUnstake(uint256 tokenId) public returns (uint256 rewardAmount) {
        // check that the user owns the bond
        require(msg.sender == feeBondingNft.ownerOf(tokenId), "Not owner");

        // check that the bond has matured
        FeeBond memory bond = _bonds[tokenId];
        require(block.timestamp >= bond.depositTimestamp + terms[bond.termIndex], "Bond not matured");

        // update the rewards for everyone
        skim();

        // burn the bond
        feeBondingNft.burn(tokenId);

        // update staked total supply
        uint256 amount = bond.depositAmount;
        feeStakedTotalSupply -= uint128((uint256(amount) * termBoosters[bond.termIndex]) / 1e18);

        // send lp tokens back to sender
        lpToken.transfer(msg.sender, amount);

        // send fee rewards to sender
        rewardAmount = feeEarned(tokenId);
        SafeTransferLib.safeTransferETH(msg.sender, rewardAmount);

        emit FeeUnstake(tokenId, bond);
    }

    /**
     * @notice Calculates how much fees a bond has earned.
     * @param tokenId The tokenId to fetch earned info for.
     * @return earned How much fees the bond has earned.
     */
    function feeEarned(uint256 tokenId) public view returns (uint256) {
        FeeBond storage bond = _bonds[tokenId];
        uint256 boostedAmount = bond.depositAmount * termBoosters[bond.termIndex];

        return ((boostedAmount) * (feeRewardPerTokenStored - bond.rewardPerTokenCheckpoint)) / 1e36;
    }

    /**
     * @notice Getter for fee bond details.
     * @param tokenId The tokenId to fetch info for.
     * @return bondDetails The bond details.
     */
    function feeBonds(uint256 tokenId) public view returns (FeeBond memory) {
        return _bonds[tokenId];
    }
}

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

pragma solidity ^0.8.0;

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

File 15 of 50 : IERC721A.sol
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.2
// Creator: Chiru Labs

pragma solidity ^0.8.4;

/**
 * @dev Interface of ERC721A.
 */
interface IERC721A {
    /**
     * The caller must own the token or be an approved operator.
     */
    error ApprovalCallerNotOwnerNorApproved();

    /**
     * The token does not exist.
     */
    error ApprovalQueryForNonexistentToken();

    /**
     * The caller cannot approve to their own address.
     */
    error ApproveToCaller();

    /**
     * Cannot query the balance for the zero address.
     */
    error BalanceQueryForZeroAddress();

    /**
     * Cannot mint to the zero address.
     */
    error MintToZeroAddress();

    /**
     * The quantity of tokens minted must be more than zero.
     */
    error MintZeroQuantity();

    /**
     * The token does not exist.
     */
    error OwnerQueryForNonexistentToken();

    /**
     * The caller must own the token or be an approved operator.
     */
    error TransferCallerNotOwnerNorApproved();

    /**
     * The token must be owned by `from`.
     */
    error TransferFromIncorrectOwner();

    /**
     * Cannot safely transfer to a contract that does not implement the
     * ERC721Receiver interface.
     */
    error TransferToNonERC721ReceiverImplementer();

    /**
     * Cannot transfer to the zero address.
     */
    error TransferToZeroAddress();

    /**
     * The token does not exist.
     */
    error URIQueryForNonexistentToken();

    /**
     * The `quantity` minted with ERC2309 exceeds the safety limit.
     */
    error MintERC2309QuantityExceedsLimit();

    /**
     * The `extraData` cannot be set on an unintialized ownership slot.
     */
    error OwnershipNotInitializedForExtraData();

    // =============================================================
    //                            STRUCTS
    // =============================================================

    struct TokenOwnership {
        // The address of the owner.
        address addr;
        // Stores the start time of ownership with minimal overhead for tokenomics.
        uint64 startTimestamp;
        // Whether the token has been burned.
        bool burned;
        // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
        uint24 extraData;
    }

    // =============================================================
    //                         TOKEN COUNTERS
    // =============================================================

    /**
     * @dev Returns the total number of tokens in existence.
     * Burned tokens will reduce the count.
     * To get the total number of tokens minted, please see {_totalMinted}.
     */
    function totalSupply() external view returns (uint256);

    // =============================================================
    //                            IERC165
    // =============================================================

    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);

    // =============================================================
    //                            IERC721
    // =============================================================

    /**
     * @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,
        bytes calldata data
    ) external;

    /**
     * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
     * whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token
     * by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

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

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

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

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

    // =============================================================
    //                        IERC721Metadata
    // =============================================================

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

    // =============================================================
    //                           IERC2309
    // =============================================================

    /**
     * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
     * (inclusive) is transferred from `from` to `to`, as defined in the
     * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
     *
     * See {_mintERC2309} for more details.
     */
    event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}

File 16 of 50 : LSSVMPairETH.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {ERC20} from "solmate/tokens/ERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {SafeTransferLib} from "solmate/utils/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);
    }
}

File 17 of 50 : LSSVMPairMissingEnumerable.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/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();
        }
    }
}

File 18 of 50 : ILSSVMPairFactoryLike.sol
// 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);
}

File 19 of 50 : IWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface IWETH {
    event Approval(address indexed src, address indexed guy, uint256 wad);
    event Transfer(address indexed src, address indexed dst, uint256 wad);
    event Deposit(address indexed dst, uint256 wad);
    event Withdrawal(address indexed src, uint256 wad);

    function deposit() external payable;

    function withdraw(uint256 wad) external;

    function totalSupply() external view returns (uint256);

    function approve(address guy, uint256 wad) external returns (bool);

    function transfer(address dst, uint256 wad) external returns (bool);

    function transferFrom(
        address src,
        address dst,
        uint256 wad
    ) external returns (bool);
}

File 20 of 50 : SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
 * Argent and Gnosis Safe.
 *
 * _Available since v4.1._
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
        if (error == ECDSA.RecoverError.NoError && recovered == signer) {
            return true;
        }

        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
        );
        return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
    }
}

File 21 of 50 : draft-EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

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

pragma solidity ^0.8.0;

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

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // 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);
    }

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

File 23 of 50 : ERC165Checker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165Checker {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;

    /**
     * @dev Returns true if `account` supports the {IERC165} interface,
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            _supportsERC165Interface(account, type(IERC165).interfaceId) &&
            !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
    }

    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
    }

    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
        internal
        view
        returns (bool[] memory)
    {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }

    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }

        // query support of each interface in _interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!_supportsERC165Interface(account, interfaceIds[i])) {
                return false;
            }
        }

        // all interfaces supported
        return true;
    }

    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     * Interface identification is specified in ERC-165.
     */
    function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
        bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
        (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
        if (result.length < 32) return false;
        return success && abi.decode(result, (bool));
    }
}

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

pragma solidity ^0.8.0;

import "../utils/Context.sol";

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

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

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

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

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

File 25 of 50 : PuttyV2Nft.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import "solmate/tokens/ERC721.sol";

// removes balanceOf modifications
// questionable tradeoff but given our use-case it's reasonable
abstract contract PuttyV2Nft is ERC721("Putty", "OPUT") {
    // remove balanceOf modifications
    function _mint(address to, uint256 id) internal override {
        require(to != address(0), "INVALID_RECIPIENT");
        require(_ownerOf[id] == address(0), "ALREADY_MINTED");

        _ownerOf[id] = to;

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

    // remove balanceOf modifications
    function transferFrom(
        address from,
        address to,
        uint256 id
    ) public override {
        require(from == _ownerOf[id], "WRONG_FROM");
        require(to != address(0), "INVALID_RECIPIENT");
        require(
            msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
            "NOT_AUTHORIZED"
        );

        _ownerOf[id] = to;
        delete getApproved[id];

        emit Transfer(from, to, id);
    }

    // set balanceOf to max for all users
    function balanceOf(address owner) public pure override returns (uint256) {
        require(owner != address(0), "ZERO_ADDRESS");
        return type(uint256).max;
    }
}

File 26 of 50 : PuttyV2Handler.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import "./PuttyV2.sol";

interface IPuttyV2Handler {
    function onFillOrder(
        PuttyV2.Order memory order,
        address taker,
        uint256[] memory floorAssetTokenIds
    ) external;

    function onExercise(
        PuttyV2.Order memory order,
        address exerciser,
        uint256[] memory floorAssetTokenIds
    ) external;
}

contract PuttyV2Handler {
    function onFillOrder(
        PuttyV2.Order memory order,
        address taker,
        uint256[] memory floorAssetTokenIds
    ) public virtual {}

    function onExercise(
        PuttyV2.Order memory order,
        address exerciser,
        uint256[] memory floorAssetTokenIds
    ) public virtual {}
}

File 27 of 50 : ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
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
    //////////////////////////////////////////////////////////////*/

    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) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - 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 {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            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("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);
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 29 of 50 : IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 *
 * _Available since v4.1._
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

File 30 of 50 : BondingNft.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import {ERC721} from "solmate/tokens/ERC721.sol";
import {Owned} from "solmate/auth/Owned.sol";

/**
 * @dev Removes all the balanceOf parts for gas savings.
 */
contract BondingNft is ERC721, Owned {
    constructor(string memory name, string memory symbol) ERC721(name, symbol) Owned(msg.sender) {}

    function mint(address to, uint256 id) public onlyOwner {
        _mint(to, id);
    }

    function burn(uint256 id) public onlyOwner {
        _burn(id);
    }

    function _mint(address to, uint256 id) internal override {
        require(to != address(0), "INVALID_RECIPIENT");
        require(_ownerOf[id] == address(0), "ALREADY_MINTED");

        _ownerOf[id] = to;

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

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

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

        delete _ownerOf[id];

        delete getApproved[id];

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

    function transferFrom(address from, address to, uint256 id) public override {
        require(from == _ownerOf[id], "WRONG_FROM");
        require(to != address(0), "INVALID_RECIPIENT");
        require(
            msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id], "NOT_AUTHORIZED"
        );

        _ownerOf[id] = to;
        delete getApproved[id];

        emit Transfer(from, to, id);
    }

    function balanceOf(address owner) public pure override returns (uint256) {
        require(owner != address(0), "ZERO_ADDRESS");
        return type(uint256).max - 1;
    }

    function tokenURI(uint256) public view virtual override returns (string memory) {
        return "";
    }
}

File 31 of 50 : LSSVMPair.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {ERC20} from "solmate/tokens/ERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.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 {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/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. (onlyOwnable modifier is in the implemented function)
        @dev If the NFT is the pair's collection, we also remove it from the id tracking (if the NFT is missing enumerable).
        @param a 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 (onlyOwnable modifier is in the implemented function).
        @param a 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
    }
}

File 32 of 50 : ICurve.sol
// 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
        );
}

File 33 of 50 : EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)

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.
 *
 * [WARNING]
 * ====
 *  Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.
 *  See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 *  In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position 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;

        /// @solidity memory-safe-assembly
        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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

File 34 of 50 : LSSVMRouter.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/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
    ) public 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
    ) public 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
    ) public 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");
    }
}

File 35 of 50 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 37 of 50 : IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 *
 * _Available since v4.1._
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

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

pragma solidity ^0.8.0;

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

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

pragma solidity ^0.8.0;

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

File 41 of 50 : OwnableWithTransferCallback.sol
// SPDX-License-Identifier: AGPL-3.0

pragma solidity ^0.8.4;

import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import {IOwnershipTransferCallback} from "./IOwnershipTransferCallback.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

abstract contract OwnableWithTransferCallback {
    using ERC165Checker for address;
    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);
    }
}

File 42 of 50 : ReentrancyGuard.sol
// 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;
    }
}

File 43 of 50 : CurveErrorCodes.sol
// 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
    }
}

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

pragma solidity ^0.8.0;

import "./ERC1155Receiver.sol";

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

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

File 45 of 50 : ERC165Checker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165Checker {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;

    /**
     * @dev Returns true if `account` supports the {IERC165} interface,
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&
            !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);
    }

    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
    }

    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
        internal
        view
        returns (bool[] memory)
    {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }

    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }

        // query support of each interface in _interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
                return false;
            }
        }

        // all interfaces supported
        return true;
    }

    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     * Interface identification is specified in ERC-165.
     */
    function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
        // prepare call
        bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);

        // perform static call
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly {
            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0x00)
        }

        return success && returnSize >= 0x20 && returnValue > 0;
    }
}

File 46 of 50 : IOwnershipTransferCallback.sol
// SPDX-License-Identifier: AGPL-3.0

pragma solidity ^0.8.4;

interface IOwnershipTransferCallback {
  function onOwnershipTransfer(address oldOwner) external;
}

File 47 of 50 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

    /**
     * @dev 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) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ERC721A/=lib/ERC721A/contracts/",
    "base64/=lib/base64/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "hot-chain-svg/=lib/hot-chain-svg/contracts/",
    "lssvm/=lib/lssvm/src/",
    "openzeppelin-contracts-upgradeable/=lib/lssvm/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/putty-v2/lib/openzeppelin-contracts/contracts/",
    "prb-math/=lib/lssvm/lib/prb-math/contracts/",
    "putty-v2/=lib/putty-v2/src/",
    "solmate/=lib/solmate/src/",
    "weird-erc20/=lib/lssvm/lib/solmate/lib/weird-erc20/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_lpToken","type":"address"},{"internalType":"address","name":"_callOptionToken","type":"address"},{"internalType":"address","name":"_putty","type":"address"},{"internalType":"address","name":"_weth","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"nftAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"AddLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"bondId","type":"uint256"},{"components":[{"internalType":"uint256","name":"rewardPerTokenCheckpoint","type":"uint256"},{"internalType":"uint128","name":"depositAmount","type":"uint128"},{"internalType":"uint32","name":"depositTimestamp","type":"uint32"},{"internalType":"uint8","name":"termIndex","type":"uint8"}],"indexed":false,"internalType":"struct FeeBonding.FeeBond","name":"bond","type":"tuple"}],"name":"FeeStake","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"bondId","type":"uint256"},{"components":[{"internalType":"uint256","name":"rewardPerTokenCheckpoint","type":"uint256"},{"internalType":"uint128","name":"depositAmount","type":"uint128"},{"internalType":"uint32","name":"depositTimestamp","type":"uint32"},{"internalType":"uint8","name":"termIndex","type":"uint8"}],"indexed":false,"internalType":"struct FeeBonding.FeeBond","name":"bond","type":"tuple"}],"name":"FeeUnstake","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"bondId","type":"uint256"},{"components":[{"internalType":"uint256","name":"rewardPerTokenCheckpoint","type":"uint256"},{"internalType":"uint128","name":"depositAmount","type":"uint128"},{"internalType":"uint32","name":"depositTimestamp","type":"uint32"},{"internalType":"uint8","name":"termIndex","type":"uint8"}],"indexed":false,"internalType":"struct OptionBonding.OptionBond","name":"bond","type":"tuple"}],"name":"OptionStake","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"bondId","type":"uint256"},{"components":[{"internalType":"uint256","name":"rewardPerTokenCheckpoint","type":"uint256"},{"internalType":"uint128","name":"depositAmount","type":"uint128"},{"internalType":"uint32","name":"depositTimestamp","type":"uint32"},{"internalType":"uint8","name":"termIndex","type":"uint8"}],"indexed":false,"internalType":"struct OptionBonding.OptionBond","name":"bond","type":"tuple"}],"name":"OptionUnstake","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"nftAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"RemoveLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REWARD_DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STRIKE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOTAL_REWARDS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint256","name":"minPrice","type":"uint256"},{"internalType":"uint256","name":"maxPrice","type":"uint256"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint256","name":"minPrice","type":"uint256"},{"internalType":"uint256","name":"maxPrice","type":"uint256"},{"internalType":"uint256","name":"termIndex","type":"uint256"}],"name":"addLiquidityAndFeeStake","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint256","name":"minPrice","type":"uint256"},{"internalType":"uint256","name":"maxPrice","type":"uint256"},{"internalType":"uint256","name":"termIndex","type":"uint256"}],"name":"addLiquidityAndOptionStake","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"bonds","outputs":[{"components":[{"internalType":"uint256","name":"rewardPerTokenCheckpoint","type":"uint256"},{"internalType":"uint128","name":"depositAmount","type":"uint128"},{"internalType":"uint32","name":"depositTimestamp","type":"uint32"},{"internalType":"uint8","name":"termIndex","type":"uint8"}],"internalType":"struct OptionBonding.OptionBond","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"callOptionToken","outputs":[{"internalType":"contract MintBurnToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"closeWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"closedWhitelist","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"numAssets","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"convertToOption","outputs":[{"internalType":"uint256","name":"longTokenId","type":"uint256"},{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"bool","name":"isCall","type":"bool"},{"internalType":"bool","name":"isLong","type":"bool"},{"internalType":"address","name":"baseAsset","type":"address"},{"internalType":"uint256","name":"strike","type":"uint256"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"address[]","name":"whitelist","type":"address[]"},{"internalType":"address[]","name":"floorTokens","type":"address[]"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"tokenAmount","type":"uint256"}],"internalType":"struct PuttyV2.ERC20Asset[]","name":"erc20Assets","type":"tuple[]"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"internalType":"struct PuttyV2.ERC721Asset[]","name":"erc721Assets","type":"tuple[]"}],"internalType":"struct PuttyV2.Order","name":"shortOrder","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeBondingNft","outputs":[{"internalType":"contract BondingNft","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"feeBonds","outputs":[{"components":[{"internalType":"uint256","name":"rewardPerTokenCheckpoint","type":"uint256"},{"internalType":"uint128","name":"depositAmount","type":"uint128"},{"internalType":"uint32","name":"depositTimestamp","type":"uint32"},{"internalType":"uint8","name":"termIndex","type":"uint8"}],"internalType":"struct FeeBonding.FeeBond","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"feeEarned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"uint256","name":"termIndex","type":"uint256"}],"name":"feeStake","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeStakedTotalSupply","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeTotalBondSupply","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"feeUnstake","outputs":[{"internalType":"uint256","name":"rewardAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"finishAt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"isValidSignature","outputs":[{"internalType":"bytes4","name":"magicValue","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lpToken","outputs":[{"internalType":"contract MintBurnToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"mintTo","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"mintWhitelist","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mintingOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nftReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"optionBondTotalSupply","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"optionBondingNft","outputs":[{"internalType":"contract BondingNft","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"optionEarned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"optionExpiration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"optionRewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"uint256","name":"termIndex","type":"uint256"}],"name":"optionStake","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"optionStakedTotalSupply","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"optionUnstake","outputs":[{"internalType":"uint256","name":"callOptionAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"owner","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pair","outputs":[{"internalType":"contract LSSVMPairMissingEnumerableETH","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"price","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"putty","outputs":[{"internalType":"contract PuttyV2","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint256","name":"minPrice","type":"uint256"},{"internalType":"uint256","name":"maxPrice","type":"uint256"}],"name":"removeLiquidity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_pair","type":"address"}],"name":"setPair","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenUri","type":"address"}],"name":"setTokenUri","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"skim","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"startAt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"termBoosters","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"terms","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenUri","outputs":[{"internalType":"contract ERC721","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"weth","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"whitelistMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"whitelistedSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"bool","name":"isCall","type":"bool"},{"internalType":"bool","name":"isLong","type":"bool"},{"internalType":"address","name":"baseAsset","type":"address"},{"internalType":"uint256","name":"strike","type":"uint256"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"address[]","name":"whitelist","type":"address[]"},{"internalType":"address[]","name":"floorTokens","type":"address[]"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"tokenAmount","type":"uint256"}],"internalType":"struct PuttyV2.ERC20Asset[]","name":"erc20Assets","type":"tuple[]"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"internalType":"struct PuttyV2.ERC721Asset[]","name":"erc721Assets","type":"tuple[]"}],"internalType":"struct PuttyV2.Order[]","name":"orders","type":"tuple[]"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdrawWeth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

6102a060405260006101e081815262093a806102005262278d00610220526276a7006102405262ed4e00610260526301e1338061028052620000449190600662000433565b506040805160c081018252670de0b6b3a76400008152670f43fc2c04ee000060208201526710a741a462780000918101919091526714d1120d7b1600006060820152671bc16d674ec8000060808201526729a2241af62c000060a0820152620000b29060019060066200048b565b506040805160c0810182526000815262093a80602082015262278d00918101919091526276a700606082015262ed4e0060808201526301e1338060a08201526200010190600790600662000433565b506040805160c081018252670de0b6b3a76400008152670f43fc2c04ee000060208201526710a741a462780000918101919091526714d1120d7b1600006060820152671bc16d674ec8000060808201526729a2241af62c000060a08201526200016f9060089060066200048b565b506200018a6304a286006903cfc82e37e9a7400000620004f9565b60c0526200019d4263096601806200051c565b60e052620001b06304a28600426200051c565b6101005242610120819052600a805463ffffffff191663ffffffff9092169190911790556001600c556014805460ff19169055348015620001f057600080fd5b5060405162006b0c38038062006b0c833981016040819052620002139162000561565b6040518060400160405280601481526020017f5768657966757320616e6f6e796d6f7573203a330000000000000000000000008152506040518060400160405280600381526020016255775560e81b81525085858585338a806001600160a01b031660a0816001600160a01b0316815250506040516200029390620004d4565b60408082526013908201527f576865796675204c502046656520426f6e6473000000000000000000000000006060820152608060208201819052600590820152642ba628232160d91b60a082015260c001604051809103906000f08015801562000301573d6000803e3d6000fd5b506001600160a01b03908116608052600680546001600160a01b03191691841691821790556040519091506000907f8292fce18fa69edf4db7b94ea2e58241df0ae57f97e0a6c9b29067028bf92d76908290a3506001600160a01b0380851661016052838116610140528281166101a05281166101c0526040516200038690620004d4565b60408082526016908201527f576865796675204c50204f7074696f6e20426f6e6473000000000000000000006060820152608060208201819052600590820152642ba62827a160d91b60a082015260c001604051809103906000f080158015620003f4573d6000803e3d6000fd5b506001600160a01b03166101805250600d92506200041791508490508262000663565b50600e62000426828262000663565b505050505050506200072f565b82805482825590600052602060002090810192821562000479579160200282015b8281111562000479578251829063ffffffff1690559160200191906001019062000454565b5062000487929150620004e2565b5090565b82805482825590600052602060002090810192821562000479579160200282015b828111156200047957825182906001600160401b0316905591602001919060010190620004ac565b611396806200577683390190565b5b80821115620004875760008155600101620004e3565b6000826200051757634e487b7160e01b600052601260045260246000fd5b500490565b808201808211156200053e57634e487b7160e01b600052601160045260246000fd5b92915050565b80516001600160a01b03811681146200055c57600080fd5b919050565b600080600080608085870312156200057857600080fd5b620005838562000544565b9350620005936020860162000544565b9250620005a36040860162000544565b9150620005b36060860162000544565b905092959194509250565b634e487b7160e01b600052604160045260246000fd5b600181811c90821680620005e957607f821691505b6020821081036200060a57634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156200065e57600081815260208120601f850160051c81016020861015620006395750805b601f850160051c820191505b818110156200065a5782815560010162000645565b5050505b505050565b81516001600160401b038111156200067f576200067f620005be565b6200069781620006908454620005d4565b8462000610565b602080601f831160018114620006cf5760008415620006b65750858301515b600019600386901b1c1916600185901b1785556200065a565b600085815260208120601f198616915b828110156200070057888601518255948401946001909101908401620006df565b50858210156200071f5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c051614f036200087360003960008181610865015281816128b201526130bd015260008181610831015281816122a9015281816122fb0152818161233401528181612a8f01528181612fe60152613f14015260008181610cf701528181611669015281816118270152613702015260008181610ac2015281816113bc0152818161148d0152818161196401528181612c0701528181612cef015261366f0152600081816109e6015281816119fa01526129cb01526000610e90015260008181610b160152818161385c01526138860152600081816108d301526128fc015260008181610c0501526138d401526000818161214001526126640152600081816107fd015281816121d30152818161238701526125410152614f036000f3fe60806040526004361061049f5760003560e01c80635c532b461161025e578063a0712d6811610143578063c212a523116100bb578063cd3daf9d1161008a578063d86f1ab01161006f578063d86f1ab014610f29578063e985e9c514610f3f578063ecc389ba14610f7a57600080fd5b8063cd3daf9d14610eef578063d50cb36414610f0457600080fd5b8063c212a52314610e5e578063c744656514610e7e578063c87b56dd14610eb2578063c8f33c9114610ed257600080fd5b8063b2b5334911610112578063b88d4fde116100f7578063b88d4fde14610dda578063c00119ce14610dfa578063c0aa0e8a14610e3e57600080fd5b8063b2b5334914610da4578063b723b34e14610dba57600080fd5b8063a0712d6814610d2e578063a16a642114610d4e578063a22cb46514610d64578063a8aa1b3114610d8457600080fd5b80637c61ab1e116101d65780638da5cb5b116101a557806395d89b411161018a57806395d89b4114610cd05780639fab026314610ce5578063a035b1fe14610d1957600080fd5b80638da5cb5b14610c9a5780639278cd1a14610cba57600080fd5b80637c61ab1e14610c275780637d01d04d14610c475780637dd0804814610c675780638187f51614610c7a57600080fd5b80636352211e1161022d5780636d23d956116102125780636d23d95614610b3857806370a0823114610bd35780637b0a47ee14610bf357600080fd5b80636352211e14610ae457806367d3b48814610b0457600080fd5b80635c532b46146109b45780635d63fcf4146109d45780635f1c17c014610a085780635fcbd28514610ab057600080fd5b806325513e131161038457806342842e0e116102fc5780634cddc728116102cb5780634dada002116102b05780634dada0021461096b578063586b9a7c146109875780635ade228a1461099c57600080fd5b80634cddc7281461092a5780634d49e87d1461095857600080fd5b806342842e0e146108a157806343c94f3e146108c15780634912fc74146108f55780634bad95101461091557600080fd5b80633781826e116103535780633de4e06b116103385780633de4e06b1461081f5780633fc8cef31461085357806341a6ba711461088757600080fd5b80633781826e146107cb5780633848eecf146107eb57600080fd5b806325513e1314610743578063255f5f551461077557806332cb6b0c14610795578063355e0c5d146107ab57600080fd5b806313af40351161041757806319096746116103e65780631daba63b116103cb5780631daba63b146106ee5780631dd19cb41461070e57806323b872dd1461072357600080fd5b806319096746146106b95780631c2655c5146106d957600080fd5b806313af40351461061e578063150b7a021461063e5780631626ba7e1461068357806318160ddd146106a357600080fd5b8063081812fc1161046e578063097114221161045357806309711422146105b357806309cf6091146105d35780630ba84e85146105f157600080fd5b8063081812fc14610543578063095ea7b31461059157600080fd5b806301ffc9a7146104ab57806304c80eaa146104e057806306fdde031461050e57806307b9d49c1461053057600080fd5b366104a657005b600080fd5b3480156104b757600080fd5b506104cb6104c63660046140cc565b610fa2565b60405190151581526020015b60405180910390f35b3480156104ec57600080fd5b506105006104fb3660046140e9565b610fe6565b6040519081526020016104d7565b34801561051a57600080fd5b5061052361107c565b6040516104d79190614152565b61050061053e3660046141b1565b61110a565b34801561054f57600080fd5b5061057961055e3660046140e9565b6011602052600090815260409020546001600160a01b031681565b6040516001600160a01b0390911681526020016104d7565b34801561059d57600080fd5b506105b16105ac36600461422b565b611130565b005b3480156105bf57600080fd5b506105b16105ce366004614257565b611226565b3480156105df57600080fd5b506105006903cfc82e37e9a740000081565b3480156105fd57600080fd5b5061050061060c3660046142a8565b60166020526000908152604090205481565b34801561062a57600080fd5b506105b16106393660046142a8565b61157f565b34801561064a57600080fd5b5061066a6106593660046142c5565b630a85bd0160e11b95945050505050565b6040516001600160e01b031990911681526020016104d7565b34801561068f57600080fd5b5061066a61069e3660046143fd565b611614565b3480156106af57600080fd5b5061050060135481565b3480156106c557600080fd5b506105006106d43660046140e9565b611650565b3480156106e557600080fd5b50610500611a9e565b3480156106fa57600080fd5b506105b161070936600461422b565b611b33565b34801561071a57600080fd5b50610500611c8a565b34801561072f57600080fd5b506105b161073e366004614487565b611e19565b34801561074f57600080fd5b506003546107609063ffffffff1681565b60405163ffffffff90911681526020016104d7565b34801561078157600080fd5b506105006107903660046144dd565b611fef565b3480156107a157600080fd5b5061050061753081565b3480156107b757600080fd5b50601854610579906001600160a01b031681565b3480156107d757600080fd5b506105006107e63660046140e9565b612277565b3480156107f757600080fd5b506105797f000000000000000000000000000000000000000000000000000000000000000081565b34801561082b57600080fd5b506105797f000000000000000000000000000000000000000000000000000000000000000081565b34801561085f57600080fd5b506105797f000000000000000000000000000000000000000000000000000000000000000081565b34801561089357600080fd5b506014546104cb9060ff1681565b3480156108ad57600080fd5b506105b16108bc366004614487565b612298565b3480156108cd57600080fd5b506105007f000000000000000000000000000000000000000000000000000000000000000081565b34801561090157600080fd5b506105006109103660046140e9565b61236e565b34801561092157600080fd5b50610500612718565b34801561093657600080fd5b5061094a6109453660046144fb565b61277b565b6040516104d79291906146a4565b610500610966366004614257565b612afa565b34801561097757600080fd5b5061050067016345785d8a000081565b34801561099357600080fd5b506105b1612dee565b3480156109a857600080fd5b506105006304a2860081565b3480156109c057600080fd5b506105b16109cf3660046142a8565b612e46565b3480156109e057600080fd5b506105797f000000000000000000000000000000000000000000000000000000000000000081565b348015610a1457600080fd5b50610aa3610a233660046140e9565b604080516080810182526000808252602082018190529181018290526060810191909152506000908152600b60209081526040918290208251608081018452815481526001909101546001600160801b03811692820192909252600160801b820463ffffffff1692810192909252600160a01b900460ff16606082015290565b6040516104d791906146bd565b348015610abc57600080fd5b506105797f000000000000000000000000000000000000000000000000000000000000000081565b348015610af057600080fd5b50610579610aff3660046140e9565b612eb1565b348015610b1057600080fd5b506105007f000000000000000000000000000000000000000000000000000000000000000081565b348015610b4457600080fd5b50610aa3610b533660046140e9565b604080516080810182526000808252602082018190529181018290526060810191909152506000908152600460209081526040918290208251608081018452815481526001909101546001600160801b03811692820192909252600160801b820463ffffffff1692810192909252600160a01b900460ff16606082015290565b348015610bdf57600080fd5b50610500610bee3660046142a8565b612f1b565b348015610bff57600080fd5b506105007f000000000000000000000000000000000000000000000000000000000000000081565b348015610c3357600080fd5b506105b1610c4236600461484d565b612f8f565b348015610c5357600080fd5b50610500610c623660046140e9565b6131a9565b610500610c753660046141b1565b613228565b348015610c8657600080fd5b506105b1610c953660046142a8565b613243565b348015610ca657600080fd5b50600654610579906001600160a01b031681565b348015610cc657600080fd5b5061050060025481565b348015610cdc57600080fd5b50610523613315565b348015610cf157600080fd5b506105797f000000000000000000000000000000000000000000000000000000000000000081565b348015610d2557600080fd5b50610500613322565b348015610d3a57600080fd5b50610500610d493660046140e9565b613367565b348015610d5a57600080fd5b5061050060095481565b348015610d7057600080fd5b506105b1610d7f366004614a36565b61337d565b348015610d9057600080fd5b50601754610579906001600160a01b031681565b348015610db057600080fd5b50610500600c5481565b348015610dc657600080fd5b50610500610dd5366004614a6f565b6133e9565b348015610de657600080fd5b506105b1610df53660046142c5565b6133f6565b348015610e0657600080fd5b50600a54610e26906801000000000000000090046001600160801b031681565b6040516001600160801b0390911681526020016104d7565b348015610e4a57600080fd5b50610500610e593660046140e9565b6134eb565b348015610e6a57600080fd5b50610500610e793660046144dd565b6134fb565b348015610e8a57600080fd5b506105007f000000000000000000000000000000000000000000000000000000000000000081565b348015610ebe57600080fd5b50610523610ecd3660046140e9565b613797565b348015610ede57600080fd5b50600a546107609063ffffffff1681565b348015610efb57600080fd5b50610500613822565b348015610f1057600080fd5b50600a5461076090640100000000900463ffffffff1681565b348015610f3557600080fd5b5061050060155481565b348015610f4b57600080fd5b506104cb610f5a366004614a94565b601260209081526000928352604080842090915290825290205460ff1681565b348015610f8657600080fd5b50600354610e269064010000000090046001600160801b031681565b60006001600160e01b031982167f780e9d63000000000000000000000000000000000000000000000000000000001480610fe05750610fe082613928565b92915050565b60008181526004602052604081206001808201548154849291600160a01b900460ff1690811061101857611018614ac2565b600091825260209091200154600183015461103c91906001600160801b0316614aee565b90506ec097ce7bc90715b34b9f100000000082600001546002546110609190614b0d565b61106a9083614aee565b6110749190614b20565b949350505050565b600d805461108990614b42565b80601f01602080910402602001604051908101604052809291908181526020018280546110b590614b42565b80156111025780601f106110d757610100808354040283529160200191611102565b820191906000526020600020905b8154815290600101906020018083116110e557829003601f168201915b505050505081565b60008061111987878787612afa565b905061112581846134fb565b979650505050505050565b6000818152600f60205260409020546001600160a01b03163381148061117957506001600160a01b038116600090815260126020908152604080832033845290915290205460ff165b6111ca5760405162461bcd60e51b815260206004820152600e60248201527f4e4f545f415554484f52495a454400000000000000000000000000000000000060448201526064015b60405180910390fd5b60008281526011602052604080822080546001600160a01b0319166001600160a01b0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b6000611230613322565b90508181111580156112425750828110155b61128e5760405162461bcd60e51b815260206004820152600e60248201527f507269636520736c69707061676500000000000000000000000000000000000060448201526064016111c1565b6000611298612718565b905060006112a4611a9e565b90506000816112b38885614aee565b6112bd9190614b20565b90506112db6112cc8285614b0d565b6112d68985614b0d565b6139c1565b6017546040516378a1085360e11b8152600481018390526001600160a01b039091169063f14210a690602401600060405180830381600087803b15801561132157600080fd5b505af1158015611335573d6000803e3d6000fd5b50506017546040517f13edab810000000000000000000000000000000000000000000000000000000081526001600160a01b0390911692506313edab8191506113869030908c908c90600401614b7c565b600060405180830381600087803b1580156113a057600080fd5b505af11580156113b4573d6000803e3d6000fd5b5050505060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611418573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061143c9190614bde565b905060008361144b8a84614aee565b6114559190614b20565b6040517f9dc29fac000000000000000000000000000000000000000000000000000000008152336004820152602481018290529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690639dc29fac90604401600060405180830381600087803b1580156114d957600080fd5b505af11580156114ed573d6000803e3d6000fd5b5050505060005b898110156115275761151f30338d8d8581811061151357611513614ac2565b90506020020135613ac3565b6001016114f4565b506115323384613ce3565b60408051848152602081018b90529081018290527f462ff1f90b66e3549a190bb471a2276749250543bad2ce9c21f706d882a59dad9060600160405180910390a150505050505050505050565b6006546001600160a01b031633146115c85760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8292fce18fa69edf4db7b94ea2e58241df0ae57f97e0a6c9b29067028bf92d7690600090a350565b6000600c54600214611627576000611649565b7f1626ba7e000000000000000000000000000000000000000000000000000000005b9392505050565b6040516331a9108f60e11b8152600481018290526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156116b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116dc9190614bf7565b6001600160a01b0316336001600160a01b0316146117285760405162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b60448201526064016111c1565b6000828152600b60209081526040918290208251608081018452815481526001909101546001600160801b03811692820192909252600160801b820463ffffffff1692810192909252600160a01b900460ff166060820181905260078054909190811061179757611797614ac2565b9060005260206000200154816040015163ffffffff166117b79190614c14565b4210156118065760405162461bcd60e51b815260206004820152601060248201527f426f6e64206e6f74206d6174757265640000000000000000000000000000000060448201526064016111c1565b61180e613822565b600955604051630852cd8d60e31b8152600481018490527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906342966c6890602401600060405180830381600087803b15801561187357600080fd5b505af1158015611887573d6000803e3d6000fd5b5050600a805463ffffffff19164263ffffffff16179055505060208101516060820151600880546001600160801b0390931692670de0b6b3a76400009260ff169081106118d6576118d6614ac2565b9060005260206000200154826118ec9190614aee565b6118f69190614b20565b600a805460089061191d9084906801000000000000000090046001600160801b0316614c27565b82546001600160801b039182166101009390930a92830291909202199091161790555060405163a9059cbb60e01b8152336004820152602481018290526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb906044016020604051808303816000875af11580156119ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119d19190614c4e565b506119db846131a9565b6040516340c10f1960e01b8152336004820152602481018290529093507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906340c10f1990604401600060405180830381600087803b158015611a4657600080fd5b505af1158015611a5a573d6000803e3d6000fd5b505050507fe44694c943742657abee88b2aec7c98d7f392a3302dd496e31b5544e537e15e08483604051611a8f929190614c6b565b60405180910390a15050919050565b601754604080517f12b495a800000000000000000000000000000000000000000000000000000000815290516000926001600160a01b0316916312b495a89160048083019260209291908290030181865afa158015611b01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b259190614cb2565b6001600160801b0316905090565b6006546001600160a01b03163314611b7c5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b60145460ff1615611bcf5760405162461bcd60e51b815260206004820152601960248201527f57686974656c69737420686173206265656e20636c6f7365640000000000000060448201526064016111c1565b6001600160a01b0382166000908152601660205260408120546015805491928392611bfb908490614b0d565b925050819055508160156000828254611c149190614c14565b90915550506015546175301015611c6d5760405162461bcd60e51b815260206004820152601a60248201527f4d617820737570706c7920616c7265616479207265616368656400000000000060448201526064016111c1565b506001600160a01b03909116600090815260166020526040902055565b600080600560009054906101000a90046001600160a01b03166001600160a01b031663398482d86040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ce0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d049190614cb2565b6005546001600160801b039190911691506000906001600160a01b0316318210611d2f576000611d47565b600554611d479083906001600160a01b031631614b0d565b6005546040516378a1085360e11b8152600481018390529192506001600160a01b03169063f14210a690602401600060405180830381600087803b158015611d8e57600080fd5b505af1158015611da2573d6000803e3d6000fd5b50505050600081118015611dc8575060035464010000000090046001600160801b031615155b15610fe05760035464010000000090046001600160801b0316611df382670de0b6b3a7640000614aee565b611dfd9190614b20565b60026000828254611e0e9190614c14565b909155505092915050565b6000818152600f60205260409020546001600160a01b03848116911614611e6f5760405162461bcd60e51b815260206004820152600a60248201526957524f4e475f46524f4d60b01b60448201526064016111c1565b6001600160a01b038216611eb95760405162461bcd60e51b81526020600482015260116024820152701253959053125117d49150d25412515395607a1b60448201526064016111c1565b336001600160a01b0384161480611ef357506001600160a01b038316600090815260126020908152604080832033845290915290205460ff165b80611f1457506000818152601160205260409020546001600160a01b031633145b611f605760405162461bcd60e51b815260206004820152600e60248201527f4e4f545f415554484f52495a454400000000000000000000000000000000000060448201526064016111c1565b6001600160a01b038084166000818152601060209081526040808320805460001901905593861680835284832080546001019055858352600f825284832080546001600160a01b03199081168317909155601190925284832080549092169091559251849392917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b6000611ff9611c8a565b50600380546001919060009061201690849063ffffffff16614ccf565b82546101009290920a63ffffffff818102199093169183160217909155600354811660008181526004602052604090206002548155600181810180546001600160801b038a166001600160a01b031990911617600160801b42909616959095029490941760ff60a01b1916600160a01b60ff8916021790935582549194509250670de0b6b3a76400009190859081106120b1576120b1614ac2565b9060005260206000200154856001600160801b03166120d09190614aee565b6120da9190614b20565b600380546004906120fd90849064010000000090046001600160801b0316614cec565b82546101009290920a6001600160801b038181021990931691831602179091556040516323b872dd60e01b815233600482015230602482015290861660448201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691506323b872dd906064016020604051808303816000875af1158015612192573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b69190614c4e565b506040516340c10f1960e01b8152336004820152602481018390527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906340c10f1990604401600060405180830381600087803b15801561221f57600080fd5b505af1158015612233573d6000803e3d6000fd5b505050507fbcfb553f47b13ce6eaa94a5a3d32329da2677aaaeb218179b18f23aca1db4c998282604051612268929190614d0c565b60405180910390a15092915050565b6008818154811061228757600080fd5b600091825260209091200154905081565b600c546002036122a757505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316836001600160a01b03161480156122e9575061753081115b801561231d5750336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016145b1561235e5761235861233182600019614b0d565b837f0000000000000000000000000000000000000000000000000000000000000000613d3e565b50505050565b612369838383613e64565b505050565b6040516331a9108f60e11b8152600481018290526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156123d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123fa9190614bf7565b6001600160a01b0316336001600160a01b0316146124465760405162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b60448201526064016111c1565b60008281526004602090815260408083208151608081018352815481526001909101546001600160801b03811693820193909352600160801b830463ffffffff1691810191909152600160a01b90910460ff1660608201819052825491929181106124b3576124b3614ac2565b9060005260206000200154816040015163ffffffff166124d39190614c14565b4210156125225760405162461bcd60e51b815260206004820152601060248201527f426f6e64206e6f74206d6174757265640000000000000000000000000000000060448201526064016111c1565b61252a611c8a565b50604051630852cd8d60e31b8152600481018490527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906342966c6890602401600060405180830381600087803b15801561258d57600080fd5b505af11580156125a1573d6000803e3d6000fd5b50505050600081602001516001600160801b03169050670de0b6b3a76400006001836060015160ff16815481106125da576125da614ac2565b9060005260206000200154826125f09190614aee565b6125fa9190614b20565b6003805460049061261d90849064010000000090046001600160801b0316614c27565b82546001600160801b039182166101009390930a92830291909202199091161790555060405163a9059cbb60e01b8152336004820152602481018290526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb906044016020604051808303816000875af11580156126ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126d19190614c4e565b506126db84610fe6565b92506126e73384613ce3565b7f68fdf814c7f7091db14b00c71885abc4f242a48abe180938ae773cf9c71eeac48483604051611a8f929190614c6b565b601754604080517f398482d800000000000000000000000000000000000000000000000000000000815290516000926001600160a01b03169163398482d89160048083019260209291908290030181865afa158015611b01573d6000803e3d6000fd5b60006127fe604051806101a0016040528060006001600160a01b0316815260200160001515815260200160001515815260200160006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160008152602001606081526020016060815260200160608152602001606081525090565b6000841161284e5760405162461bcd60e51b815260206004820152601f60248201527f4d75737420636f6e76657274206174206c65617374206f6e652061737365740060448201526064016111c1565b603284111561289f5760405162461bcd60e51b815260206004820152601e60248201527f4d75737420636f6e76657274203530206f72206c65737320617373657473000060448201526064016111c1565b30815260016020820152600060408201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031660608201526128f18467016345785d8a0000614aee565b6080820152612920427f0000000000000000000000000000000000000000000000000000000000000000614b0d565b60c0820152612930426001614c14565b60e0820152610100810183905260408051600180825281830190925290816020015b6040805180820190915260008082526020820152815260200190600190039081612952575050610180820152604080518082019091523081526020810161299b86600019614b0d565b8152508161018001516000815181106129b6576129b6614ac2565b60209081029190910101526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016639dc29fac33612a0387670de0b6b3a7640000614aee565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401600060405180830381600087803b158015612a4957600080fd5b505af1158015612a5d573d6000803e3d6000fd5b50505050612a6a81613ece565b6040516323b872dd60e01b8152306004820152336024820152604481018290529092507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906323b872dd90606401600060405180830381600087803b158015612adb57600080fd5b505af1158015612aef573d6000803e3d6000fd5b505050509250929050565b600080612b05612718565b90506000612b11611a9e565b905060008083118015612b245750600082115b612b2f576000612b39565b612b398284614b20565b9050848111158015612b4b5750858110155b612b975760405162461bcd60e51b815260206004820152600e60248201527f507269636520736c69707061676500000000000000000000000000000000000060448201526064016111c1565b655af3107a40003411612bec5760405162461bcd60e51b815260206004820152601f60248201527f4d7573742073656e64206174206c6561737420302e303030312065746865720060448201526064016111c1565b612c03612bf93485614c14565b6112d68985614c14565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c879190614bde565b90508015612cc657612cc184612c9d3484614aee565b612ca79190614b20565b84612cb28b85614aee565b612cbc9190614b20565b613f98565b612cd0565b612cd08834614aee565b6040516340c10f1960e01b8152336004820152602481018290529095507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906340c10f1990604401600060405180830381600087803b158015612d3b57600080fd5b505af1158015612d4f573d6000803e3d6000fd5b5050505060005b88811015612d8a57601754612d829033906001600160a01b03168c8c8581811061151357611513614ac2565b600101612d56565b50601754612da1906001600160a01b031634613ce3565b60408051348152602081018a90529081018690527ff75993dbe1645872cbbea6395e1feebee76b435baf0e4d62d7eac269c6f57b249060600160405180910390a150505050949350505050565b6006546001600160a01b03163314612e375760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b6014805460ff19166001179055565b6006546001600160a01b03163314612e8f5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b601880546001600160a01b0319166001600160a01b0392909216919091179055565b6000818152600f60205260409020546001600160a01b031680612f165760405162461bcd60e51b815260206004820152600a60248201527f4e4f545f4d494e5445440000000000000000000000000000000000000000000060448201526064016111c1565b919050565b60006001600160a01b038216612f735760405162461bcd60e51b815260206004820152600c60248201527f5a45524f5f41444452455353000000000000000000000000000000000000000060448201526064016111c1565b506001600160a01b031660009081526010602052604090205490565b6006546001600160a01b03163314612fd85760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b60005b825181101561308e577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316631913cfd784838151811061302557613025614ac2565b60200260200101516040518263ffffffff1660e01b81526004016130499190614d50565b600060405180830381600087803b15801561306357600080fd5b505af1158015613077573d6000803e3d6000fd5b50505050808061308690614d63565b915050612fdb565b506040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a9059cbb90839083906370a0823190602401602060405180830381865afa158015613116573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061313a9190614bde565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044016020604051808303816000875af1158015613185573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123699190614c4e565b6000818152600b602052604081206001810154600880548492600160a01b900460ff169081106131db576131db614ac2565b60009182526020909120015460018301546131ff91906001600160801b0316614aee565b90506ec097ce7bc90715b34b9f1000000000826000015461321e613822565b6110609190614b0d565b60008061323787878787612afa565b90506111258184611fef565b6006546001600160a01b0316331461328c5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b6017546001600160a01b0316156132e55760405162461bcd60e51b815260206004820152601060248201527f5061697220616c7265616479207365740000000000000000000000000000000060448201526064016111c1565b601780546001600160a01b03929092166001600160a01b0319928316811790915560058054909216179055565b50565b600e805461108990614b42565b60008061332d612718565b90506000613339611a9e565b905060008211801561334b5750600081115b613356576000613360565b6133608183614b20565b9250505090565b600061337382336133e9565b5050601354919050565b3360008181526012602090815260408083206001600160a01b03871680855290835292819020805460ff191686151590811790915590519081529192917f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a35050565b6000611649838333613d3e565b613401858585611e19565b6001600160a01b0384163b15806134985750604051630a85bd0160e11b808252906001600160a01b0386169063150b7a02906134499033908a90899089908990600401614d7c565b6020604051808303816000875af1158015613468573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061348c9190614dd0565b6001600160e01b031916145b6134e45760405162461bcd60e51b815260206004820152601060248201527f554e534146455f524543495049454e540000000000000000000000000000000060448201526064016111c1565b5050505050565b6007818154811061228757600080fd5b6000613505613822565b600955600a80546001919060049061352c908490640100000000900463ffffffff16614ccf565b82546101009290920a63ffffffff818102199093169183160217909155600a8054640100000000900482166000818152600b6020526040902060095481556001810180546001600160801b038a166001600160a01b031990911617600160801b429096169586021760ff60a01b1916600160a01b60ff8a1602179055825463ffffffff191690931790915560088054919450919250670de0b6b3a76400009190859081106135dc576135dc614ac2565b9060005260206000200154856001600160801b03166135fb9190614aee565b6136059190614b20565b600a805460089061362c9084906801000000000000000090046001600160801b0316614cec565b82546101009290920a6001600160801b038181021990931691831602179091556040516323b872dd60e01b815233600482015230602482015290861660448201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691506323b872dd906064016020604051808303816000875af11580156136c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136e59190614c4e565b506040516340c10f1960e01b8152336004820152602481018390527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906340c10f1990604401600060405180830381600087803b15801561374e57600080fd5b505af1158015613762573d6000803e3d6000fd5b505050507fe92e7a07bbbf0885cfe2769d6491097062ce995593b84a32f347b92eb74ac1c78282604051612268929190614d0c565b6018546040517fc87b56dd000000000000000000000000000000000000000000000000000000008152600481018390526060916001600160a01b03169063c87b56dd90602401600060405180830381865afa1580156137fa573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610fe09190810190614ded565b600a546000906801000000000000000090046001600160801b0316810361384a575060095490565b600a546000906138809063ffffffff167f0000000000000000000000000000000000000000000000000000000000000000613f98565b6138aa427f0000000000000000000000000000000000000000000000000000000000000000613f98565b6138b49190614b0d565b600a549091506801000000000000000090046001600160801b03166138f97f000000000000000000000000000000000000000000000000000000000000000083614aee565b61390b90670de0b6b3a7640000614aee565b6139159190614b20565b6009546139229190614c14565b91505090565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000006001600160e01b03198316148061398b57507f80ac58cd000000000000000000000000000000000000000000000000000000006001600160e01b03198316145b80610fe05750506001600160e01b0319167f5b5e139f000000000000000000000000000000000000000000000000000000001490565b6017546040517fd8a1890c0000000000000000000000000000000000000000000000000000000081526001600160801b03841660048201526001600160a01b039091169063d8a1890c90602401600060405180830381600087803b158015613a2857600080fd5b505af1158015613a3c573d6000803e3d6000fd5b50506017546040517f6809f6640000000000000000000000000000000000000000000000000000000081526001600160801b03851660048201526001600160a01b039091169250636809f6649150602401600060405180830381600087803b158015613aa757600080fd5b505af1158015613abb573d6000803e3d6000fd5b505050505050565b6000818152600f60205260409020546001600160a01b03848116911614613b195760405162461bcd60e51b815260206004820152600a60248201526957524f4e475f46524f4d60b01b60448201526064016111c1565b6001600160a01b038216613b635760405162461bcd60e51b81526020600482015260116024820152701253959053125117d49150d25412515395607a1b60448201526064016111c1565b6001600160a01b038084166000818152601060209081526040808320805460001901905593861680835284832080546001019055858352600f825284832080546001600160a01b03199081168317909155601190925284832080549092169091559251849392917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a46001600160a01b0382163b1580613c975750604051630a85bd0160e11b8082523360048301526001600160a01b03858116602484015260448301849052608060648401526000608484015290919084169063150b7a029060a4015b6020604051808303816000875af1158015613c67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c8b9190614dd0565b6001600160e01b031916145b6123695760405162461bcd60e51b815260206004820152601060248201527f554e534146455f524543495049454e540000000000000000000000000000000060448201526064016111c1565b600080600080600085875af19050806123695760405162461bcd60e51b815260206004820152601360248201527f4554485f5452414e534645525f4641494c45440000000000000000000000000060448201526064016111c1565b6001600160a01b038116600090815260166020526040812054841115613da65760405162461bcd60e51b815260206004820152601f60248201527f4e6f742077686974656c697374656420666f72207468697320616d6f756e740060448201526064016111c1565b6013545b84601354613db89190614c14565b811015613de557613dd384613dce836001614c14565b613fae565b80613ddd81614d63565b915050613daa565b506001600160a01b03831660009081526010602052604081208054869290613e0e908490614c14565b925050819055508360136000828254613e279190614c14565b90915550506001600160a01b03821660009081526016602052604081208054869290613e54908490614b0d565b9091555050601354949350505050565b613e6f838383611e19565b6001600160a01b0382163b1580613c975750604051630a85bd0160e11b8082523360048301526001600160a01b03858116602484015260448301849052608060648401526000608484015290919084169063150b7a029060a401613c48565b6002600c5560408051600080825260208201928390527f68840dd40000000000000000000000000000000000000000000000000000000090925260606001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166368840dd4613f4886848660248101614e64565b6020604051808303816000875af1158015613f67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f8b9190614bde565b6001600c55949350505050565b6000818310613fa75781611649565b5090919050565b6001600160a01b038216613ff85760405162461bcd60e51b81526020600482015260116024820152701253959053125117d49150d25412515395607a1b60448201526064016111c1565b6000818152600f60205260409020546001600160a01b03161561405d5760405162461bcd60e51b815260206004820152600e60248201527f414c52454144595f4d494e54454400000000000000000000000000000000000060448201526064016111c1565b6000818152600f602052604080822080546001600160a01b0319166001600160a01b03861690811790915590518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b6001600160e01b03198116811461331257600080fd5b6000602082840312156140de57600080fd5b8135611649816140b6565b6000602082840312156140fb57600080fd5b5035919050565b60005b8381101561411d578181015183820152602001614105565b50506000910152565b6000815180845261413e816020860160208601614102565b601f01601f19169290920160200192915050565b6020815260006116496020830184614126565b60008083601f84011261417757600080fd5b50813567ffffffffffffffff81111561418f57600080fd5b6020830191508360208260051b85010111156141aa57600080fd5b9250929050565b6000806000806000608086880312156141c957600080fd5b853567ffffffffffffffff8111156141e057600080fd5b6141ec88828901614165565b9099909850602088013597604081013597506060013595509350505050565b6001600160a01b038116811461331257600080fd5b8035612f168161420b565b6000806040838503121561423e57600080fd5b82356142498161420b565b946020939093013593505050565b6000806000806060858703121561426d57600080fd5b843567ffffffffffffffff81111561428457600080fd5b61429087828801614165565b90989097506020870135966040013595509350505050565b6000602082840312156142ba57600080fd5b81356116498161420b565b6000806000806000608086880312156142dd57600080fd5b85356142e88161420b565b945060208601356142f88161420b565b935060408601359250606086013567ffffffffffffffff8082111561431c57600080fd5b818801915088601f83011261433057600080fd5b81358181111561433f57600080fd5b89602082850101111561435157600080fd5b9699959850939650602001949392505050565b634e487b7160e01b600052604160045260246000fd5b6040516101a0810167ffffffffffffffff8111828210171561439e5761439e614364565b60405290565b604051601f8201601f1916810167ffffffffffffffff811182821017156143cd576143cd614364565b604052919050565b600067ffffffffffffffff8211156143ef576143ef614364565b50601f01601f191660200190565b6000806040838503121561441057600080fd5b82359150602083013567ffffffffffffffff81111561442e57600080fd5b8301601f8101851361443f57600080fd5b803561445261444d826143d5565b6143a4565b81815286602083850101111561446757600080fd5b816020840160208301376000602083830101528093505050509250929050565b60008060006060848603121561449c57600080fd5b83356144a78161420b565b925060208401356144b78161420b565b929592945050506040919091013590565b6001600160801b038116811461331257600080fd5b600080604083850312156144f057600080fd5b8235614249816144c8565b6000806040838503121561450e57600080fd5b50508035926020909101359150565b600081518084526020808501945080840160005b838110156145565781516001600160a01b031687529582019590820190600101614531565b509495945050505050565b600081518084526020808501945080840160005b8381101561455657815180516001600160a01b031688528301518388015260409096019590820190600101614575565b80516001600160a01b0316825260006101a060208301516145ca602086018215159052565b5060408301516145de604086018215159052565b5060608301516145f960608601826001600160a01b03169052565b506080830151608085015260a083015160a085015260c083015160c085015260e083015160e08501526101008084015181860152506101208084015182828701526146468387018261451d565b925050506101408084015185830382870152614662838261451d565b92505050610160808401518583038287015261467e8382614561565b92505050610180808401518583038287015261469a8382614561565b9695505050505050565b82815260406020820152600061107460408301846145a5565b815181526020808301516001600160801b03169082015260408083015163ffffffff169082015260608083015160ff169082015260808101610fe0565b600067ffffffffffffffff82111561471457614714614364565b5060051b60200190565b801515811461331257600080fd5b8035612f168161471e565b600082601f83011261474857600080fd5b8135602061475861444d836146fa565b82815260059290921b8401810191818101908684111561477757600080fd5b8286015b8481101561479b57803561478e8161420b565b835291830191830161477b565b509695505050505050565b600082601f8301126147b757600080fd5b813560206147c761444d836146fa565b82815260069290921b840181019181810190868411156147e657600080fd5b8286015b8481101561479b57604080828a0312156148045760008081fd5b805181810181811067ffffffffffffffff8211171561482557614825614364565b9091528135906148348261420b565b90815281850135858201528352918301916040016147ea565b6000806040838503121561486057600080fd5b823567ffffffffffffffff8082111561487857600080fd5b818501915085601f83011261488c57600080fd5b8135602061489c61444d836146fa565b82815260059290921b840181019181810190898411156148bb57600080fd5b8286015b84811015614a19578035868111156148d657600080fd5b87016101a0818d03601f190112156148ed57600080fd5b6148f561437a565b614900868301614220565b815261490e6040830161472c565b8682015261491e6060830161472c565b604082015261492f60808301614220565b606082015260a0820135608082015260c082013560a082015260e082013560c082015261010082013560e08201526101208201356101008201526101408201358881111561497c57600080fd5b61498a8e8883860101614737565b61012083015250610160820135888111156149a457600080fd5b6149b28e8883860101614737565b6101408301525061018080830135898111156149cd57600080fd5b6149db8f89838701016147a6565b610160840152506101a0830135898111156149f557600080fd5b614a038f89838701016147a6565b91830191909152508452509183019183016148bf565b509650614a299050878201614220565b9450505050509250929050565b60008060408385031215614a4957600080fd5b8235614a548161420b565b91506020830135614a648161471e565b809150509250929050565b60008060408385031215614a8257600080fd5b823591506020830135614a648161420b565b60008060408385031215614aa757600080fd5b8235614ab28161420b565b91506020830135614a648161420b565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615614b0857614b08614ad8565b500290565b81810381811115610fe057610fe0614ad8565b600082614b3d57634e487b7160e01b600052601260045260246000fd5b500490565b600181811c90821680614b5657607f821691505b602082108103614b7657634e487b7160e01b600052602260045260246000fd5b50919050565b6001600160a01b03841681526040602082015281604082015260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115614bc457600080fd5b8260051b8085606085013791909101606001949350505050565b600060208284031215614bf057600080fd5b5051919050565b600060208284031215614c0957600080fd5b81516116498161420b565b80820180821115610fe057610fe0614ad8565b6001600160801b03828116828216039080821115614c4757614c47614ad8565b5092915050565b600060208284031215614c6057600080fd5b81516116498161471e565b82815260a081016116496020830184805182526001600160801b03602082015116602083015263ffffffff604082015116604083015260ff60608201511660608301525050565b600060208284031215614cc457600080fd5b8151611649816144c8565b63ffffffff818116838216019080821115614c4757614c47614ad8565b6001600160801b03818116838216019080821115614c4757614c47614ad8565b82815260a08101611649602083018480548252600101546001600160801b0381166020830152608081901c63ffffffff16604083015260a01c60ff16606090910152565b60208152600061164960208301846145a5565b600060018201614d7557614d75614ad8565b5060010190565b60006001600160a01b03808816835280871660208401525084604083015260806060830152826080830152828460a0840137600060a0848401015260a0601f19601f85011683010190509695505050505050565b600060208284031215614de257600080fd5b8151611649816140b6565b600060208284031215614dff57600080fd5b815167ffffffffffffffff811115614e1657600080fd5b8201601f81018413614e2757600080fd5b8051614e3561444d826143d5565b818152856020838501011115614e4a57600080fd5b614e5b826020830160208601614102565b95945050505050565b606081526000614e7760608301866145a5565b602083820381850152614e8a8287614126565b8481036040860152855180825282870193509082019060005b81811015614ebf57845183529383019391830191600101614ea3565b50909897505050505050505056fea26469706673582212201b04b511c5626fcd22953ba534ee7e24a01bb31b8c714bae08eb7eacd16df90b64736f6c6343000810003360806040523480156200001157600080fd5b506040516200139638038062001396833981016040819052620000349162000170565b338282600062000045838262000269565b50600162000054828262000269565b5050600680546001600160a01b0319166001600160a01b0384169081179091556040519091506000907f8292fce18fa69edf4db7b94ea2e58241df0ae57f97e0a6c9b29067028bf92d76908290a350505062000335565b634e487b7160e01b600052604160045260246000fd5b600082601f830112620000d357600080fd5b81516001600160401b0380821115620000f057620000f0620000ab565b604051601f8301601f19908116603f011681019082821181831017156200011b576200011b620000ab565b816040528381526020925086838588010111156200013857600080fd5b600091505b838210156200015c57858201830151818301840152908201906200013d565b600093810190920192909252949350505050565b600080604083850312156200018457600080fd5b82516001600160401b03808211156200019c57600080fd5b620001aa86838701620000c1565b93506020850151915080821115620001c157600080fd5b50620001d085828601620000c1565b9150509250929050565b600181811c90821680620001ef57607f821691505b6020821081036200021057634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156200026457600081815260208120601f850160051c810160208610156200023f5750805b601f850160051c820191505b8181101562000260578281556001016200024b565b5050505b505050565b81516001600160401b03811115620002855762000285620000ab565b6200029d81620002968454620001da565b8462000216565b602080601f831160018114620002d55760008415620002bc5750858301515b600019600386901b1c1916600185901b17855562000260565b600085815260208120601f198616915b828110156200030657888601518255948401946001909101908401620002e5565b5085821015620003255787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b61105180620003456000396000f3fe608060405234801561001057600080fd5b506004361061011b5760003560e01c806342966c68116100b257806395d89b4111610081578063b88d4fde11610066578063b88d4fde14610274578063c87b56dd14610287578063e985e9c5146102a857600080fd5b806395d89b4114610259578063a22cb4651461026157600080fd5b806342966c68146101ff5780636352211e1461021257806370a08231146102255780638da5cb5b1461024657600080fd5b806313af4035116100ee57806313af4035146101b357806323b872dd146101c657806340c10f19146101d957806342842e0e146101ec57600080fd5b806301ffc9a71461012057806306fdde0314610148578063081812fc1461015d578063095ea7b31461019e575b600080fd5b61013361012e366004610d22565b6102d6565b60405190151581526020015b60405180910390f35b610150610373565b60405161013f9190610d46565b61018661016b366004610d94565b6004602052600090815260409020546001600160a01b031681565b6040516001600160a01b03909116815260200161013f565b6101b16101ac366004610dc4565b610401565b005b6101b16101c1366004610dee565b6104f7565b6101b16101d4366004610e09565b61058c565b6101b16101e7366004610dc4565b610761565b6101b16101fa366004610e09565b6107b8565b6101b161020d366004610d94565b6108bd565b610186610220366004610d94565b610912565b610238610233366004610dee565b610969565b60405190815260200161013f565b600654610186906001600160a01b031681565b6101506109ce565b6101b161026f366004610e45565b6109db565b6101b1610282366004610e81565b610a47565b610150610295366004610d94565b5060408051602081019091526000815290565b6101336102b6366004610f1c565b600560209081526000928352604080842090915290825290205460ff1681565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000006001600160e01b03198316148061033957507f80ac58cd000000000000000000000000000000000000000000000000000000006001600160e01b03198316145b8061036d57507f5b5e139f000000000000000000000000000000000000000000000000000000006001600160e01b03198316145b92915050565b6000805461038090610f4f565b80601f01602080910402602001604051908101604052809291908181526020018280546103ac90610f4f565b80156103f95780601f106103ce576101008083540402835291602001916103f9565b820191906000526020600020905b8154815290600101906020018083116103dc57829003601f168201915b505050505081565b6000818152600260205260409020546001600160a01b03163381148061044a57506001600160a01b038116600090815260056020908152604080832033845290915290205460ff165b61049b5760405162461bcd60e51b815260206004820152600e60248201527f4e4f545f415554484f52495a454400000000000000000000000000000000000060448201526064015b60405180910390fd5b60008281526004602052604080822080546001600160a01b0319166001600160a01b0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b6006546001600160a01b031633146105405760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401610492565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8292fce18fa69edf4db7b94ea2e58241df0ae57f97e0a6c9b29067028bf92d7690600090a350565b6000818152600260205260409020546001600160a01b038481169116146105f55760405162461bcd60e51b815260206004820152600a60248201527f57524f4e475f46524f4d000000000000000000000000000000000000000000006044820152606401610492565b6001600160a01b03821661064b5760405162461bcd60e51b815260206004820152601160248201527f494e56414c49445f524543495049454e540000000000000000000000000000006044820152606401610492565b336001600160a01b038416148061068557506001600160a01b038316600090815260056020908152604080832033845290915290205460ff165b806106a657506000818152600460205260409020546001600160a01b031633145b6106f25760405162461bcd60e51b815260206004820152600e60248201527f4e4f545f415554484f52495a45440000000000000000000000000000000000006044820152606401610492565b600081815260026020908152604080832080546001600160a01b038088166001600160a01b031992831681179093556004909452828520805490911690559051849391928716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b6006546001600160a01b031633146107aa5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401610492565b6107b48282610b3c565b5050565b6107c383838361058c565b6001600160a01b0382163b158061086c5750604051630a85bd0160e11b8082523360048301526001600160a01b03858116602484015260448301849052608060648401526000608484015290919084169063150b7a029060a4016020604051808303816000875af115801561083c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108609190610f89565b6001600160e01b031916145b6108b85760405162461bcd60e51b815260206004820152601060248201527f554e534146455f524543495049454e54000000000000000000000000000000006044820152606401610492565b505050565b6006546001600160a01b031633146109065760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401610492565b61090f81610c50565b50565b6000818152600260205260409020546001600160a01b0316806109645760405162461bcd60e51b815260206004820152600a6024820152691393d517d3525395115160b21b6044820152606401610492565b919050565b60006001600160a01b0382166109c15760405162461bcd60e51b815260206004820152600c60248201527f5a45524f5f4144445245535300000000000000000000000000000000000000006044820152606401610492565b61036d6001600019610fa6565b6001805461038090610f4f565b3360008181526005602090815260408083206001600160a01b03871680855290835292819020805460ff191686151590811790915590519081529192917f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a35050565b610a5285858561058c565b6001600160a01b0384163b1580610ae95750604051630a85bd0160e11b808252906001600160a01b0386169063150b7a0290610a9a9033908a90899089908990600401610fc7565b6020604051808303816000875af1158015610ab9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610add9190610f89565b6001600160e01b031916145b610b355760405162461bcd60e51b815260206004820152601060248201527f554e534146455f524543495049454e54000000000000000000000000000000006044820152606401610492565b5050505050565b6001600160a01b038216610b925760405162461bcd60e51b815260206004820152601160248201527f494e56414c49445f524543495049454e540000000000000000000000000000006044820152606401610492565b6000818152600260205260409020546001600160a01b031615610bf75760405162461bcd60e51b815260206004820152600e60248201527f414c52454144595f4d494e5445440000000000000000000000000000000000006044820152606401610492565b60008181526002602052604080822080546001600160a01b0319166001600160a01b03861690811790915590518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b6000818152600260205260409020546001600160a01b031680610ca25760405162461bcd60e51b815260206004820152600a6024820152691393d517d3525395115160b21b6044820152606401610492565b600082815260026020908152604080832080546001600160a01b031990811690915560049092528083208054909216909155518391906001600160a01b038416907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908390a45050565b6001600160e01b03198116811461090f57600080fd5b600060208284031215610d3457600080fd5b8135610d3f81610d0c565b9392505050565b600060208083528351808285015260005b81811015610d7357858101830151858201604001528201610d57565b506000604082860101526040601f19601f8301168501019250505092915050565b600060208284031215610da657600080fd5b5035919050565b80356001600160a01b038116811461096457600080fd5b60008060408385031215610dd757600080fd5b610de083610dad565b946020939093013593505050565b600060208284031215610e0057600080fd5b610d3f82610dad565b600080600060608486031215610e1e57600080fd5b610e2784610dad565b9250610e3560208501610dad565b9150604084013590509250925092565b60008060408385031215610e5857600080fd5b610e6183610dad565b915060208301358015158114610e7657600080fd5b809150509250929050565b600080600080600060808688031215610e9957600080fd5b610ea286610dad565b9450610eb060208701610dad565b935060408601359250606086013567ffffffffffffffff80821115610ed457600080fd5b818801915088601f830112610ee857600080fd5b813581811115610ef757600080fd5b896020828501011115610f0957600080fd5b9699959850939650602001949392505050565b60008060408385031215610f2f57600080fd5b610f3883610dad565b9150610f4660208401610dad565b90509250929050565b600181811c90821680610f6357607f821691505b602082108103610f8357634e487b7160e01b600052602260045260246000fd5b50919050565b600060208284031215610f9b57600080fd5b8151610d3f81610d0c565b8181038181111561036d57634e487b7160e01b600052601160045260246000fd5b60006001600160a01b03808816835280871660208401525084604083015260806060830152826080830152828460a0840137600060a0848401015260a0601f19601f8501168301019050969550505050505056fea2646970667358221220ab505b0fa2a68c2e7a7b99fefd55dd57b30afd94e202e9ec829346cdb98433e764736f6c63430008100033000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce00000000000000000000000060167eace2d0a650313c22df7e613043f571e0d30000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c22000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2

Deployed Bytecode

0x60806040526004361061049f5760003560e01c80635c532b461161025e578063a0712d6811610143578063c212a523116100bb578063cd3daf9d1161008a578063d86f1ab01161006f578063d86f1ab014610f29578063e985e9c514610f3f578063ecc389ba14610f7a57600080fd5b8063cd3daf9d14610eef578063d50cb36414610f0457600080fd5b8063c212a52314610e5e578063c744656514610e7e578063c87b56dd14610eb2578063c8f33c9114610ed257600080fd5b8063b2b5334911610112578063b88d4fde116100f7578063b88d4fde14610dda578063c00119ce14610dfa578063c0aa0e8a14610e3e57600080fd5b8063b2b5334914610da4578063b723b34e14610dba57600080fd5b8063a0712d6814610d2e578063a16a642114610d4e578063a22cb46514610d64578063a8aa1b3114610d8457600080fd5b80637c61ab1e116101d65780638da5cb5b116101a557806395d89b411161018a57806395d89b4114610cd05780639fab026314610ce5578063a035b1fe14610d1957600080fd5b80638da5cb5b14610c9a5780639278cd1a14610cba57600080fd5b80637c61ab1e14610c275780637d01d04d14610c475780637dd0804814610c675780638187f51614610c7a57600080fd5b80636352211e1161022d5780636d23d956116102125780636d23d95614610b3857806370a0823114610bd35780637b0a47ee14610bf357600080fd5b80636352211e14610ae457806367d3b48814610b0457600080fd5b80635c532b46146109b45780635d63fcf4146109d45780635f1c17c014610a085780635fcbd28514610ab057600080fd5b806325513e131161038457806342842e0e116102fc5780634cddc728116102cb5780634dada002116102b05780634dada0021461096b578063586b9a7c146109875780635ade228a1461099c57600080fd5b80634cddc7281461092a5780634d49e87d1461095857600080fd5b806342842e0e146108a157806343c94f3e146108c15780634912fc74146108f55780634bad95101461091557600080fd5b80633781826e116103535780633de4e06b116103385780633de4e06b1461081f5780633fc8cef31461085357806341a6ba711461088757600080fd5b80633781826e146107cb5780633848eecf146107eb57600080fd5b806325513e1314610743578063255f5f551461077557806332cb6b0c14610795578063355e0c5d146107ab57600080fd5b806313af40351161041757806319096746116103e65780631daba63b116103cb5780631daba63b146106ee5780631dd19cb41461070e57806323b872dd1461072357600080fd5b806319096746146106b95780631c2655c5146106d957600080fd5b806313af40351461061e578063150b7a021461063e5780631626ba7e1461068357806318160ddd146106a357600080fd5b8063081812fc1161046e578063097114221161045357806309711422146105b357806309cf6091146105d35780630ba84e85146105f157600080fd5b8063081812fc14610543578063095ea7b31461059157600080fd5b806301ffc9a7146104ab57806304c80eaa146104e057806306fdde031461050e57806307b9d49c1461053057600080fd5b366104a657005b600080fd5b3480156104b757600080fd5b506104cb6104c63660046140cc565b610fa2565b60405190151581526020015b60405180910390f35b3480156104ec57600080fd5b506105006104fb3660046140e9565b610fe6565b6040519081526020016104d7565b34801561051a57600080fd5b5061052361107c565b6040516104d79190614152565b61050061053e3660046141b1565b61110a565b34801561054f57600080fd5b5061057961055e3660046140e9565b6011602052600090815260409020546001600160a01b031681565b6040516001600160a01b0390911681526020016104d7565b34801561059d57600080fd5b506105b16105ac36600461422b565b611130565b005b3480156105bf57600080fd5b506105b16105ce366004614257565b611226565b3480156105df57600080fd5b506105006903cfc82e37e9a740000081565b3480156105fd57600080fd5b5061050061060c3660046142a8565b60166020526000908152604090205481565b34801561062a57600080fd5b506105b16106393660046142a8565b61157f565b34801561064a57600080fd5b5061066a6106593660046142c5565b630a85bd0160e11b95945050505050565b6040516001600160e01b031990911681526020016104d7565b34801561068f57600080fd5b5061066a61069e3660046143fd565b611614565b3480156106af57600080fd5b5061050060135481565b3480156106c557600080fd5b506105006106d43660046140e9565b611650565b3480156106e557600080fd5b50610500611a9e565b3480156106fa57600080fd5b506105b161070936600461422b565b611b33565b34801561071a57600080fd5b50610500611c8a565b34801561072f57600080fd5b506105b161073e366004614487565b611e19565b34801561074f57600080fd5b506003546107609063ffffffff1681565b60405163ffffffff90911681526020016104d7565b34801561078157600080fd5b506105006107903660046144dd565b611fef565b3480156107a157600080fd5b5061050061753081565b3480156107b757600080fd5b50601854610579906001600160a01b031681565b3480156107d757600080fd5b506105006107e63660046140e9565b612277565b3480156107f757600080fd5b506105797f0000000000000000000000002600c3a0d5b51698bd951ece63b131ad088a25ca81565b34801561082b57600080fd5b506105797f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c2281565b34801561085f57600080fd5b506105797f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b34801561089357600080fd5b506014546104cb9060ff1681565b3480156108ad57600080fd5b506105b16108bc366004614487565b612298565b3480156108cd57600080fd5b506105007f000000000000000000000000000000000000000000000000000000006c8657f081565b34801561090157600080fd5b506105006109103660046140e9565b61236e565b34801561092157600080fd5b50610500612718565b34801561093657600080fd5b5061094a6109453660046144fb565b61277b565b6040516104d79291906146a4565b610500610966366004614257565b612afa565b34801561097757600080fd5b5061050067016345785d8a000081565b34801561099357600080fd5b506105b1612dee565b3480156109a857600080fd5b506105006304a2860081565b3480156109c057600080fd5b506105b16109cf3660046142a8565b612e46565b3480156109e057600080fd5b506105797f00000000000000000000000060167eace2d0a650313c22df7e613043f571e0d381565b348015610a1457600080fd5b50610aa3610a233660046140e9565b604080516080810182526000808252602082018190529181018290526060810191909152506000908152600b60209081526040918290208251608081018452815481526001909101546001600160801b03811692820192909252600160801b820463ffffffff1692810192909252600160a01b900460ff16606082015290565b6040516104d791906146bd565b348015610abc57600080fd5b506105797f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce81565b348015610af057600080fd5b50610579610aff3660046140e9565b612eb1565b348015610b1057600080fd5b506105007f0000000000000000000000000000000000000000000000000000000067c2dc7081565b348015610b4457600080fd5b50610aa3610b533660046140e9565b604080516080810182526000808252602082018190529181018290526060810191909152506000908152600460209081526040918290208251608081018452815481526001909101546001600160801b03811692820192909252600160801b820463ffffffff1692810192909252600160a01b900460ff16606082015290565b348015610bdf57600080fd5b50610500610bee3660046142a8565b612f1b565b348015610bff57600080fd5b506105007f0000000000000000000000000000000000000000000000000000d287fb79cd0981565b348015610c3357600080fd5b506105b1610c4236600461484d565b612f8f565b348015610c5357600080fd5b50610500610c623660046140e9565b6131a9565b610500610c753660046141b1565b613228565b348015610c8657600080fd5b506105b1610c953660046142a8565b613243565b348015610ca657600080fd5b50600654610579906001600160a01b031681565b348015610cc657600080fd5b5061050060025481565b348015610cdc57600080fd5b50610523613315565b348015610cf157600080fd5b506105797f000000000000000000000000d2b87d87267e24fb5003fba7805a1b9623d1948781565b348015610d2557600080fd5b50610500613322565b348015610d3a57600080fd5b50610500610d493660046140e9565b613367565b348015610d5a57600080fd5b5061050060095481565b348015610d7057600080fd5b506105b1610d7f366004614a36565b61337d565b348015610d9057600080fd5b50601754610579906001600160a01b031681565b348015610db057600080fd5b50610500600c5481565b348015610dc657600080fd5b50610500610dd5366004614a6f565b6133e9565b348015610de657600080fd5b506105b1610df53660046142c5565b6133f6565b348015610e0657600080fd5b50600a54610e26906801000000000000000090046001600160801b031681565b6040516001600160801b0390911681526020016104d7565b348015610e4a57600080fd5b50610500610e593660046140e9565b6134eb565b348015610e6a57600080fd5b50610500610e793660046144dd565b6134fb565b348015610e8a57600080fd5b506105007f000000000000000000000000000000000000000000000000000000006320567081565b348015610ebe57600080fd5b50610523610ecd3660046140e9565b613797565b348015610ede57600080fd5b50600a546107609063ffffffff1681565b348015610efb57600080fd5b50610500613822565b348015610f1057600080fd5b50600a5461076090640100000000900463ffffffff1681565b348015610f3557600080fd5b5061050060155481565b348015610f4b57600080fd5b506104cb610f5a366004614a94565b601260209081526000928352604080842090915290825290205460ff1681565b348015610f8657600080fd5b50600354610e269064010000000090046001600160801b031681565b60006001600160e01b031982167f780e9d63000000000000000000000000000000000000000000000000000000001480610fe05750610fe082613928565b92915050565b60008181526004602052604081206001808201548154849291600160a01b900460ff1690811061101857611018614ac2565b600091825260209091200154600183015461103c91906001600160801b0316614aee565b90506ec097ce7bc90715b34b9f100000000082600001546002546110609190614b0d565b61106a9083614aee565b6110749190614b20565b949350505050565b600d805461108990614b42565b80601f01602080910402602001604051908101604052809291908181526020018280546110b590614b42565b80156111025780601f106110d757610100808354040283529160200191611102565b820191906000526020600020905b8154815290600101906020018083116110e557829003601f168201915b505050505081565b60008061111987878787612afa565b905061112581846134fb565b979650505050505050565b6000818152600f60205260409020546001600160a01b03163381148061117957506001600160a01b038116600090815260126020908152604080832033845290915290205460ff165b6111ca5760405162461bcd60e51b815260206004820152600e60248201527f4e4f545f415554484f52495a454400000000000000000000000000000000000060448201526064015b60405180910390fd5b60008281526011602052604080822080546001600160a01b0319166001600160a01b0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b6000611230613322565b90508181111580156112425750828110155b61128e5760405162461bcd60e51b815260206004820152600e60248201527f507269636520736c69707061676500000000000000000000000000000000000060448201526064016111c1565b6000611298612718565b905060006112a4611a9e565b90506000816112b38885614aee565b6112bd9190614b20565b90506112db6112cc8285614b0d565b6112d68985614b0d565b6139c1565b6017546040516378a1085360e11b8152600481018390526001600160a01b039091169063f14210a690602401600060405180830381600087803b15801561132157600080fd5b505af1158015611335573d6000803e3d6000fd5b50506017546040517f13edab810000000000000000000000000000000000000000000000000000000081526001600160a01b0390911692506313edab8191506113869030908c908c90600401614b7c565b600060405180830381600087803b1580156113a057600080fd5b505af11580156113b4573d6000803e3d6000fd5b5050505060007f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce6001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611418573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061143c9190614bde565b905060008361144b8a84614aee565b6114559190614b20565b6040517f9dc29fac000000000000000000000000000000000000000000000000000000008152336004820152602481018290529091507f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce6001600160a01b031690639dc29fac90604401600060405180830381600087803b1580156114d957600080fd5b505af11580156114ed573d6000803e3d6000fd5b5050505060005b898110156115275761151f30338d8d8581811061151357611513614ac2565b90506020020135613ac3565b6001016114f4565b506115323384613ce3565b60408051848152602081018b90529081018290527f462ff1f90b66e3549a190bb471a2276749250543bad2ce9c21f706d882a59dad9060600160405180910390a150505050505050505050565b6006546001600160a01b031633146115c85760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8292fce18fa69edf4db7b94ea2e58241df0ae57f97e0a6c9b29067028bf92d7690600090a350565b6000600c54600214611627576000611649565b7f1626ba7e000000000000000000000000000000000000000000000000000000005b9392505050565b6040516331a9108f60e11b8152600481018290526000907f000000000000000000000000d2b87d87267e24fb5003fba7805a1b9623d194876001600160a01b031690636352211e90602401602060405180830381865afa1580156116b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116dc9190614bf7565b6001600160a01b0316336001600160a01b0316146117285760405162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b60448201526064016111c1565b6000828152600b60209081526040918290208251608081018452815481526001909101546001600160801b03811692820192909252600160801b820463ffffffff1692810192909252600160a01b900460ff166060820181905260078054909190811061179757611797614ac2565b9060005260206000200154816040015163ffffffff166117b79190614c14565b4210156118065760405162461bcd60e51b815260206004820152601060248201527f426f6e64206e6f74206d6174757265640000000000000000000000000000000060448201526064016111c1565b61180e613822565b600955604051630852cd8d60e31b8152600481018490527f000000000000000000000000d2b87d87267e24fb5003fba7805a1b9623d194876001600160a01b0316906342966c6890602401600060405180830381600087803b15801561187357600080fd5b505af1158015611887573d6000803e3d6000fd5b5050600a805463ffffffff19164263ffffffff16179055505060208101516060820151600880546001600160801b0390931692670de0b6b3a76400009260ff169081106118d6576118d6614ac2565b9060005260206000200154826118ec9190614aee565b6118f69190614b20565b600a805460089061191d9084906801000000000000000090046001600160801b0316614c27565b82546001600160801b039182166101009390930a92830291909202199091161790555060405163a9059cbb60e01b8152336004820152602481018290526001600160a01b037f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce169063a9059cbb906044016020604051808303816000875af11580156119ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119d19190614c4e565b506119db846131a9565b6040516340c10f1960e01b8152336004820152602481018290529093507f00000000000000000000000060167eace2d0a650313c22df7e613043f571e0d36001600160a01b0316906340c10f1990604401600060405180830381600087803b158015611a4657600080fd5b505af1158015611a5a573d6000803e3d6000fd5b505050507fe44694c943742657abee88b2aec7c98d7f392a3302dd496e31b5544e537e15e08483604051611a8f929190614c6b565b60405180910390a15050919050565b601754604080517f12b495a800000000000000000000000000000000000000000000000000000000815290516000926001600160a01b0316916312b495a89160048083019260209291908290030181865afa158015611b01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b259190614cb2565b6001600160801b0316905090565b6006546001600160a01b03163314611b7c5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b60145460ff1615611bcf5760405162461bcd60e51b815260206004820152601960248201527f57686974656c69737420686173206265656e20636c6f7365640000000000000060448201526064016111c1565b6001600160a01b0382166000908152601660205260408120546015805491928392611bfb908490614b0d565b925050819055508160156000828254611c149190614c14565b90915550506015546175301015611c6d5760405162461bcd60e51b815260206004820152601a60248201527f4d617820737570706c7920616c7265616479207265616368656400000000000060448201526064016111c1565b506001600160a01b03909116600090815260166020526040902055565b600080600560009054906101000a90046001600160a01b03166001600160a01b031663398482d86040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ce0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d049190614cb2565b6005546001600160801b039190911691506000906001600160a01b0316318210611d2f576000611d47565b600554611d479083906001600160a01b031631614b0d565b6005546040516378a1085360e11b8152600481018390529192506001600160a01b03169063f14210a690602401600060405180830381600087803b158015611d8e57600080fd5b505af1158015611da2573d6000803e3d6000fd5b50505050600081118015611dc8575060035464010000000090046001600160801b031615155b15610fe05760035464010000000090046001600160801b0316611df382670de0b6b3a7640000614aee565b611dfd9190614b20565b60026000828254611e0e9190614c14565b909155505092915050565b6000818152600f60205260409020546001600160a01b03848116911614611e6f5760405162461bcd60e51b815260206004820152600a60248201526957524f4e475f46524f4d60b01b60448201526064016111c1565b6001600160a01b038216611eb95760405162461bcd60e51b81526020600482015260116024820152701253959053125117d49150d25412515395607a1b60448201526064016111c1565b336001600160a01b0384161480611ef357506001600160a01b038316600090815260126020908152604080832033845290915290205460ff165b80611f1457506000818152601160205260409020546001600160a01b031633145b611f605760405162461bcd60e51b815260206004820152600e60248201527f4e4f545f415554484f52495a454400000000000000000000000000000000000060448201526064016111c1565b6001600160a01b038084166000818152601060209081526040808320805460001901905593861680835284832080546001019055858352600f825284832080546001600160a01b03199081168317909155601190925284832080549092169091559251849392917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b6000611ff9611c8a565b50600380546001919060009061201690849063ffffffff16614ccf565b82546101009290920a63ffffffff818102199093169183160217909155600354811660008181526004602052604090206002548155600181810180546001600160801b038a166001600160a01b031990911617600160801b42909616959095029490941760ff60a01b1916600160a01b60ff8916021790935582549194509250670de0b6b3a76400009190859081106120b1576120b1614ac2565b9060005260206000200154856001600160801b03166120d09190614aee565b6120da9190614b20565b600380546004906120fd90849064010000000090046001600160801b0316614cec565b82546101009290920a6001600160801b038181021990931691831602179091556040516323b872dd60e01b815233600482015230602482015290861660448201527f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce6001600160a01b031691506323b872dd906064016020604051808303816000875af1158015612192573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b69190614c4e565b506040516340c10f1960e01b8152336004820152602481018390527f0000000000000000000000002600c3a0d5b51698bd951ece63b131ad088a25ca6001600160a01b0316906340c10f1990604401600060405180830381600087803b15801561221f57600080fd5b505af1158015612233573d6000803e3d6000fd5b505050507fbcfb553f47b13ce6eaa94a5a3d32329da2677aaaeb218179b18f23aca1db4c998282604051612268929190614d0c565b60405180910390a15092915050565b6008818154811061228757600080fd5b600091825260209091200154905081565b600c546002036122a757505050565b7f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c226001600160a01b0316836001600160a01b03161480156122e9575061753081115b801561231d5750336001600160a01b037f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c2216145b1561235e5761235861233182600019614b0d565b837f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c22613d3e565b50505050565b612369838383613e64565b505050565b6040516331a9108f60e11b8152600481018290526000907f0000000000000000000000002600c3a0d5b51698bd951ece63b131ad088a25ca6001600160a01b031690636352211e90602401602060405180830381865afa1580156123d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123fa9190614bf7565b6001600160a01b0316336001600160a01b0316146124465760405162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b60448201526064016111c1565b60008281526004602090815260408083208151608081018352815481526001909101546001600160801b03811693820193909352600160801b830463ffffffff1691810191909152600160a01b90910460ff1660608201819052825491929181106124b3576124b3614ac2565b9060005260206000200154816040015163ffffffff166124d39190614c14565b4210156125225760405162461bcd60e51b815260206004820152601060248201527f426f6e64206e6f74206d6174757265640000000000000000000000000000000060448201526064016111c1565b61252a611c8a565b50604051630852cd8d60e31b8152600481018490527f0000000000000000000000002600c3a0d5b51698bd951ece63b131ad088a25ca6001600160a01b0316906342966c6890602401600060405180830381600087803b15801561258d57600080fd5b505af11580156125a1573d6000803e3d6000fd5b50505050600081602001516001600160801b03169050670de0b6b3a76400006001836060015160ff16815481106125da576125da614ac2565b9060005260206000200154826125f09190614aee565b6125fa9190614b20565b6003805460049061261d90849064010000000090046001600160801b0316614c27565b82546001600160801b039182166101009390930a92830291909202199091161790555060405163a9059cbb60e01b8152336004820152602481018290526001600160a01b037f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce169063a9059cbb906044016020604051808303816000875af11580156126ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126d19190614c4e565b506126db84610fe6565b92506126e73384613ce3565b7f68fdf814c7f7091db14b00c71885abc4f242a48abe180938ae773cf9c71eeac48483604051611a8f929190614c6b565b601754604080517f398482d800000000000000000000000000000000000000000000000000000000815290516000926001600160a01b03169163398482d89160048083019260209291908290030181865afa158015611b01573d6000803e3d6000fd5b60006127fe604051806101a0016040528060006001600160a01b0316815260200160001515815260200160001515815260200160006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160008152602001606081526020016060815260200160608152602001606081525090565b6000841161284e5760405162461bcd60e51b815260206004820152601f60248201527f4d75737420636f6e76657274206174206c65617374206f6e652061737365740060448201526064016111c1565b603284111561289f5760405162461bcd60e51b815260206004820152601e60248201527f4d75737420636f6e76657274203530206f72206c65737320617373657473000060448201526064016111c1565b30815260016020820152600060408201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031660608201526128f18467016345785d8a0000614aee565b6080820152612920427f000000000000000000000000000000000000000000000000000000006c8657f0614b0d565b60c0820152612930426001614c14565b60e0820152610100810183905260408051600180825281830190925290816020015b6040805180820190915260008082526020820152815260200190600190039081612952575050610180820152604080518082019091523081526020810161299b86600019614b0d565b8152508161018001516000815181106129b6576129b6614ac2565b60209081029190910101526001600160a01b037f00000000000000000000000060167eace2d0a650313c22df7e613043f571e0d316639dc29fac33612a0387670de0b6b3a7640000614aee565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401600060405180830381600087803b158015612a4957600080fd5b505af1158015612a5d573d6000803e3d6000fd5b50505050612a6a81613ece565b6040516323b872dd60e01b8152306004820152336024820152604481018290529092507f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c226001600160a01b0316906323b872dd90606401600060405180830381600087803b158015612adb57600080fd5b505af1158015612aef573d6000803e3d6000fd5b505050509250929050565b600080612b05612718565b90506000612b11611a9e565b905060008083118015612b245750600082115b612b2f576000612b39565b612b398284614b20565b9050848111158015612b4b5750858110155b612b975760405162461bcd60e51b815260206004820152600e60248201527f507269636520736c69707061676500000000000000000000000000000000000060448201526064016111c1565b655af3107a40003411612bec5760405162461bcd60e51b815260206004820152601f60248201527f4d7573742073656e64206174206c6561737420302e303030312065746865720060448201526064016111c1565b612c03612bf93485614c14565b6112d68985614c14565b60007f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce6001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c879190614bde565b90508015612cc657612cc184612c9d3484614aee565b612ca79190614b20565b84612cb28b85614aee565b612cbc9190614b20565b613f98565b612cd0565b612cd08834614aee565b6040516340c10f1960e01b8152336004820152602481018290529095507f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce6001600160a01b0316906340c10f1990604401600060405180830381600087803b158015612d3b57600080fd5b505af1158015612d4f573d6000803e3d6000fd5b5050505060005b88811015612d8a57601754612d829033906001600160a01b03168c8c8581811061151357611513614ac2565b600101612d56565b50601754612da1906001600160a01b031634613ce3565b60408051348152602081018a90529081018690527ff75993dbe1645872cbbea6395e1feebee76b435baf0e4d62d7eac269c6f57b249060600160405180910390a150505050949350505050565b6006546001600160a01b03163314612e375760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b6014805460ff19166001179055565b6006546001600160a01b03163314612e8f5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b601880546001600160a01b0319166001600160a01b0392909216919091179055565b6000818152600f60205260409020546001600160a01b031680612f165760405162461bcd60e51b815260206004820152600a60248201527f4e4f545f4d494e5445440000000000000000000000000000000000000000000060448201526064016111c1565b919050565b60006001600160a01b038216612f735760405162461bcd60e51b815260206004820152600c60248201527f5a45524f5f41444452455353000000000000000000000000000000000000000060448201526064016111c1565b506001600160a01b031660009081526010602052604090205490565b6006546001600160a01b03163314612fd85760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b60005b825181101561308e577f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c226001600160a01b0316631913cfd784838151811061302557613025614ac2565b60200260200101516040518263ffffffff1660e01b81526004016130499190614d50565b600060405180830381600087803b15801561306357600080fd5b505af1158015613077573d6000803e3d6000fd5b50505050808061308690614d63565b915050612fdb565b506040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b03169063a9059cbb90839083906370a0823190602401602060405180830381865afa158015613116573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061313a9190614bde565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044016020604051808303816000875af1158015613185573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123699190614c4e565b6000818152600b602052604081206001810154600880548492600160a01b900460ff169081106131db576131db614ac2565b60009182526020909120015460018301546131ff91906001600160801b0316614aee565b90506ec097ce7bc90715b34b9f1000000000826000015461321e613822565b6110609190614b0d565b60008061323787878787612afa565b90506111258184611fef565b6006546001600160a01b0316331461328c5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064016111c1565b6017546001600160a01b0316156132e55760405162461bcd60e51b815260206004820152601060248201527f5061697220616c7265616479207365740000000000000000000000000000000060448201526064016111c1565b601780546001600160a01b03929092166001600160a01b0319928316811790915560058054909216179055565b50565b600e805461108990614b42565b60008061332d612718565b90506000613339611a9e565b905060008211801561334b5750600081115b613356576000613360565b6133608183614b20565b9250505090565b600061337382336133e9565b5050601354919050565b3360008181526012602090815260408083206001600160a01b03871680855290835292819020805460ff191686151590811790915590519081529192917f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a35050565b6000611649838333613d3e565b613401858585611e19565b6001600160a01b0384163b15806134985750604051630a85bd0160e11b808252906001600160a01b0386169063150b7a02906134499033908a90899089908990600401614d7c565b6020604051808303816000875af1158015613468573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061348c9190614dd0565b6001600160e01b031916145b6134e45760405162461bcd60e51b815260206004820152601060248201527f554e534146455f524543495049454e540000000000000000000000000000000060448201526064016111c1565b5050505050565b6007818154811061228757600080fd5b6000613505613822565b600955600a80546001919060049061352c908490640100000000900463ffffffff16614ccf565b82546101009290920a63ffffffff818102199093169183160217909155600a8054640100000000900482166000818152600b6020526040902060095481556001810180546001600160801b038a166001600160a01b031990911617600160801b429096169586021760ff60a01b1916600160a01b60ff8a1602179055825463ffffffff191690931790915560088054919450919250670de0b6b3a76400009190859081106135dc576135dc614ac2565b9060005260206000200154856001600160801b03166135fb9190614aee565b6136059190614b20565b600a805460089061362c9084906801000000000000000090046001600160801b0316614cec565b82546101009290920a6001600160801b038181021990931691831602179091556040516323b872dd60e01b815233600482015230602482015290861660448201527f000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce6001600160a01b031691506323b872dd906064016020604051808303816000875af11580156136c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136e59190614c4e565b506040516340c10f1960e01b8152336004820152602481018390527f000000000000000000000000d2b87d87267e24fb5003fba7805a1b9623d194876001600160a01b0316906340c10f1990604401600060405180830381600087803b15801561374e57600080fd5b505af1158015613762573d6000803e3d6000fd5b505050507fe92e7a07bbbf0885cfe2769d6491097062ce995593b84a32f347b92eb74ac1c78282604051612268929190614d0c565b6018546040517fc87b56dd000000000000000000000000000000000000000000000000000000008152600481018390526060916001600160a01b03169063c87b56dd90602401600060405180830381865afa1580156137fa573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610fe09190810190614ded565b600a546000906801000000000000000090046001600160801b0316810361384a575060095490565b600a546000906138809063ffffffff167f0000000000000000000000000000000000000000000000000000000067c2dc70613f98565b6138aa427f0000000000000000000000000000000000000000000000000000000067c2dc70613f98565b6138b49190614b0d565b600a549091506801000000000000000090046001600160801b03166138f97f0000000000000000000000000000000000000000000000000000d287fb79cd0983614aee565b61390b90670de0b6b3a7640000614aee565b6139159190614b20565b6009546139229190614c14565b91505090565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000006001600160e01b03198316148061398b57507f80ac58cd000000000000000000000000000000000000000000000000000000006001600160e01b03198316145b80610fe05750506001600160e01b0319167f5b5e139f000000000000000000000000000000000000000000000000000000001490565b6017546040517fd8a1890c0000000000000000000000000000000000000000000000000000000081526001600160801b03841660048201526001600160a01b039091169063d8a1890c90602401600060405180830381600087803b158015613a2857600080fd5b505af1158015613a3c573d6000803e3d6000fd5b50506017546040517f6809f6640000000000000000000000000000000000000000000000000000000081526001600160801b03851660048201526001600160a01b039091169250636809f6649150602401600060405180830381600087803b158015613aa757600080fd5b505af1158015613abb573d6000803e3d6000fd5b505050505050565b6000818152600f60205260409020546001600160a01b03848116911614613b195760405162461bcd60e51b815260206004820152600a60248201526957524f4e475f46524f4d60b01b60448201526064016111c1565b6001600160a01b038216613b635760405162461bcd60e51b81526020600482015260116024820152701253959053125117d49150d25412515395607a1b60448201526064016111c1565b6001600160a01b038084166000818152601060209081526040808320805460001901905593861680835284832080546001019055858352600f825284832080546001600160a01b03199081168317909155601190925284832080549092169091559251849392917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a46001600160a01b0382163b1580613c975750604051630a85bd0160e11b8082523360048301526001600160a01b03858116602484015260448301849052608060648401526000608484015290919084169063150b7a029060a4015b6020604051808303816000875af1158015613c67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c8b9190614dd0565b6001600160e01b031916145b6123695760405162461bcd60e51b815260206004820152601060248201527f554e534146455f524543495049454e540000000000000000000000000000000060448201526064016111c1565b600080600080600085875af19050806123695760405162461bcd60e51b815260206004820152601360248201527f4554485f5452414e534645525f4641494c45440000000000000000000000000060448201526064016111c1565b6001600160a01b038116600090815260166020526040812054841115613da65760405162461bcd60e51b815260206004820152601f60248201527f4e6f742077686974656c697374656420666f72207468697320616d6f756e740060448201526064016111c1565b6013545b84601354613db89190614c14565b811015613de557613dd384613dce836001614c14565b613fae565b80613ddd81614d63565b915050613daa565b506001600160a01b03831660009081526010602052604081208054869290613e0e908490614c14565b925050819055508360136000828254613e279190614c14565b90915550506001600160a01b03821660009081526016602052604081208054869290613e54908490614b0d565b9091555050601354949350505050565b613e6f838383611e19565b6001600160a01b0382163b1580613c975750604051630a85bd0160e11b8082523360048301526001600160a01b03858116602484015260448301849052608060648401526000608484015290919084169063150b7a029060a401613c48565b6002600c5560408051600080825260208201928390527f68840dd40000000000000000000000000000000000000000000000000000000090925260606001600160a01b037f0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c22166368840dd4613f4886848660248101614e64565b6020604051808303816000875af1158015613f67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f8b9190614bde565b6001600c55949350505050565b6000818310613fa75781611649565b5090919050565b6001600160a01b038216613ff85760405162461bcd60e51b81526020600482015260116024820152701253959053125117d49150d25412515395607a1b60448201526064016111c1565b6000818152600f60205260409020546001600160a01b03161561405d5760405162461bcd60e51b815260206004820152600e60248201527f414c52454144595f4d494e54454400000000000000000000000000000000000060448201526064016111c1565b6000818152600f602052604080822080546001600160a01b0319166001600160a01b03861690811790915590518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b6001600160e01b03198116811461331257600080fd5b6000602082840312156140de57600080fd5b8135611649816140b6565b6000602082840312156140fb57600080fd5b5035919050565b60005b8381101561411d578181015183820152602001614105565b50506000910152565b6000815180845261413e816020860160208601614102565b601f01601f19169290920160200192915050565b6020815260006116496020830184614126565b60008083601f84011261417757600080fd5b50813567ffffffffffffffff81111561418f57600080fd5b6020830191508360208260051b85010111156141aa57600080fd5b9250929050565b6000806000806000608086880312156141c957600080fd5b853567ffffffffffffffff8111156141e057600080fd5b6141ec88828901614165565b9099909850602088013597604081013597506060013595509350505050565b6001600160a01b038116811461331257600080fd5b8035612f168161420b565b6000806040838503121561423e57600080fd5b82356142498161420b565b946020939093013593505050565b6000806000806060858703121561426d57600080fd5b843567ffffffffffffffff81111561428457600080fd5b61429087828801614165565b90989097506020870135966040013595509350505050565b6000602082840312156142ba57600080fd5b81356116498161420b565b6000806000806000608086880312156142dd57600080fd5b85356142e88161420b565b945060208601356142f88161420b565b935060408601359250606086013567ffffffffffffffff8082111561431c57600080fd5b818801915088601f83011261433057600080fd5b81358181111561433f57600080fd5b89602082850101111561435157600080fd5b9699959850939650602001949392505050565b634e487b7160e01b600052604160045260246000fd5b6040516101a0810167ffffffffffffffff8111828210171561439e5761439e614364565b60405290565b604051601f8201601f1916810167ffffffffffffffff811182821017156143cd576143cd614364565b604052919050565b600067ffffffffffffffff8211156143ef576143ef614364565b50601f01601f191660200190565b6000806040838503121561441057600080fd5b82359150602083013567ffffffffffffffff81111561442e57600080fd5b8301601f8101851361443f57600080fd5b803561445261444d826143d5565b6143a4565b81815286602083850101111561446757600080fd5b816020840160208301376000602083830101528093505050509250929050565b60008060006060848603121561449c57600080fd5b83356144a78161420b565b925060208401356144b78161420b565b929592945050506040919091013590565b6001600160801b038116811461331257600080fd5b600080604083850312156144f057600080fd5b8235614249816144c8565b6000806040838503121561450e57600080fd5b50508035926020909101359150565b600081518084526020808501945080840160005b838110156145565781516001600160a01b031687529582019590820190600101614531565b509495945050505050565b600081518084526020808501945080840160005b8381101561455657815180516001600160a01b031688528301518388015260409096019590820190600101614575565b80516001600160a01b0316825260006101a060208301516145ca602086018215159052565b5060408301516145de604086018215159052565b5060608301516145f960608601826001600160a01b03169052565b506080830151608085015260a083015160a085015260c083015160c085015260e083015160e08501526101008084015181860152506101208084015182828701526146468387018261451d565b925050506101408084015185830382870152614662838261451d565b92505050610160808401518583038287015261467e8382614561565b92505050610180808401518583038287015261469a8382614561565b9695505050505050565b82815260406020820152600061107460408301846145a5565b815181526020808301516001600160801b03169082015260408083015163ffffffff169082015260608083015160ff169082015260808101610fe0565b600067ffffffffffffffff82111561471457614714614364565b5060051b60200190565b801515811461331257600080fd5b8035612f168161471e565b600082601f83011261474857600080fd5b8135602061475861444d836146fa565b82815260059290921b8401810191818101908684111561477757600080fd5b8286015b8481101561479b57803561478e8161420b565b835291830191830161477b565b509695505050505050565b600082601f8301126147b757600080fd5b813560206147c761444d836146fa565b82815260069290921b840181019181810190868411156147e657600080fd5b8286015b8481101561479b57604080828a0312156148045760008081fd5b805181810181811067ffffffffffffffff8211171561482557614825614364565b9091528135906148348261420b565b90815281850135858201528352918301916040016147ea565b6000806040838503121561486057600080fd5b823567ffffffffffffffff8082111561487857600080fd5b818501915085601f83011261488c57600080fd5b8135602061489c61444d836146fa565b82815260059290921b840181019181810190898411156148bb57600080fd5b8286015b84811015614a19578035868111156148d657600080fd5b87016101a0818d03601f190112156148ed57600080fd5b6148f561437a565b614900868301614220565b815261490e6040830161472c565b8682015261491e6060830161472c565b604082015261492f60808301614220565b606082015260a0820135608082015260c082013560a082015260e082013560c082015261010082013560e08201526101208201356101008201526101408201358881111561497c57600080fd5b61498a8e8883860101614737565b61012083015250610160820135888111156149a457600080fd5b6149b28e8883860101614737565b6101408301525061018080830135898111156149cd57600080fd5b6149db8f89838701016147a6565b610160840152506101a0830135898111156149f557600080fd5b614a038f89838701016147a6565b91830191909152508452509183019183016148bf565b509650614a299050878201614220565b9450505050509250929050565b60008060408385031215614a4957600080fd5b8235614a548161420b565b91506020830135614a648161471e565b809150509250929050565b60008060408385031215614a8257600080fd5b823591506020830135614a648161420b565b60008060408385031215614aa757600080fd5b8235614ab28161420b565b91506020830135614a648161420b565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615614b0857614b08614ad8565b500290565b81810381811115610fe057610fe0614ad8565b600082614b3d57634e487b7160e01b600052601260045260246000fd5b500490565b600181811c90821680614b5657607f821691505b602082108103614b7657634e487b7160e01b600052602260045260246000fd5b50919050565b6001600160a01b03841681526040602082015281604082015260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115614bc457600080fd5b8260051b8085606085013791909101606001949350505050565b600060208284031215614bf057600080fd5b5051919050565b600060208284031215614c0957600080fd5b81516116498161420b565b80820180821115610fe057610fe0614ad8565b6001600160801b03828116828216039080821115614c4757614c47614ad8565b5092915050565b600060208284031215614c6057600080fd5b81516116498161471e565b82815260a081016116496020830184805182526001600160801b03602082015116602083015263ffffffff604082015116604083015260ff60608201511660608301525050565b600060208284031215614cc457600080fd5b8151611649816144c8565b63ffffffff818116838216019080821115614c4757614c47614ad8565b6001600160801b03818116838216019080821115614c4757614c47614ad8565b82815260a08101611649602083018480548252600101546001600160801b0381166020830152608081901c63ffffffff16604083015260a01c60ff16606090910152565b60208152600061164960208301846145a5565b600060018201614d7557614d75614ad8565b5060010190565b60006001600160a01b03808816835280871660208401525084604083015260806060830152826080830152828460a0840137600060a0848401015260a0601f19601f85011683010190509695505050505050565b600060208284031215614de257600080fd5b8151611649816140b6565b600060208284031215614dff57600080fd5b815167ffffffffffffffff811115614e1657600080fd5b8201601f81018413614e2757600080fd5b8051614e3561444d826143d5565b818152856020838501011115614e4a57600080fd5b614e5b826020830160208601614102565b95945050505050565b606081526000614e7760608301866145a5565b602083820381850152614e8a8287614126565b8481036040860152855180825282870193509082019060005b81811015614ebf57845183529383019391830191600101614ea3565b50909897505050505050505056fea26469706673582212201b04b511c5626fcd22953ba534ee7e24a01bb31b8c714bae08eb7eacd16df90b64736f6c63430008100033

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

000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce00000000000000000000000060167eace2d0a650313c22df7e613043f571e0d30000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c22000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2

-----Decoded View---------------
Arg [0] : _lpToken (address): 0xA775B9Cd6335C028693e7b0b3b6f76fC90aea8Ce
Arg [1] : _callOptionToken (address): 0x60167eAcE2D0A650313C22dF7E613043F571e0d3
Arg [2] : _putty (address): 0x8Ad3668B088Bf7abEE6488Da8F6570e8c3586c22
Arg [3] : _weth (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2

-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 000000000000000000000000a775b9cd6335c028693e7b0b3b6f76fc90aea8ce
Arg [1] : 00000000000000000000000060167eace2d0a650313c22df7e613043f571e0d3
Arg [2] : 0000000000000000000000008ad3668b088bf7abee6488da8f6570e8c3586c22
Arg [3] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2


Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.