S Price: $0.157924 (-9.96%)

Contract

0x45B35E5BA5f5a337Fc170D47E1Ce2A45954cb110

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
SonicOrderBook

Compiler Version
v0.8.30+commit.73712a01

Optimization Enabled:
Yes with 175 runs

Other Settings:
cancun EvmVersion
File 1 of 36 : SonicOrderBook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import {ReentrancyGuardTransientUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardTransientUpgradeable.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";
import {IWrappedSonic} from "./interfaces/IWrappedSonic.sol";
import {ISonicAirdropNFT} from "./interfaces/ISonicAirdropNFT.sol";
import {Season, SeasonData, TokenIdInfo, MakerOrderInfo, OrderSide} from "./shared/global.sol";

import {BokkyPooBahsRedBlackTreeLibrary} from "./libraries/BokkyPooBahsRedBlackTreeLibrary.sol";
import {SegmentLibrary} from "./libraries/SegmentLibrary.sol";
import {SlotLibrary} from "./libraries/SlotLibrary.sol";
import {SonicOrderBookLibrary} from "./libraries/SonicOrderBookLibrary.sol";

import {QUANTITY_TICK, FEE_SCALING_FACTOR, NUM_SLOTS_PER_SEGMENT, MAX_ORDER_ID, MAX_CLAIMABLE_ORDERS} from "./shared/constants.sol";

/// @title SonicOrderBook
/// @author Sam Witch (Paintswap, Estfor Kingdom) & 0xDoubleSharp
/// @notice This efficient ERC1155 order book is an upgradeable UUPS proxy contract. It has functions for bulk placing
///         limit orders, cancelling limit orders, and claiming NFTs and tokens from filled or partially filled orders.
///         It suppports dev fees on successful trades. Each order book is for a specific quote pair
contract SonicOrderBook is UUPSUpgradeable, OwnableUpgradeable, ERC1155Holder, ReentrancyGuardTransientUpgradeable {
  using BokkyPooBahsRedBlackTreeLibrary for BokkyPooBahsRedBlackTreeLibrary.Tree;
  using SafeERC20 for IERC20Metadata;
  using SegmentLibrary for bytes32;
  using SlotLibrary for bytes10;

  event NewOrder(address indexed makerOrTaker, uint48 orderId);
  event AddedToBook(
    address indexed maker,
    OrderSide indexed side,
    uint48 orderId,
    uint256 indexed tokenId,
    uint256 price,
    uint256 quantity,
    uint256 originalQuantity,
    uint16 devFeeBps
  );
  event OrdersMatched(
    address indexed taker,
    uint48 indexed takerOrderId,
    uint48[] orderIds,
    uint256 indexed tokenId,
    uint256[] prices,
    uint256[] quantities
  );
  event OrdersCancelled(
    address indexed maker,
    uint48[] orderIds,
    uint256[] tokenIds,
    uint256[] prices,
    uint256[] quantities
  );
  event FailedToAddToBook(
    address indexed maker,
    OrderSide indexed side,
    uint48 orderId,
    uint256 indexed tokenId,
    uint256 price,
    uint256 quantity
  );
  event ClaimedTokens(address indexed maker, uint48[] orderIds, uint256 amount);
  event ClaimedNFTs(address indexed maker, uint48[] orderIds, uint256[] tokenIds, uint256[] amounts);
  event SetTokenIdInfos(uint256[] tokenIds, TokenIdInfo[] tokenInfos);
  event SetMaxOrdersPerPriceLevel(uint256 maxOrdersPerPrice);
  event SetFees(address devAddr, uint256 devFeeMakerBps, uint256 devFeeTakerBps);
  event SetQuantityTickSize(uint256 quantityTick);

  error ZeroAddress();
  error DevFeeNotSet();
  error DevFeeTooHigh();
  error BaseDecimalDivisorMustMatch();
  error NotERC1155();
  error NoQuantity();
  error OrderNotFound(uint256 orderId);
  error PriceNotMultipleOfTick(uint256 priceTick);
  error PriceTickCannotBeChanged();
  error PriceTickCannotBeZero();
  error PriceZero();
  error LengthMismatch();
  error NotMaker();
  error TooManyOrdersHit();
  error MaxOrdersNotMultipleOfOrdersInSegment();
  error FailedToTakeExactQuantityFromBook();
  error TotalCostConditionNotMet();
  error NotTradeable();
  error SeasonLocked();
  error InvalidQuantity();
  error InvalidMinQuantity();
  error TokenIdZeroIsReserved();
  error TokenIdTooHigh();
  error ValueMustBeZeroForNonS();
  error PriceTickTooHigh();
  error PostOnly();
  error InsufficientQuantityFulfilled();
  error InsufficientQuoteReceived();
  error SellMustUseExactQuantity();
  error MakerPriceMustMatch(uint256 expectedPrice, uint256 actualPrice);
  error OnlyThisContract();

  // Errors related to price segment invariants being broken
  error PriceSegmentHasAHole();
  error IncorrectDiffBetweenLastSegmentAndTombstoneOffset();
  error IncorrectDiffBetweenLastSegmentAndTheNewTombstoneOffset();
  error LastPriceSegmentCannotBeEmpty();
  error OnlyTheTombstoneSegmentCanStartWithEmptySlots();

  struct LimitOrder {
    OrderSide side;
    uint256 tokenId;
    uint64 price;
    uint88 quantity;
    bool onlyPost;
    bool onlyExactPriceIfMaker;
  }

  struct MarketOrder {
    OrderSide side;
    uint256 tokenId;
    uint88 quantity;
    uint256 totalCost;
    bool useExactQuantity;
  }

  struct TakeFromOrderBookParams {
    // the following fields should only be initialised once
    address sender;
    OrderSide side;
    uint256 tokenId;
    uint64 limitPrice;
    uint48 orderId;
    uint88 quantity;
    uint256 maxCost;
    bool isBudgetConstrainedBuying;
    uint16 devFeeTakerBps;
    // the following fields would change in memory
    uint64 bestPrice;
    uint256 quantityFulfilled;
    uint256 currentCost;
    uint256 fee;
    uint256 numberOfOrdersTraded;
    bool stopConsumingMoreOrders;
  }

  // A helper type for a view function to return orders. Packing doesn't matter
  struct Order {
    address maker;
    uint88 quantity;
    uint48 id;
  }

  uint16 private constant MAX_ORDERS_HIT = 2_000;

  ISonicAirdropNFT private immutable _nft;
  IERC20Metadata private immutable _quoteToken;
  IWrappedSonic private immutable _wS;
  bool private immutable _isQuoteTokenSonic;
  uint256 private immutable BASE_DECIMAL_DIVISOR;

  // First storage slot
  address private _devAddr;
  uint16 private _devFeeMakerBps;
  uint16 private _devFeeTakerBps;
  uint16 private _maxOrdersPerPrice;
  uint48 private _nextOrderId;

  // mappings
  mapping(uint256 tokenId => TokenIdInfo tokenIdInfo) private _tokenIdInfos;
  mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) private _asks;
  mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) private _bids;
  // token id => price => ask(normalized quantity (uint32), id (uint48)) x 3
  mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) private _asksAtPrice;
  // token id => price => bid(normalized quantity (uint32), id (uint48)) x 3
  mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) private _bidsAtPrice;
  MakerOrderInfo[MAX_ORDER_ID] private _orders;

  modifier onlyThisContract() {
    require(_msgSender() == address(this), OnlyThisContract());
    _;
  }

  /// @notice Initialize the implementation contract with immutable variables as part of the proxy contract deployment
  /// @param nft Address of the fnft
  /// @param quoteToken The quote token address (wrapped sonic or stablecoin most likely)
  /// @param wS The wrapped sonic address
  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor(ISonicAirdropNFT nft, IERC20Metadata quoteToken, IWrappedSonic wS) {
    _disableInitializers();
    _nft = nft;
    _quoteToken = quoteToken;
    _wS = wS;
    _isQuoteTokenSonic = address(quoteToken) == address(wS);

    // nft must be an ERC1155 via ERC165
    require(nft.supportsInterface(type(IERC1155).interfaceId), NotERC1155());
    // Check that the base decimal divisor matches the one in the library
    BASE_DECIMAL_DIVISOR = 10 ** nft.decimals();
    require(BASE_DECIMAL_DIVISOR == SonicOrderBookLibrary.BASE_DECIMAL_DIVISOR, BaseDecimalDivisorMustMatch());
  }

  /// @notice Initialize the contract as part of the proxy contract deployment
  function initialize() external initializer {
    __Ownable_init(_msgSender());
    __UUPSUpgradeable_init();
    __ReentrancyGuardTransient_init();

    _nextOrderId = 1;

    emit SetQuantityTickSize(QUANTITY_TICK);
  }

  /// @notice Place market order
  /// @param order market order to be placed
  /// @param returnWrappedS Whether to return wrapped sonic or not (if the quote is wrapped sonic)
  function placeMarketOrder(MarketOrder calldata order, bool returnWrappedS) external payable nonReentrant {
    // Must fufill the order and be below the total cost (or above depending on the side)
    uint256 quoteTokensToUs;
    uint256 quoteTokensFromUs;
    address sender = _msgSender();

    uint48[] memory orderIdsPool = new uint48[](MAX_ORDERS_HIT);
    uint256[] memory quantitiesPool = new uint256[](MAX_ORDERS_HIT);
    uint256[] memory pricesPool = new uint256[](MAX_ORDERS_HIT);

    (uint256 cost, uint256 fee, uint256 quantityFulfilled, bool isBudgetConstrainedBuying) = _placeMarketOrder(
      sender,
      order,
      orderIdsPool,
      quantitiesPool,
      pricesPool
    );

    if (order.side == OrderSide.Buy) {
      require(cost <= order.totalCost, TotalCostConditionNotMet());

      // For budget-constrained buy market orders (non-exact buy orders), we enforce
      // that the full requested quantity must be fulfillable within the specified budget.
      // This means `quantityFulfilled` must equal `order.quantity` for these orders.
      // The check below ensures budget-constrained orders follow an "all-or-nothing"
      // approach - either the complete quantity is obtained within budget, or the order fails.
      // This differs from the behavior of exact orders, where the quantity check is
      // performed elsewhere in the flow.

      if (isBudgetConstrainedBuying) {
        // For budget-constrained buy market orders, we require that the full requested
        // quantity is fulfilled. Even though these orders have a budget constraint,
        // this check ensures that if the order was processed, it met the minimum
        // quantity requirement. Budget-constrained orders that cannot fulfill the
        // full quantity due to budget limitations should fail here.
        require(quantityFulfilled >= order.quantity, InsufficientQuantityFulfilled());
      }

      quoteTokensFromUs = 0;
      quoteTokensToUs = cost;

      uint256 nftAmountToTransfer = quantityFulfilled - fee;

      this.resolveQuoteTokens(sender, 0, quoteTokensToUs, quoteTokensFromUs, msg.value, returnWrappedS);
      _safeTransferNFTsFromUs(sender, order.tokenId, nftAmountToTransfer);
      _safeTransferNFTsFromUs(_devAddr, order.tokenId, fee);
    } else {
      require(cost >= order.totalCost, InsufficientQuoteReceived());
      // Transfer tokens to the seller if any have sold
      quoteTokensFromUs = cost - fee;
      quoteTokensToUs = 0;
      // Selling, transfer all NFTs to us
      _safeTransferNFTsToUs(sender, order.tokenId, quantityFulfilled);
      this.resolveQuoteTokens(sender, fee, quoteTokensToUs, quoteTokensFromUs, msg.value, returnWrappedS);
    }
  }

  /// @notice Place multiple limit orders in the order book
  /// @param orders Array of limit orders to be placed
  /// @param returnWrappedS Whether to return wrapped sonic or not (if the quote is wrapped sonic)
  function placeLimitOrders(LimitOrder[] calldata orders, bool returnWrappedS) external payable nonReentrant {
    address sender = _msgSender();

    (uint256 quoteFees, uint256 quoteTokensToUs, uint256 quoteTokensFromUs) = _placeLimitOrders(sender, orders);
    this.resolveQuoteTokens(sender, quoteFees, quoteTokensToUs, quoteTokensFromUs, msg.value, returnWrappedS);
  }

  /// @notice Cancel multiple orders in the order book
  /// @param orderIds Array of order IDs to be cancelled
  /// @param returnWrappedS Whether to return wrapped sonic or not (if the quote is wrapped sonic)
  function cancelOrders(uint48[] calldata orderIds, bool returnWrappedS) external nonReentrant {
    address sender = _msgSender();
    (uint256 quoteTokensFromUs, uint256[] memory nftIdsFromUs, uint256[] memory nftAmountsFromUs) = _cancelOrders(
      sender,
      orderIds
    );

    if (nftIdsFromUs.length != 0) {
      _safeBatchTransferNFTsFromUs(sender, nftIdsFromUs, nftAmountsFromUs);
    }

    // Transfer tokens if there are any to send
    if (quoteTokensFromUs != 0) {
      _safeTransferCoinsFromUs(sender, quoteTokensFromUs, returnWrappedS);
    }
  }

  /// @notice Cancel multiple orders and place multiple limit orders in the order book. Can be used to replace orders.
  ///         NFTs are returned after cancelling while quote tokens are only returned at the end.
  /// @param orderIds Array of order IDs to be cancelled
  /// @param newOrders Array of limit orders to be placed
  /// @param returnWrappedS Whether to return wrapped sonic or not (if the quote is wrapped sonic)
  function cancelAndPlaceLimitOrders(
    uint48[] calldata orderIds,
    LimitOrder[] calldata newOrders,
    bool returnWrappedS
  ) external payable nonReentrant {
    address sender = _msgSender();

    (
      uint256 quoteTokensFromCancelling,
      uint256[] memory nftIdsFromUs,
      uint256[] memory nftAmountsFromUs
    ) = _cancelOrders(sender, orderIds);

    if (nftIdsFromUs.length != 0) {
      _safeBatchTransferNFTsFromUs(sender, nftIdsFromUs, nftAmountsFromUs);
    }

    (uint256 fees, uint256 quoteTokensToUs, uint256 quoteTokensFromUs) = _placeLimitOrders(sender, newOrders);

    if (quoteTokensToUs > quoteTokensFromCancelling) {
      quoteTokensToUs -= quoteTokensFromCancelling;
    } else {
      quoteTokensFromUs += quoteTokensFromCancelling - quoteTokensToUs;
      quoteTokensToUs = 0;
    }

    this.resolveQuoteTokens(sender, fees, quoteTokensToUs, quoteTokensFromUs, msg.value, returnWrappedS);
  }

  /// @notice Claim tokens associated with filled or partially filled orders.
  ///         Must be the maker of these orders.
  /// @param orderIds Array of order IDs from which to claim tokens
  /// @param returnWrappedS Whether to return wrapped sonic or not (if the quote is wrapped sonic)
  function claimTokens(uint48[] calldata orderIds, bool returnWrappedS) external nonReentrant {
    SonicOrderBookLibrary.claimTokens(
      _msgSender(),
      orderIds,
      _orders,
      _asksAtPrice,
      _asks,
      _getSonicOrderBookLibraryClaimableInterface(),
      returnWrappedS
    );
  }

  /// @notice Claim NFTs associated with filled or partially filled orders
  ///         Must be the maker of these orders.
  /// @param orderIds Array of order IDs from which to claim NFTs
  function claimNFTs(uint48[] calldata orderIds) external nonReentrant {
    SonicOrderBookLibrary.claimNFTs(
      _msgSender(),
      orderIds,
      _orders,
      _bidsAtPrice,
      _bids,
      _getSonicOrderBookLibraryClaimableInterface()
    );
  }

  function _transferNFTFees(uint256[5] memory nftFeeInSeasons) private {
    for (uint256 i = 0; i < nftFeeInSeasons.length; ++i) {
      uint256 fee = nftFeeInSeasons[i];
      if (fee == 0) {
        continue;
      }
      uint256 tokenId = i + 1; // Seasons are 1-indexed
      _safeTransferNFTsFromUs(_devAddr, tokenId, fee);
    }
  }

  /// @notice Convenience function to claim both tokens and nfts in filled or partially filled orders.
  ///         Must be the maker of these orders.
  /// @param quoteTokenOrderIds Array of order IDs from which to claim tokens
  /// @param nftOrderIds Array of order IDs from which to claim NFTs
  /// @param returnWrappedS Whether to return wrapped sonic or not (if the quote is wrapped sonic)
  function claimAll(
    uint48[] calldata quoteTokenOrderIds,
    uint48[] calldata nftOrderIds,
    bool returnWrappedS
  ) external nonReentrant {
    SonicOrderBookLibrary.claimAll(
      _msgSender(),
      quoteTokenOrderIds,
      nftOrderIds,
      _orders,
      _asksAtPrice,
      _bidsAtPrice,
      _asks,
      _bids,
      _getSonicOrderBookLibraryClaimableInterface(),
      returnWrappedS
    );
  }

  /// @notice Get the amount of tokens claimable for these orders
  /// @param orderIds The order IDs of which to find the claimable tokens for
  /// @return amount The amount of tokens claimable for these orders
  function tokensClaimable(uint48[] calldata orderIds) external view returns (uint256 amount) {
    return SonicOrderBookLibrary.tokensClaimable(orderIds, _orders, _asksAtPrice, _asks);
  }

  /// @notice Get the amount of NFTs claimable for these orders
  /// @param orderIds The order IDs to get the claimable NFTs for
  /// @return amounts The amounts of NFTs claimable for each order ID
  function nftsClaimable(uint48[] calldata orderIds) external view returns (uint256[] memory amounts) {
    return SonicOrderBookLibrary.nftsClaimable(orderIds, _orders, _bidsAtPrice, _bids);
  }

  /// @notice Get the token ID info for a specific token ID
  /// @param tokenId The token ID to get the info for
  /// @return tokenIdInfo The token ID info struct containing the price tick and min quantity
  function getTokenIdInfo(uint256 tokenId) external view returns (TokenIdInfo memory tokenIdInfo) {
    return _tokenIdInfos[tokenId];
  }

  /// @notice Get the highest bid for a specific token ID
  /// @param tokenId The token ID to get the highest bid for
  /// @return highestBid The highest bid for the specified token ID
  function getHighestBid(uint256 tokenId) public view returns (uint64 highestBid) {
    return _bids[tokenId].last();
  }

  /// @notice Get the lowest ask for a specific token ID
  /// @param tokenId The token ID to get the lowest ask for
  /// @return lowestAsk The lowest ask for the specified token ID
  function getLowestAsk(uint256 tokenId) public view returns (uint64 lowestAsk) {
    return _asks[tokenId].first();
  }

  /// @notice Get the order book entry for a specific order ID
  /// @param side The side of the order book to get the node from
  /// @param tokenId The token ID to get the node for
  /// @param price The price level to get the node for
  /// @return node The order book entry for the specified order ID
  function getNode(
    OrderSide side,
    uint256 tokenId,
    uint64 price
  ) external view returns (BokkyPooBahsRedBlackTreeLibrary.Node memory node) {
    if (side == OrderSide.Buy) {
      return _bids[tokenId].getNode(price);
    } else {
      return _asks[tokenId].getNode(price);
    }
  }

  /// @notice Get all orders at a specific price level
  /// @param side The side of the order book to get orders from
  /// @param tokenId The token ID to get orders for
  /// @param price The price level to get orders for
  /// @return orders The array of orders at the specified price level
  function allOrdersAtPrice(
    OrderSide side,
    uint256 tokenId,
    uint64 price
  ) external view returns (Order[] memory orders) {
    if (side == OrderSide.Buy) {
      return _allOrdersAtPriceSide(_bidsAtPrice[tokenId][price], _bids[tokenId], price);
    } else {
      return _allOrdersAtPriceSide(_asksAtPrice[tokenId][price], _asks[tokenId], price);
    }
  }

  /// @notice Get the order by ID
  /// @param orderId The order ID to get the order for
  /// @return order The order struct containing the maker info
  function getMakerOrder(uint48 orderId) external view returns (MakerOrderInfo memory order) {
    return _orders[orderId];
  }

  /// @notice Place multiple limit orders in the order book
  /// @param orders Array of limit orders to be placed
  /// @return quoteFees The quote fees incurred from taking orders
  /// @return quoteTokensToUs The amount of quote tokens to be sent to us
  /// @return quoteTokensFromUs The amount of quote tokens to be sent from us
  function _placeLimitOrders(
    address sender,
    LimitOrder[] calldata orders
  ) private returns (uint256 quoteFees, uint256 quoteTokensToUs, uint256 quoteTokensFromUs) {
    uint256 nftLengthToUs;
    uint256[] memory nftIdsToUs = new uint256[](orders.length);
    uint256[] memory nftAmountsToUs = new uint256[](orders.length);
    uint256 nftLengthFromUs;
    uint256[] memory nftIdsFromUs = new uint256[](orders.length);
    uint256[] memory nftAmountsFromUs = new uint256[](orders.length);

    // Reuse this array in all the orders
    uint48[] memory orderIdsPool = new uint48[](MAX_ORDERS_HIT);
    uint256[] memory quantitiesPool = new uint256[](MAX_ORDERS_HIT);
    uint256[] memory pricesPool = new uint256[](MAX_ORDERS_HIT);

    // read the next order ID so we can increment in memory
    uint48 currentOrderId = _nextOrderId;

    // Assumes up to 5 seasons
    uint256[5] memory nftFeeInSeasons;

    // Allocate a memory region to be used when taking from orderbook.
    // This memory region will be reused in each iteration, preventing
    // unnecessary memory expansions.
    // Note make sure to reset and repopulate the other fields in each iteration
    TakeFromOrderBookParams memory params;
    params.sender = sender;
    params.maxCost = type(uint256).max;
    params.isBudgetConstrainedBuying = false;
    params.devFeeTakerBps = _devFeeTakerBps;

    for (uint256 i = 0; i < orders.length; ++i) {
      LimitOrder calldata order = orders[i];
      uint128 priceTick = _tokenIdInfos[order.tokenId].priceTick;
      (
        uint256 quantityAddedToBook,
        uint256 failedQuantity,
        uint256 cost,
        uint64 price,
        uint256 takerFee
      ) = _placeLimitOrder(params, currentOrderId, order, orderIdsPool, quantitiesPool, pricesPool, priceTick);
      ++currentOrderId;

      if (order.side == OrderSide.Buy) {
        unchecked {
          quoteTokensToUs += cost + (uint256(price) * quantityAddedToBook) / BASE_DECIMAL_DIVISOR;
        }

        if (cost != 0) {
          // Transfer the NFTs taken from the order book straight to the taker
          uint256 nftAmountToTaker = order.quantity - quantityAddedToBook - failedQuantity - takerFee;
          nftIdsFromUs[nftLengthFromUs] = order.tokenId;
          nftAmountsFromUs[nftLengthFromUs++] = nftAmountToTaker;

          nftFeeInSeasons[order.tokenId - 1] += takerFee;
        }
      } else {
        // Selling, transfer all NFTs to us
        if (order.quantity != failedQuantity) {
          nftIdsToUs[nftLengthToUs] = order.tokenId;
          nftAmountsToUs[nftLengthToUs++] = order.quantity - failedQuantity;
        }

        // Transfer tokens to the seller if any have sold
        quoteTokensFromUs += cost - takerFee;
        quoteFees += takerFee;
      }
    }

    // update the state if any orders were added to the book
    _nextOrderId = currentOrderId;

    if (nftLengthToUs != 0) {
      assembly ("memory-safe") {
        mstore(nftIdsToUs, nftLengthToUs)
        mstore(nftAmountsToUs, nftLengthToUs)
      }
      _safeBatchTransferNFTsToUs(sender, nftIdsToUs, nftAmountsToUs);
    }

    if (nftLengthFromUs != 0) {
      assembly ("memory-safe") {
        mstore(nftIdsFromUs, nftLengthFromUs)
        mstore(nftAmountsFromUs, nftLengthFromUs)
      }
      _safeBatchTransferNFTsFromUs(sender, nftIdsFromUs, nftAmountsFromUs);
    }

    _transferNFTFees(nftFeeInSeasons);
  }

  function _cancelOrders(
    address sender,
    uint48[] calldata orderIds
  ) private returns (uint256 quoteTokensFromUs, uint256[] memory nftIdsFromUs, uint256[] memory nftAmountsFromUs) {
    uint256 nftsFromUs = 0;
    uint256 numberOfOrders = orderIds.length;
    nftIdsFromUs = new uint256[](numberOfOrders);
    nftAmountsFromUs = new uint256[](numberOfOrders);
    uint256[] memory prices = new uint256[](numberOfOrders);
    uint256[] memory tokenIds = new uint256[](numberOfOrders);
    uint256[] memory quantities = new uint256[](numberOfOrders);
    for (uint256 i = 0; i < numberOfOrders; ++i) {
      MakerOrderInfo storage orderInfo = _orders[orderIds[i]];
      (OrderSide side, uint256 tokenId, uint64 price) = (orderInfo.side, orderInfo.tokenId, uint64(orderInfo.price));
      uint256 quantity = 0;
      if (side == OrderSide.Buy) {
        quantity = _cancelOrdersSide(orderIds[i], price, _bidsAtPrice[tokenId][price], _bids[tokenId]);
        // Send the remaining token back to them
        quoteTokensFromUs += (quantity * price) / BASE_DECIMAL_DIVISOR;
      } else {
        quantity = _cancelOrdersSide(orderIds[i], price, _asksAtPrice[tokenId][price], _asks[tokenId]);
        // Send the remaining NFTs back to them
        nftIdsFromUs[nftsFromUs] = tokenId;
        nftAmountsFromUs[nftsFromUs] = quantity;
        ++nftsFromUs;
      }
      prices[i] = price;
      quantities[i] = quantity;
      tokenIds[i] = tokenId;
    }

    // shrink the size
    assembly ("memory-safe") {
      mstore(nftIdsFromUs, nftsFromUs)
      mstore(nftAmountsFromUs, nftsFromUs)
    }

    emit OrdersCancelled(sender, orderIds, tokenIds, prices, quantities);
  }

  function _shouldTakeMoreFromOrderBook(TakeFromOrderBookParams memory params) internal pure returns (bool) {
    if (params.stopConsumingMoreOrders) {
      return false;
    }

    if (params.isBudgetConstrainedBuying) {
      return params.currentCost < params.maxCost;
    } else {
      return params.quantityFulfilled < params.quantity;
    }
  }

  function _tryUpdateBestPriceAndContinue(TakeFromOrderBookParams memory params) internal view returns (bool) {
    bool senderIsSelling = params.side == OrderSide.Sell;
    uint64 bestPrice = senderIsSelling ? getHighestBid(params.tokenId) : getLowestAsk(params.tokenId);

    if (bestPrice == 0) {
      return false;
    }

    if (senderIsSelling) {
      if (bestPrice < params.limitPrice) {
        return false;
      }
    } else {
      // sender is buying
      if (bestPrice > params.limitPrice) {
        return false;
      }
    }

    // at this point we know that
    // 1. bestPrice != 0
    // 2. bestPrice satisfy the bound set by the limitPrice

    params.bestPrice = bestPrice;
    return true;
  }

  function _takeFromOrderBookSide(
    TakeFromOrderBookParams memory params,
    uint48[] memory orderIdsPool,
    uint256[] memory quantitiesPool,
    uint256[] memory pricesPool,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage segmentsAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage tree
  ) private {
    // reset the size
    assembly ("memory-safe") {
      mstore(orderIdsPool, MAX_ORDERS_HIT)
      mstore(quantitiesPool, MAX_ORDERS_HIT)
      mstore(pricesPool, MAX_ORDERS_HIT)
    }

    while (_shouldTakeMoreFromOrderBook(params) && _tryUpdateBestPriceAndContinue(params)) {
      _consumePriceSegments(
        params,
        tree[params.tokenId],
        segmentsAtPrice[params.tokenId][params.bestPrice],
        orderIdsPool,
        quantitiesPool,
        pricesPool
      );
    }

    uint256 numberOfOrdersTraded = params.numberOfOrdersTraded;
    if (numberOfOrdersTraded != 0) {
      assembly ("memory-safe") {
        mstore(orderIdsPool, numberOfOrdersTraded)
        mstore(quantitiesPool, numberOfOrdersTraded)
        mstore(pricesPool, numberOfOrdersTraded)
      }

      emit OrdersMatched(params.sender, params.orderId, orderIdsPool, params.tokenId, pricesPool, quantitiesPool);
    }
  }

  function _consumePriceSegments(
    TakeFromOrderBookParams memory params,
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    bytes32[] storage segments,
    uint48[] memory orderIdsPool,
    uint256[] memory quantitiesPool,
    uint256[] memory pricesPool
  ) private {
    // when bestPrice (!=0) was picked it should be guaranteed that the node exists.
    BokkyPooBahsRedBlackTreeLibrary.Node storage node = tree.getNodeUnsafe(params.bestPrice);

    uint256 numOrdersFullyConsumed = 0;
    bytes32 segment;
    uint256 lastConsumedSegmentIndex;
    uint16 devFeeTakerBps = params.devFeeTakerBps;

    uint256 segmentsLength = segments.length;
    uint256 tombstoneSegmentOffset = node.tombstoneSegmentOffset;

    for (uint256 i = tombstoneSegmentOffset; i < segmentsLength && _shouldTakeMoreFromOrderBook(params); ++i) {
      lastConsumedSegmentIndex = i;
      segment = segments[i];

      for (
        uint256 slotIndex = 0;
        slotIndex < NUM_SLOTS_PER_SEGMENT && _shouldTakeMoreFromOrderBook(params);
        ++slotIndex
      ) {
        require(params.numberOfOrdersTraded < MAX_ORDERS_HIT, TooManyOrdersHit());
        bytes32 remainingSegment = segment.getRemainingSegment(slotIndex);
        if (remainingSegment == 0) {
          // Should only hit this branch on the last segment
          if (i < segmentsLength - 1) {
            // This branch which should not be reachable
            revert PriceSegmentHasAHole();
          } else {
            // we are processing the last price segment in this branch
            // the possibilities are (o: an empty slot, s: slotIndex):
            // o    o    o(s) - BAD
            // o    o(s) ...  - skip incrementing `numOrdersFullyConsumed`
            // o(s) ...  ...  - skip incrementing `numOrdersFullyConsumed`
            if (slotIndex == 0) {
              // This branch which should not be reachable
              // the last segment in the active area of the price segment
              // only has empty slots
              // o    o    o(s) - BAD
              revert LastPriceSegmentCannotBeEmpty();
            }
          }

          break;
        }

        bytes10 slot = segment.getSlot(slotIndex);
        uint48 orderId = slot.getOrderId();
        if (orderId == 0) {
          // we should only hit this branch at the very beginning of the
          // active area of the price segment pointed to by the `tombstoneSegmentOffset`
          // Possible configurations of this segment should be of the form:
          // (o: an empty slot, x: a non empty slot, s: slotIndex, ot = tombstoneSegmentOffset)
          // x o    o(s)  <-- (i === ot) - allowed
          // x o(s) o     <-- (i === ot) - allowed
          // x x    o(s)  <-- (i === ot) - allowed
          // o x    o(s)  <-- (i === ot) - allowed
          //
          // x o    o(s)  <-- (i =/= ot) - BAD
          // x o(s) o     <-- (i =/= ot) - BAD
          // x x    o(s)  <-- (i =/= ot) - BAD
          // x o(s) x     <-- (i  >= ot) - BAD

          if (i == tombstoneSegmentOffset) {
            // o x    o(s)  <-- (i === ot) - allowed
            // x o    o(s)  <-- (i === ot) - allowed
            // x o(s) o     <-- (i === ot) - allowed
            // x x    o(s)  <-- (i === ot) - allowed
            //
            // @dev we are allowing this potentially unreachable state below to pass through
            //      and just increment `numOrdersFullyConsumed`
            // x o(s) x     <-- (i  == ot) - BAD

            // Skip this order in the segment as it's been deleted
            require(segment.compressedStatus() != 2, PriceSegmentHasAHole());
            ++numOrdersFullyConsumed;
            continue;
          } else {
            // this branch should be unreachable if all invariants are satisfied
            // x o    o(s)  <-- (i =/= ot) - BAD
            // x o(s) o     <-- (i =/= ot) - BAD
            // x x    o(s)  <-- (i =/= ot) - BAD
            // x o(s) x     <-- (i =/= ot) - BAD

            revert OnlyTheTombstoneSegmentCanStartWithEmptySlots();
          }
        }

        uint256 ordersConsumed = 0;
        uint256 quantityNFTClaimable = 0;

        (segment, ordersConsumed, quantityNFTClaimable) = _parseOrder(params, segment, slotIndex, devFeeTakerBps);

        numOrdersFullyConsumed += ordersConsumed;

        orderIdsPool[params.numberOfOrdersTraded] = orderId;
        quantitiesPool[params.numberOfOrdersTraded] = quantityNFTClaimable;
        pricesPool[params.numberOfOrdersTraded++] = params.bestPrice;
      }
    }

    _updateSegmentsAndTree(
      tree,
      node,
      segments,
      params.bestPrice,
      segment,
      lastConsumedSegmentIndex,
      numOrdersFullyConsumed
    );
  }

  function _parseOrder(
    TakeFromOrderBookParams memory params,
    bytes32 segment,
    uint256 slotIndex,
    uint256 devFeeTakerBps
  ) private view returns (bytes32 newSegment, uint256 ordersConsumed, uint256 quantityNFTClaimable) {
    bytes10 slot = segment.getSlot(slotIndex);
    uint256 quantityL3 = slot.getQuantity();

    if (params.isBudgetConstrainedBuying) {
      // Check budget constraint before consuming order
      uint256 fullOrderCost = (quantityL3 * params.bestPrice) / BASE_DECIMAL_DIVISOR;
      uint256 remainingBudget = params.maxCost - params.currentCost;

      if (fullOrderCost > remainingBudget) {
        // // Can't afford a full order, stop here as the slot will be potentially partially touched.
        params.stopConsumingMoreOrders = true;
        // Check if we can afford partial order
        uint256 maxAffordableQuantity = (remainingBudget * BASE_DECIMAL_DIVISOR) / params.bestPrice;
        // Floor to QUANTITY_TICK to ensure proper alignment
        maxAffordableQuantity = (maxAffordableQuantity / QUANTITY_TICK) * QUANTITY_TICK;
        if (maxAffordableQuantity == 0) {
          return (
            segment,
            0, // ordersConsumed
            0 // quantityNFTClaimable
          );
        }

        quantityNFTClaimable = maxAffordableQuantity;

        // Update the slot with remaining quantity
        slot = slot.setQuantity(uint88(quantityL3 - quantityNFTClaimable));
        segment = segment.setSlot(slotIndex, slot);
      } else {
        // the remaining budget can afford consuming the whole order
        quantityNFTClaimable = quantityL3;
        ordersConsumed = 1;
      }

      // at this point we shold have
      // params.currentCost + (quantityNFTClaimable * params.bestPrice) / BASE_DECIMAL_DIVISOR
      // <= params.maxCost
      //
      // So in general during the whole iteration of matching orders we should have:
      // params.currentCost <= params.maxCost
    } else {
      // non-budget constrained order. Need to make sure we don't
      // fill/match more than params.quantity
      uint256 quantityRemaining = params.quantity - params.quantityFulfilled;

      if (quantityRemaining >= quantityL3) {
        quantityNFTClaimable = quantityL3;
        ordersConsumed = 1;
      } else {
        // Eat into the order
        slot = slot.setQuantity(uint88(quantityL3 - quantityRemaining));
        segment = segment.setSlot(slotIndex, slot);
        quantityNFTClaimable = quantityRemaining;
        params.stopConsumingMoreOrders = true;
      }

      // at this point one should be able to prove that:
      // params.quantityFulfilled + quantityNFTClaimable <= params.quantity
      // so for non-budget constrained orders we should always have:
      // params.quantityFulfilled <= params.quantity
      //
      // Only non-exact buy market orders can be budget constrained.
    }

    {
      // update quantityFulfilled, currentCost and fee
      params.quantityFulfilled += quantityNFTClaimable;
      uint256 tradeCost = (quantityNFTClaimable * params.bestPrice) / BASE_DECIMAL_DIVISOR;
      params.currentCost += tradeCost;

      if (params.side == OrderSide.Sell) {
        params.fee += _calcFee(tradeCost, devFeeTakerBps);
      } else {
        params.fee += _calcFee(quantityNFTClaimable, devFeeTakerBps);
      }
    }

    newSegment = segment;
  }

  function _updateSegmentsAndTree(
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    BokkyPooBahsRedBlackTreeLibrary.Node storage bestPriceNode,
    bytes32[] storage segments,
    uint64 bestPrice,
    bytes32 lastSegment,
    uint256 lastSegmentIndex,
    uint256 numOrdersFullyConsumed
  ) private {
    // `segments.length > lastSegmentIndex >= oldTombstoneOffset`
    // `numOrdersFullyConsumed` should be the number of order slots fully consumed
    // yet not modified but the cursor passed over it to the next order slot.

    // Assumptions:
    //    1. `numSegmentsFullyConsumed` is calculated correctly, it should be the number of
    //       slots fully consumed or skipped if the slot was EMPTY (0)
    //    2. `lastSegmentIndex` points to the last segment consumed
    //    3. `lastSegment` is the segment pointed to by `lastSegmentIndex`

    // [CHECK LIST] One should enforce the following for `lastSegment` (the last segment consumed):
    // (o: an EMPTY slot, x: a non-EMPTY slot)
    //
    // o o o - last consumed segment - ALLOWED (only if the price node gets removed from the tree)
    // o o x - last consumed segment - ALLOWED (check `ot` & `seg.len - 1` point to this slot too)
    // o x o - last consumed segment - ALLOWED (check `ot` & `seg.len - 1` point to this slot too)
    // o x x - last consumed segment - ALLOWED (check `seg.len - 1` point to this slot too)
    // x o o - last consumed segment - ALLOWED (check `ot` point to this slot too)
    // x o x - last consumed segment - CATCH - no hole in the middle allowed
    // x x o - last consumed segment - ALLOWED (check `ot` point to this slot too)
    // x x x - last consumed segment - ALLOWED

    uint256 numSegmentsFullyConsumed = numOrdersFullyConsumed / NUM_SLOTS_PER_SEGMENT;
    uint256 oldTombstoneOffset = bestPriceNode.tombstoneSegmentOffset;
    uint256 newTombstoneSegmentOffset = oldTombstoneOffset + numSegmentsFullyConsumed;

    uint256 numOrdersWithinLastSegmentFullyConsumed = numOrdersFullyConsumed % NUM_SLOTS_PER_SEGMENT;
    if (lastSegmentIndex == newTombstoneSegmentOffset) {
      // At this branch we know `segments.length > lastSegmentIndex >= newTombstoneSegmentOffset`
      lastSegment = lastSegment.clearUpToSlot(numOrdersWithinLastSegmentFullyConsumed);

      if (uint256(lastSegment) == 0) {
        // `lastSegment` has this property/assumption that either:
        // A1. An other was partially matched in this segment or
        // A2. We had reached the last segment in the active area of the price segments which
        //     has some zero slots (`if (remainingSegment == 0)` branch in `_consumePriceSegments`)
        //
        // Moreover, there is an assumption here that if `lastSegment` that was touched during the
        // matching/filling process ends up being `0` then that would mean, there are no orders
        // left in the price segments since A1 would not be possible and so for A2:
        // 1. any order slot before this segment should have been fully filled/matched and thus
        //    should have been zeroed out in the previous `if (numSegmentsFullyConsumed != 0)`
        //    block.
        // 2. There could not be any non-zero order slot past this segment since otherwise,
        //    that would indicate there would have been holes in the price segments previously
        //    breaking (Inv 1.)
        newTombstoneSegmentOffset = lastSegmentIndex + 1;
        // so we would have:
        // `segments.length >= newTombstoneSegmentOffset == lastSegmentIndex + 1`
        // `newTombstoneSegmentOffset == lastSegmentIndex + 1 > oldTombstoneOffset`
        // thus below `lastSegment` shuold get deleted

        // o o o - last consumed segment - ALLOWED - it will get deleted and the new tombstone offset
        //                                           points to the following segment

        // The checks from the [CHECK LIST] are not required since if one hits this branch and continue
        // without reverting, the last segment consumed would be removed from the price segments
        // and the new tombstone offset would point to the following segment.
      } else {
        // At this branch we know `segments.length > lastSegmentIndex >= newTombstoneSegmentOffset`
        // and `lastSegment` is non-zero, so at the end `bestPrice` would not get removed from the `tree`

        // s2 s1 s0 : cs(bits) : lastSegment <-- (lastSegmentIndex == newTombstoneSegmentOffset)
        // --------------------------------(si: the `i`th slot, cs: compressed status)-------
        //  o  o  o :      111 : last consumed segment - ALLOWED (only if the price node gets removed from the tree)
        //  o  o  x :      110 : last consumed segment - ALLOWED (check `ot` & `seg.len - 1` point to this slot too)
        //  o  x  o :      101 : last consumed segment - ALLOWED (check `ot` & `seg.len - 1` point to this slot too)
        //  o  x  x :      100 : last consumed segment - ALLOWED (check `seg.len - 1` point to this slot too)
        //  x  o  o :      011 : last consumed segment - ALLOWED (check `ot` point to this slot too)
        //  x  o  x :      010 : last consumed segment - CATCH - no hole in the middle allowed
        //  x  x  o :      001 : last consumed segment - ALLOWED (check `ot` point to this slot too)
        //  x  x  x :      000 : last consumed segment - ALLOWED

        uint256 compressedStatus = lastSegment.compressedStatus();

        //  o  o  o : 111 : one would not enter this branch for this case

        //  x  o  x : 010 : last consumed segment - CATCH - no hole in the middle allowed
        require(compressedStatus != 2, PriceSegmentHasAHole());

        if (compressedStatus > 3) {
          //  o  x  x : 100 : last consumed segment - ALLOWED (check `seg.len - 1` point to this slot too)
          //  o  x  o : 101 : last consumed segment - ALLOWED (check `ot` & `seg.len - 1` point to this slot too)
          //  o  o  x : 110 : last consumed segment - ALLOWED (check `ot` & `seg.len - 1` point to this slot too)
          require(lastSegmentIndex == segments.length - 1, PriceSegmentHasAHole());
        }

        segments[lastSegmentIndex] = lastSegment;
      }
    } else {
      // if `lastSegmentIndex =/= newTombstoneSegmentOffset` that would mean the matching process had ended up
      // with ( - dashes the slot can be 0 or not, c means that it was consumed):
      // ...
      // x(c) -(c) -(c) : lastSegmentIndex
      // where in the last segment, the last slot was fully filled and thus we would end up with:
      // ...
      // x(c) -(c) -(c) : lastSegmentIndex
      //   -  -    -    : newTombstoneSegmentOffset
      // So these values can only be off by `1`
      require(
        (lastSegmentIndex + 1 == newTombstoneSegmentOffset) && (numOrdersWithinLastSegmentFullyConsumed == 0),
        IncorrectDiffBetweenLastSegmentAndTheNewTombstoneOffset()
      );

      // The checks from the [CHECK LIST] are not required since if one hits this branch and continue
      // without reverting, the last segment consumed would be removed from the price segments
      // and the new tombstone offset would point to the following segment.
    }

    // Cleanup segments to get a gas refund
    for (uint256 i = oldTombstoneOffset; i < newTombstoneSegmentOffset; ++i) {
      delete segments[i];
    }

    if (newTombstoneSegmentOffset != oldTombstoneOffset) {
      tree.edit(bestPrice, uint56(newTombstoneSegmentOffset));
    }

    // below one can add an extra branch for `newTombstoneSegmentOffset > segments.length`
    // and possibly revert since that would mean some invariant was broken.
    if (newTombstoneSegmentOffset >= segments.length) {
      tree.remove(bestPrice);
    }
  }

  function _takeFromOrderBook(
    TakeFromOrderBookParams memory params,
    uint48[] memory orderIdsPool,
    uint256[] memory quantitiesPool,
    uint256[] memory pricesPool
  ) private {
    // Take as much as possible from the order book
    if (params.side == OrderSide.Buy) {
      _takeFromOrderBookSide(params, orderIdsPool, quantitiesPool, pricesPool, _asksAtPrice, _asks);
    } else {
      _takeFromOrderBookSide(params, orderIdsPool, quantitiesPool, pricesPool, _bidsAtPrice, _bids);
    }
  }

  function _allOrdersAtPriceSide(
    bytes32[] storage segments,
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    uint64 price
  ) private view returns (Order[] memory orders) {
    if (!tree.exists(price)) {
      return orders;
    }
    uint256 tombstoneSegmentOffset = tree.getNode(price).tombstoneSegmentOffset;
    orders = new Order[]((segments.length - tombstoneSegmentOffset) * NUM_SLOTS_PER_SEGMENT);
    uint256 numberOfEntries;
    for (uint256 segmentIdx = tombstoneSegmentOffset; segmentIdx < segments.length; ++segmentIdx) {
      bytes32 segment = segments[segmentIdx];
      for (uint256 slotIndex = 0; slotIndex < NUM_SLOTS_PER_SEGMENT; ++slotIndex) {
        bytes10 slot = segment.getSlot(slotIndex);
        uint48 id = slot.getOrderId();
        if (id != 0) {
          uint88 quantity = slot.getQuantity();
          orders[numberOfEntries] = Order(_orders[id].maker, quantity, id);
          ++numberOfEntries;
        }
      }
    }

    assembly ("memory-safe") {
      mstore(orders, numberOfEntries)
    }
  }

  function _cancelOrdersSide(
    uint256 orderId,
    uint64 price,
    bytes32[] storage segments,
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree
  ) private returns (uint88 quantity) {
    BokkyPooBahsRedBlackTreeLibrary.Node storage node = tree.getNode(price);
    uint256 tombstoneSegmentOffset = node.tombstoneSegmentOffset;

    (uint256 segmentIndex, uint256 slotIndex) = _find(segments, tombstoneSegmentOffset, segments.length, orderId);
    require(segmentIndex != type(uint).max, OrderNotFound(orderId));

    bytes32 segment = segments[segmentIndex];
    bytes10 slot = segment.getSlot(slotIndex);
    quantity = slot.getQuantity();

    _cancelOrder(_msgSender(), segments, price, segmentIndex, slotIndex, tombstoneSegmentOffset, tree);
    // Decrease the remaining quantity in the order, let the remaining still be claimed if it was partially filled
    _orders[uint48(orderId)].remainingNormalizedQuantity -= uint32(quantity / QUANTITY_TICK);
  }

  function _placeMarketOrder(
    address sender,
    MarketOrder calldata order,
    uint48[] memory orderIdsPool,
    uint256[] memory quantitiesPool,
    uint256[] memory pricesPool
  ) private returns (uint256 cost, uint256 fee, uint256 quantityFulfilled, bool isBudgetConstrainedBuying) {
    require(order.quantity != 0 || !order.useExactQuantity, NoQuantity()); // Allow 0 quantity when it is a minimum
    require(order.quantity % QUANTITY_TICK == 0, InvalidQuantity());
    require(order.side == OrderSide.Buy || order.useExactQuantity, SellMustUseExactQuantity());

    TokenIdInfo memory tokenIdInfo = _tokenIdInfos[order.tokenId];
    require(tokenIdInfo.isTradeable, NotTradeable());

    uint48 newOrderId = _nextOrderId++;
    emit NewOrder(sender, newOrderId);

    uint64 price = order.side == OrderSide.Buy ? type(uint64).max : 0;

    uint256 maxCost = type(uint256).max;

    if (!order.useExactQuantity && order.side == OrderSide.Buy) {
      // Budget-constrained buying: use totalCost as maximum budget
      maxCost = order.totalCost;
      isBudgetConstrainedBuying = true;
    }

    TakeFromOrderBookParams memory params = TakeFromOrderBookParams({
      sender: sender,
      side: order.side,
      tokenId: order.tokenId,
      limitPrice: price, // should make the price limit check trivial since extreme endpoints are chosen based on the order side
      orderId: newOrderId,
      quantity: order.quantity,
      maxCost: maxCost,
      isBudgetConstrainedBuying: isBudgetConstrainedBuying,
      devFeeTakerBps: _devFeeTakerBps,
      // the following would change in memory
      bestPrice: 0,
      quantityFulfilled: 0,
      currentCost: 0,
      fee: 0,
      numberOfOrdersTraded: 0,
      stopConsumingMoreOrders: false
    });

    _takeFromOrderBook(params, orderIdsPool, quantitiesPool, pricesPool);

    cost = params.currentCost;
    fee = params.fee;
    quantityFulfilled = params.quantityFulfilled;

    if (order.useExactQuantity) {
      // Must fulfill complete order
      require(quantityFulfilled == order.quantity, FailedToTakeExactQuantityFromBook());
    }
  }

  function _placeLimitOrder(
    TakeFromOrderBookParams memory params,
    uint48 newOrderId,
    LimitOrder calldata order,
    uint48[] memory orderIdsPool,
    uint256[] memory quantitiesPool,
    uint256[] memory pricesPool,
    uint128 priceTick
  ) private returns (uint256 quantityAddedToBook, uint256 failedQuantity, uint256 cost, uint64 price, uint256 fee) {
    require(order.quantity != 0, NoQuantity());
    require(order.quantity % QUANTITY_TICK == 0, InvalidQuantity());
    require(order.price != 0, PriceZero());

    require(_tokenIdInfos[order.tokenId].isTradeable, NotTradeable());
    require(order.price % priceTick == 0, PriceNotMultipleOfTick(priceTick));

    emit NewOrder(params.sender, newOrderId);

    {
      // the following fields need to be populated
      params.side = order.side;
      params.tokenId = order.tokenId;
      params.limitPrice = order.price;
      params.orderId = newOrderId;
      params.quantity = order.quantity;

      // the following would change in memory
      params.bestPrice = 0;
      params.quantityFulfilled = 0;
      params.currentCost = 0;
      params.fee = 0;
      params.numberOfOrdersTraded = 0;
      params.stopConsumingMoreOrders = false;
    }

    _takeFromOrderBook(params, orderIdsPool, quantitiesPool, pricesPool);

    cost = params.currentCost;
    fee = params.fee;
    uint256 quantityFulfilled = params.quantityFulfilled;

    if (cost != 0) {
      require(!order.onlyPost, PostOnly());
    }

    uint256 quantityRemaining = order.quantity - quantityFulfilled;

    // Add the rest to the order book if has the minimum required, in order to keep order books healthy
    if (quantityRemaining >= _tokenIdInfos[order.tokenId].minQuantity) {
      quantityAddedToBook = quantityRemaining;
      price = _addToBook(
        params.sender,
        newOrderId,
        priceTick,
        order.side,
        order.tokenId,
        order.price,
        quantityAddedToBook,
        order.quantity
      );
      if (order.onlyExactPriceIfMaker) {
        require(price == order.price, MakerPriceMustMatch(order.price, price));
      }
    } else if (quantityRemaining != 0) {
      price = order.price;
      failedQuantity = quantityRemaining;
      emit FailedToAddToBook(params.sender, order.side, newOrderId, order.tokenId, price, failedQuantity);
    }
  }

  /**
   * @dev Returns the used capacity of a specific price level in the market.
   * The used capacity is determined by the number of segments at that price level,
   * minus the number of tombstones (inactive slots), and then multiplied by the number of slots per segment.
   *
   * @param tree The Red-Black Tree containing the prices and their associated nodes.
   * @param segmentsPriceMap A mapping from each price to its segments, where each segment is an array of bytes32 representing the slots at that price level.
   * @param price The price level for which to retrieve the used capacity.
   *
   * @return uint256 The used capacity of the specified price level in the market.
   */
  function _getPriceLevelUsedCapacity(
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    mapping(uint256 price => bytes32[]) storage segmentsPriceMap,
    uint64 price
  ) internal view returns (uint256) {
    // below already checks whether the price exists in the tree
    uint256 tombstoneSegmentOffset = tree.getNodeUnsafe(price).tombstoneSegmentOffset;
    return (segmentsPriceMap[price].length - tombstoneSegmentOffset) * NUM_SLOTS_PER_SEGMENT;
  }

  function _segmentsHasSpaceForMoreOrders(
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    mapping(uint256 price => bytes32[]) storage segmentsPriceMap,
    uint64 price,
    uint16 maxOrdersPerPrice
  ) private returns (bool) {
    if (!tree.exists(price)) {
      tree.insert(price);
      return true;
    }

    return (_getPriceLevelUsedCapacity(tree, segmentsPriceMap, price) < maxOrdersPerPrice ||
      _getLastSlot(segmentsPriceMap, price) == 0);
  }

  function _nextPrice(
    uint64 price,
    int128 priceTick // - for buy, + for sell
  ) private pure returns (uint64) {
    unchecked {
      return SafeCast.toUint64(uint128(int128(uint128(price)) + priceTick));
    }
  }

  function _addOrderToEndOfSegments(
    bytes32[] storage segments,
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    uint64 price,
    uint48 orderId,
    uint32 normalizedQuantity
  ) private {
    // Read last one. Decide if we can add to the existing segment or if we need to add a new segment
    if (segments.length != 0) {
      uint256 lastSegmentIndex = segments.length - 1;
      BokkyPooBahsRedBlackTreeLibrary.Node storage node = tree.getNode(price);
      if (lastSegmentIndex >= node.tombstoneSegmentOffset) {
        bytes32 lastSegment = segments[lastSegmentIndex];
        // Are there are free slots in this segment
        for (uint256 slotIndex = 0; slotIndex < NUM_SLOTS_PER_SEGMENT; ++slotIndex) {
          bytes32 remainingSegment = lastSegment.getRemainingSegment(slotIndex);
          if (remainingSegment == 0) {
            // catch o o o
            require(slotIndex != 0, LastPriceSegmentCannotBeEmpty());
            // for o x o, must be head
            if (lastSegment.getSlot(0) == 0) {
              require(lastSegmentIndex == node.tombstoneSegmentOffset, PriceSegmentHasAHole());
            }
            // Found free slot, so add this order to an existing segment
            bytes10 slot = SlotLibrary.createSlot(orderId, normalizedQuantity);
            bytes32 newSegment = lastSegment.setSlotUnsafe(slotIndex, slot);
            segments[lastSegmentIndex] = newSegment;
            return;
          }
        }
        // At this point we know `compressedStatus` should be less then `4` and only
        // the following slot configurations would end up here:
        // s2 s1 s0 | compressedStatus |
        //  x  o  o | 3 | allowed only when (ot == seg.len - 1)
        //  x  o  x | 2 | BAD - There is a hole
        //  x  x  o | 1 | allowed only when (ot == seg.len - 1)
        //  x  x  x | 0 | allowed
        uint256 compressedStatus = lastSegment.compressedStatus();
        require(compressedStatus != 2, PriceSegmentHasAHole());

        // At this point we know compressedStatus ∈ {0, 1, 3}
        require((compressedStatus == 0) || (lastSegmentIndex == node.tombstoneSegmentOffset), PriceSegmentHasAHole());
      } else {
        // ot is at most equal to seg.len
        require(
          lastSegmentIndex + 1 == node.tombstoneSegmentOffset,
          IncorrectDiffBetweenLastSegmentAndTombstoneOffset()
        );
      }
    }

    bytes32 segment = SlotLibrary.createSlotAsBytes32(orderId, normalizedQuantity);
    segments.push(segment);
  }

  function _addToBookSide(
    mapping(uint256 price => bytes32[]) storage segmentsPriceMap,
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree,
    uint64 price,
    uint48 orderId,
    uint32 normalizedQuantity,
    int128 priceTick // - for buy, + for sell
  ) private returns (uint64) {
    // Loop until we find a suitable price level to insert the order
    uint16 maxOrdersPerPrice = _maxOrdersPerPrice;
    while (!_segmentsHasSpaceForMoreOrders(tree, segmentsPriceMap, price, maxOrdersPerPrice)) {
      price = _nextPrice(price, priceTick);
    }

    _addOrderToEndOfSegments(segmentsPriceMap[price], tree, price, orderId, normalizedQuantity);

    return price;
  }

  function _addToBook(
    address sender,
    uint48 newOrderId,
    uint128 priceTick,
    OrderSide side,
    uint256 tokenId,
    uint64 price,
    uint256 quantity,
    uint256 originalQuantity
  ) private returns (uint64) {
    // Normalize quantity before storing
    uint32 normalizedQuantity = SafeCast.toUint32(quantity / QUANTITY_TICK);

    // Price can update if the price level is at capacity
    if (side == OrderSide.Buy) {
      price = _addToBookSide(
        _bidsAtPrice[tokenId],
        _bids[tokenId],
        price,
        newOrderId,
        normalizedQuantity,
        -int128(priceTick)
      );
    } else {
      price = _addToBookSide(
        _asksAtPrice[tokenId],
        _asks[tokenId],
        price,
        newOrderId,
        normalizedQuantity,
        int128(priceTick)
      );
    }

    uint16 devFeeBps = _devFeeMakerBps;
    // Store order for querying, claiming and cancellation
    _orders[newOrderId] = MakerOrderInfo({
      maker: sender,
      side: side,
      tokenId: uint8(tokenId),
      remainingNormalizedQuantity: normalizedQuantity,
      originalNormalizedQuantity: normalizedQuantity,
      price: price,
      devFeeBps: devFeeBps
    });

    emit AddedToBook(sender, side, newOrderId, tokenId, price, quantity, originalQuantity, devFeeBps);
    return price;
  }

  function _calcFee(uint256 cost, uint256 devFeeBps) private pure returns (uint256 fee) {
    return SonicOrderBookLibrary._calcFee(cost, devFeeBps);
  }

  function _sendFees(uint256 devFees) private {
    address devAddr = _devAddr;
    if (devAddr != address(0) && devFees != 0) {
      _safeTransferCoinsFromUs(devAddr, devFees, false);
    }
  }

  function _find(
    bytes32[] storage segments,
    uint256 begin,
    uint256 end,
    uint256 value
  ) private view returns (uint256 mid, uint256 slotIndex) {
    return SonicOrderBookLibrary.find(segments, begin, end, value);
  }

  function _getSonicOrderBookLibraryClaimableInterface()
    private
    view
    returns (SonicOrderBookLibrary.ContractInterfaces memory)
  {
    return
      SonicOrderBookLibrary.ContractInterfaces({
        nft: _nft,
        quoteToken: _quoteToken,
        wS: _wS,
        devAddr: _devAddr,
        isQuoteTokenSonic: _isQuoteTokenSonic
      });
  }

  function _cancelOrder(
    address sender,
    bytes32[] storage segments,
    uint64 price,
    uint256 segmentIndex,
    uint256 slotIndex,
    uint256 tombstoneSegmentOffset,
    BokkyPooBahsRedBlackTreeLibrary.Tree storage tree
  ) private {
    bytes32 segment = segments[segmentIndex];
    bytes10 slot = segment.getSlot(slotIndex);
    uint48 orderId = slot.getOrderId();

    require(_orders[orderId].maker == sender, NotMaker());

    bool isFinalSegment = segmentIndex == segments.length - 1;
    bool isOnlyOrderInSegment = segment.onlyContainsSlot(slotIndex);
    if (isFinalSegment && isOnlyOrderInSegment) {
      // If this is the only segment then remove the whole price level
      segments.pop();
      // There are no other segments so remove the price level
      if (segments.length == tombstoneSegmentOffset) {
        tree.remove(price);
      }
    } else {
      uint256 absoluteSlotIndexToRemove = segmentIndex * NUM_SLOTS_PER_SEGMENT + slotIndex;

      // Although this is called next, it also acts as the "last" used later
      uint256 nextSegmentIndex = absoluteSlotIndexToRemove / NUM_SLOTS_PER_SEGMENT;
      uint256 nextSlotIndex = absoluteSlotIndexToRemove % NUM_SLOTS_PER_SEGMENT;
      // Shift orders cross-segments.
      // This does all except the last order
      uint256 totalOrders = segments.length * NUM_SLOTS_PER_SEGMENT - 1;
      for (uint256 i = absoluteSlotIndexToRemove; i < totalOrders; ++i) {
        nextSegmentIndex = (i + 1) / NUM_SLOTS_PER_SEGMENT;
        nextSlotIndex = (i + 1) % NUM_SLOTS_PER_SEGMENT;

        bytes32 currentOrNextSegment = segments[nextSegmentIndex];
        uint256 currentSegmentIndex = i / NUM_SLOTS_PER_SEGMENT;
        uint256 currentSlotIndex = i % NUM_SLOTS_PER_SEGMENT;
        bytes32 currentSegment = segments[currentSegmentIndex];
        bytes10 nextSlot = currentOrNextSegment.getSlot(nextSlotIndex);
        if (nextSlot == 0) {
          // When reaching a hole, make sure it has iterated to the last order.

          // Must iterate to the last seg
          require(nextSegmentIndex == segments.length - 1, PriceSegmentHasAHole());

          // nextSlot and subsequent slots must be empty
          require(currentOrNextSegment.getRemainingSegment(nextSlotIndex) == 0, PriceSegmentHasAHole());

          // The last non-empty order must be in `seg[seg.len-1]` (`seg.len-1` cannot point to an empty segment).
          require(nextSlotIndex > 0, LastPriceSegmentCannotBeEmpty());

          // There are no more orders left, reset back to the currently iterated order as the last
          nextSegmentIndex = currentSegmentIndex;
          nextSlotIndex = currentSlotIndex;
          break;
        }

        // Clear the current slot and set it with the shifted slot
        currentSegment = currentSegment.setSlot(currentSlotIndex, nextSlot);
        segments[currentSegmentIndex] = currentSegment;
      }
      // Only pop if the next slot is 0 which means there is only 1 slot left in that segment (at the start)
      if (nextSlotIndex == 0) {
        segments.pop();
      } else {
        // Clear the last element
        bytes32 lastSegment = segments[nextSegmentIndex];
        lastSegment = lastSegment.clearSlot(nextSlotIndex);
        segments[nextSegmentIndex] = lastSegment;
      }
    }
  }

  function _safeBatchTransferNFTsToUs(address from, uint256[] memory tokenIds, uint256[] memory amounts) private {
    _nft.safeBatchTransferFrom(from, address(this), tokenIds, amounts, "");
  }

  function _safeBatchTransferNFTsFromUs(address to, uint256[] memory tokenIds, uint256[] memory amounts) private {
    _nft.safeBatchTransferFrom(address(this), to, tokenIds, amounts, "");
  }

  function _safeTransferNFTsToUs(address from, uint256 tokenId, uint256 amount) private {
    _nft.safeTransferFrom(from, address(this), tokenId, amount, "");
  }

  function _safeTransferNFTsFromUs(address to, uint256 tokenId, uint256 amount) private {
    _nft.safeTransferFrom(address(this), to, tokenId, amount, "");
  }

  function _safeTransferCoinsFromUs(address to, uint256 amount, bool returnWrappedS) private {
    SonicOrderBookLibrary._safeTransferCoinsFromUs(_isQuoteTokenSonic, _wS, _quoteToken, to, amount, returnWrappedS);
  }

  function _safeTransferCoinsToUs(address from, uint256 value, uint256 amount) private {
    // If they are paying with
    if (_isQuoteTokenSonic) {
      // Allow partial payment with native S and the rest wrapped S
      amount -= value;
    }

    if (amount != 0) {
      _quoteToken.safeTransferFrom(from, address(this), amount);

      if (_isQuoteTokenSonic) {
        // If they are paying with wrapped S, unwrap the remainder
        _wS.withdraw(amount);
      }
    }
  }

  function resolveQuoteTokens(
    address sender,
    uint256 fees,
    uint256 quoteTokensToUs,
    uint256 quoteTokensFromUs,
    uint256 value,
    bool returnWrappedS
  ) external onlyThisContract {
    if (_quoteToken == _wS && value > quoteTokensToUs) {
      // Refund remainder to the user
      unchecked {
        quoteTokensFromUs += value - quoteTokensToUs;
      }
      value = quoteTokensToUs;
    } else if (_quoteToken != _wS) {
      require(value == 0, ValueMustBeZeroForNonS());
    }

    if (quoteTokensToUs != 0) {
      _safeTransferCoinsToUs(sender, value, quoteTokensToUs);
    }

    if (quoteTokensFromUs != 0) {
      _safeTransferCoinsFromUs(sender, quoteTokensFromUs, returnWrappedS);
    }

    _sendFees(fees);
  }

  function _getLastSlot(
    mapping(uint256 price => bytes32[]) storage segmentsPriceMap,
    uint64 price
  ) private view returns (bytes10 lastSlot) {
    return segmentsPriceMap[price][segmentsPriceMap[price].length - 1].getSlot(NUM_SLOTS_PER_SEGMENT - 1);
  }

  /// @notice Set the fees for the contract and/or the maximum amount of orders allowed at a specific price level
  /// @notice Set constraints like minimum quantity of an order that is allowed to be placed and the minimum of specific tokenIds in this nft collection.
  /// @param devAddr The address to receive trade fees
  /// @param devFeeMakerBps The maker fee to send to the dev address (max 10%)
  /// @param devFeeTakerBps The taker fee to send to the dev address (max 10%)
  /// @param maxOrdersPerPrice The new maximum amount of orders allowed at a specific price level
  /// @param tokenIds Array of token IDs for which to set TokenInfo
  /// @param tokenIdInfos Array of TokenInfo to be set
  function setAdminVars(
    address devAddr,
    uint16 devFeeMakerBps,
    uint16 devFeeTakerBps,
    uint16 maxOrdersPerPrice,
    uint256[] calldata tokenIds,
    TokenIdInfo[] calldata tokenIdInfos
  ) external onlyOwner {
    SonicOrderBookLibrary.setTokenIdInfos(tokenIds, tokenIdInfos, _nft, _tokenIdInfos, BASE_DECIMAL_DIVISOR);

    // Checks inputs and fires an event
    SonicOrderBookLibrary.setFeesAndMaxOrdersPerPrice(devAddr, devFeeMakerBps, devFeeTakerBps, maxOrdersPerPrice);
    // State is stored afterwards
    _devAddr = devAddr;
    _devFeeMakerBps = devFeeMakerBps;
    _devFeeTakerBps = devFeeTakerBps;
    _maxOrdersPerPrice = maxOrdersPerPrice;
  }

  /// @notice Enables receiving native S when withdrawing from WSONIC
  receive() external payable {}

  // solhint-disable-next-line no-empty-blocks
  function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
}

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

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

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

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

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

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

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

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

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

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

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

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

pragma solidity ^0.8.24;

import {TransientSlot} from "@openzeppelin/contracts/utils/TransientSlot.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransientUpgradeable is Initializable {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

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

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

    function __ReentrancyGuardTransient_init() internal onlyInitializing {
    }

    function __ReentrancyGuardTransient_init_unchained() internal onlyInitializing {
    }
    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

File 10 of 36 : IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     *
     * NOTE: ERC-2981 allows setting the royalty to 100% of the price. In that case all the price would be sent to the
     * royalty receiver and 0 tokens to the seller. Contracts dealing with royalty should consider empty transfers.
     */
    function royaltyInfo(
        uint256 tokenId,
        uint256 salePrice
    ) external view returns (address receiver, uint256 royaltyAmount);
}

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

pragma solidity ^0.8.20;

interface IERC6372 {
    /**
     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
     */
    function clock() external view returns (uint48);

    /**
     * @dev Description of the clock
     */
    // solhint-disable-next-line func-name-mixedcase
    function CLOCK_MODE() external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC-1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[ERC].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of 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 value of tokens of token type `id` owned by `account`.
     */
    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 zero address.
     */
    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 a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * 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 `value` 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 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` 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 values,
        bytes calldata data
    ) external;
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 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 ERC-1155 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);
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 */
abstract contract ERC1155Holder 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);
    }

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) 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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

File 23 of 36 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

File 26 of 36 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

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

import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC6372} from "@openzeppelin/contracts/interfaces/IERC6372.sol";
import {Season, SeasonData, ClaimsData} from "../shared/global.sol";

interface ISonicAirdropNFT is IERC1155, IERC6372 {
  function decimals() external pure returns (uint8 numDecimals);

  function uriForUser(uint256 seasonId, address holder) external view returns (string memory seasonUri);

  function getInstantClaimBps(Season season) external view returns (uint16 instantClaimAvailableBps);

  function hasFullyClaimed(
    Season season,
    address account,
    uint128 initialAmount,
    uint128 totalAmount
  ) external view returns (bool hasClaimed);

  function getClaimedAmount(Season season, address account) external view returns (uint128 claimedAmount);

  function getSeasonData(Season season) external view returns (SeasonData memory seasonData);

  function getClaimsData(Season season) external view returns (ClaimsData memory claimsData);

  function getSeasonBalances(
    Season season,
    address holder
  ) external view returns (uint128 balance, uint128 vested, uint128 penalty);

  function claimAirdropNFT(
    Season season,
    uint128 initialAmount,
    uint128 totalAmount,
    bytes32[] calldata merkleProof
  ) external;

  function unlockAndBurnAirdrop(Season season, uint128 amount) external;

  function burnUnclaimed(Season season) external;

  function burnLocked(Season season) external;

  function addSeason(
    Season season,
    uint128 airdropAmount,
    uint40 startTime,
    uint40 maturationTime,
    uint40 claimsBurnTime,
    uint40 lockedBurnTime,
    uint16 instantClaimAvailableBps,
    bytes32 merkleRoot
  ) external payable;

  function editSeason(
    Season season,
    uint128 airdropAmount,
    uint40 startTime,
    uint40 maturationTime,
    uint40 claimsBurnTime,
    uint40 lockedBurnTime,
    uint16 instantClaimAvailableBps,
    bytes32 merkleRoot
  ) external payable;
}

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IWrappedSonic is IERC20Metadata {
  function depositFor(address account) external payable returns (bool);

  function withdraw(uint value) external;
}

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

// ----------------------------------------------------------------------------
// BokkyPooBah's Red-Black Tree Library v1.0-pre-release-a
//
// A Solidity Red-Black Tree binary search library to store and access a sorted
// list of unsigned integer data. The Red-Black algorithm rebalances the binary
// search tree, resulting in O(log n) insert, remove and search time (and ~gas)
//
// https://github.com/bokkypoobah/BokkyPooBahsRedBlackTreeLibrary
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2020. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsRedBlackTreeLibrary {
  error KeyCannotBeZero();
  error KeyDoesntExist();

  // Fits inside 1 storage slot
  struct Node {
    uint64 parent;
    uint64 left;
    uint64 right;
    uint56 tombstoneSegmentOffset; // Number of deleted segments, added here for packed gas efficiency
    bool red;
  }

  struct Tree {
    uint64 root;
    mapping(uint64 => Node) nodes;
  }

  uint64 private constant EMPTY = 0;

  function first(Tree storage self) internal view returns (uint64 key) {
    key = self.root;
    if (key != EMPTY) {
      while (self.nodes[key].left != EMPTY) {
        key = self.nodes[key].left;
      }
    }
  }

  function last(Tree storage self) internal view returns (uint64 key) {
    key = self.root;
    if (key != EMPTY) {
      while (self.nodes[key].right != EMPTY) {
        key = self.nodes[key].right;
      }
    }
  }

  function exists(Tree storage self, uint64 key) internal view returns (bool) {
    return (key != EMPTY) && ((key == self.root) || (self.nodes[key].parent != EMPTY));
  }

  function isEmpty(uint64 key) internal pure returns (bool) {
    return key == EMPTY;
  }

  function getEmpty() internal pure returns (uint64) {
    return EMPTY;
  }

  function getNodeUnsafe(Tree storage self, uint64 key) internal view returns (Node storage node) {
    return self.nodes[key];
  }

  function getNode(Tree storage self, uint64 key) internal view returns (Node storage node) {
    require(exists(self, key), KeyDoesntExist());
    return getNodeUnsafe(self, key);
  }

  // Intentionally does not check if key exists as we need to fetch the value without caring if it's currently in the tree
  function getTombstoneSegmentOffset(Tree storage self, uint64 key) internal view returns (uint56) {
    return self.nodes[key].tombstoneSegmentOffset;
  }

  // Key must exist!
  function edit(Tree storage self, uint64 key, uint56 newTombstonSegmentOffset) internal {
    self.nodes[key].tombstoneSegmentOffset = newTombstonSegmentOffset;
  }

  function insert(Tree storage self, uint64 key) internal {
    require(key != EMPTY, KeyCannotBeZero());
    uint64 cursor = EMPTY;
    uint64 probe = self.root;
    while (probe != EMPTY) {
      cursor = probe;
      if (key < probe) {
        probe = self.nodes[probe].left;
      } else {
        probe = self.nodes[probe].right;
      }
    }
    self.nodes[key] = Node({
      parent: cursor,
      left: EMPTY,
      right: EMPTY,
      red: true,
      tombstoneSegmentOffset: self.nodes[key].tombstoneSegmentOffset
    });
    if (cursor == EMPTY) {
      self.root = key;
    } else if (key < cursor) {
      self.nodes[cursor].left = key;
    } else {
      self.nodes[cursor].right = key;
    }
    insertFixup(self, key);
  }

  function remove(Tree storage self, uint64 key) internal {
    require(key != EMPTY, KeyCannotBeZero());
    require(exists(self, key), KeyDoesntExist());
    uint64 probe;
    uint64 cursor;
    if (self.nodes[key].left == EMPTY || self.nodes[key].right == EMPTY) {
      cursor = key;
    } else {
      cursor = self.nodes[key].right;
      while (self.nodes[cursor].left != EMPTY) {
        cursor = self.nodes[cursor].left;
      }
    }
    if (self.nodes[cursor].left != EMPTY) {
      probe = self.nodes[cursor].left;
    } else {
      probe = self.nodes[cursor].right;
    }
    uint64 yParent = self.nodes[cursor].parent;
    self.nodes[probe].parent = yParent;
    if (yParent != EMPTY) {
      if (cursor == self.nodes[yParent].left) {
        self.nodes[yParent].left = probe;
      } else {
        self.nodes[yParent].right = probe;
      }
    } else {
      self.root = probe;
    }
    bool doFixup = !self.nodes[cursor].red;
    if (cursor != key) {
      replaceParent(self, cursor, key);
      self.nodes[cursor].left = self.nodes[key].left;
      self.nodes[self.nodes[cursor].left].parent = cursor;
      self.nodes[cursor].right = self.nodes[key].right;
      self.nodes[self.nodes[cursor].right].parent = cursor;
      self.nodes[cursor].red = self.nodes[key].red;
      (cursor, key) = (key, cursor);
    }
    if (doFixup) {
      removeFixup(self, probe);
    }
    // Don't delete the node, so that we can re-use the tombstone offset if re-adding this price
    self.nodes[cursor].parent = EMPTY;
  }

  function treeMinimum(Tree storage self, uint64 key) private view returns (uint64) {
    while (self.nodes[key].left != EMPTY) {
      key = self.nodes[key].left;
    }
    return key;
  }

  function treeMaximum(Tree storage self, uint64 key) private view returns (uint64) {
    while (self.nodes[key].right != EMPTY) {
      key = self.nodes[key].right;
    }
    return key;
  }

  function rotateLeft(Tree storage self, uint64 key) private {
    uint64 cursor = self.nodes[key].right;
    uint64 keyParent = self.nodes[key].parent;
    uint64 cursorLeft = self.nodes[cursor].left;
    self.nodes[key].right = cursorLeft;
    if (cursorLeft != EMPTY) {
      self.nodes[cursorLeft].parent = key;
    }
    self.nodes[cursor].parent = keyParent;
    if (keyParent == EMPTY) {
      self.root = cursor;
    } else if (key == self.nodes[keyParent].left) {
      self.nodes[keyParent].left = cursor;
    } else {
      self.nodes[keyParent].right = cursor;
    }
    self.nodes[cursor].left = key;
    self.nodes[key].parent = cursor;
  }

  function rotateRight(Tree storage self, uint64 key) private {
    uint64 cursor = self.nodes[key].left;
    uint64 keyParent = self.nodes[key].parent;
    uint64 cursorRight = self.nodes[cursor].right;
    self.nodes[key].left = cursorRight;
    if (cursorRight != EMPTY) {
      self.nodes[cursorRight].parent = key;
    }
    self.nodes[cursor].parent = keyParent;
    if (keyParent == EMPTY) {
      self.root = cursor;
    } else if (key == self.nodes[keyParent].right) {
      self.nodes[keyParent].right = cursor;
    } else {
      self.nodes[keyParent].left = cursor;
    }
    self.nodes[cursor].right = key;
    self.nodes[key].parent = cursor;
  }

  function insertFixup(Tree storage self, uint64 key) private {
    uint64 cursor;
    while (key != self.root && self.nodes[self.nodes[key].parent].red) {
      uint64 keyParent = self.nodes[key].parent;
      if (keyParent == self.nodes[self.nodes[keyParent].parent].left) {
        cursor = self.nodes[self.nodes[keyParent].parent].right;
        if (self.nodes[cursor].red) {
          self.nodes[keyParent].red = false;
          self.nodes[cursor].red = false;
          self.nodes[self.nodes[keyParent].parent].red = true;
          key = self.nodes[keyParent].parent;
        } else {
          if (key == self.nodes[keyParent].right) {
            key = keyParent;
            rotateLeft(self, key);
          }
          keyParent = self.nodes[key].parent;
          self.nodes[keyParent].red = false;
          self.nodes[self.nodes[keyParent].parent].red = true;
          rotateRight(self, self.nodes[keyParent].parent);
        }
      } else {
        cursor = self.nodes[self.nodes[keyParent].parent].left;
        if (self.nodes[cursor].red) {
          self.nodes[keyParent].red = false;
          self.nodes[cursor].red = false;
          self.nodes[self.nodes[keyParent].parent].red = true;
          key = self.nodes[keyParent].parent;
        } else {
          if (key == self.nodes[keyParent].left) {
            key = keyParent;
            rotateRight(self, key);
          }
          keyParent = self.nodes[key].parent;
          self.nodes[keyParent].red = false;
          self.nodes[self.nodes[keyParent].parent].red = true;
          rotateLeft(self, self.nodes[keyParent].parent);
        }
      }
    }
    self.nodes[self.root].red = false;
  }

  function replaceParent(Tree storage self, uint64 a, uint64 b) private {
    uint64 bParent = self.nodes[b].parent;
    self.nodes[a].parent = bParent;
    if (bParent == EMPTY) {
      self.root = a;
    } else {
      if (b == self.nodes[bParent].left) {
        self.nodes[bParent].left = a;
      } else {
        self.nodes[bParent].right = a;
      }
    }
  }

  function removeFixup(Tree storage self, uint64 key) private {
    uint64 cursor;
    while (key != self.root && !self.nodes[key].red) {
      uint64 keyParent = self.nodes[key].parent;
      if (key == self.nodes[keyParent].left) {
        cursor = self.nodes[keyParent].right;
        if (self.nodes[cursor].red) {
          self.nodes[cursor].red = false;
          self.nodes[keyParent].red = true;
          rotateLeft(self, keyParent);
          cursor = self.nodes[keyParent].right;
        }
        if (!self.nodes[self.nodes[cursor].left].red && !self.nodes[self.nodes[cursor].right].red) {
          self.nodes[cursor].red = true;
          key = keyParent;
        } else {
          if (!self.nodes[self.nodes[cursor].right].red) {
            self.nodes[self.nodes[cursor].left].red = false;
            self.nodes[cursor].red = true;
            rotateRight(self, cursor);
            cursor = self.nodes[keyParent].right;
          }
          self.nodes[cursor].red = self.nodes[keyParent].red;
          self.nodes[keyParent].red = false;
          self.nodes[self.nodes[cursor].right].red = false;
          rotateLeft(self, keyParent);
          key = self.root;
        }
      } else {
        cursor = self.nodes[keyParent].left;
        if (self.nodes[cursor].red) {
          self.nodes[cursor].red = false;
          self.nodes[keyParent].red = true;
          rotateRight(self, keyParent);
          cursor = self.nodes[keyParent].left;
        }
        if (!self.nodes[self.nodes[cursor].right].red && !self.nodes[self.nodes[cursor].left].red) {
          self.nodes[cursor].red = true;
          key = keyParent;
        } else {
          if (!self.nodes[self.nodes[cursor].left].red) {
            self.nodes[self.nodes[cursor].right].red = false;
            self.nodes[cursor].red = true;
            rotateLeft(self, cursor);
            cursor = self.nodes[keyParent].left;
          }
          self.nodes[cursor].red = self.nodes[keyParent].red;
          self.nodes[keyParent].red = false;
          self.nodes[self.nodes[cursor].left].red = false;
          rotateRight(self, keyParent);
          key = self.root;
        }
      }
    }
    self.nodes[key].red = false;
  }
}
// ----------------------------------------------------------------------------
// End - BokkyPooBah's Red-Black Tree Library
// ----------------------------------------------------------------------------

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

import {SEGMENT_SIZE, SEGMENT_MASK} from "../shared/constants.sol";

/// @title SegmentLibrary
/// @notice Library for managing segments containing packed order data
/// @dev Segments are 256-bit values that contain 3 slots, each slot is 80 bits
///      (32 bits for normalized quantity and 48 bits for order ID).
///      Slots are indexed from 0-2, with slot 0 at the least significant bits.
///
///      Bit layout (256 bits total):
///      [unused 16 bits][slot 2: 80 bits][slot 1: 80 bits][slot 0: 80 bits]
library SegmentLibrary {
  /// @notice Sets a slot at the specified index, clearing any existing data first
  /// @dev This is the safe version that ensures no data corruption by clearing first
  /// @param segment The segment to modify
  /// @param slotIndex The index of the slot to set (0, 1, or 2)
  /// @param slot The 80-bit slot data to set
  /// @return newSegment The updated segment with the new slot data
  function setSlot(bytes32 segment, uint256 slotIndex, bytes10 slot) internal pure returns (bytes32 newSegment) {
    // First clear the existing slot, then set the new one
    bytes32 clearedSegment = clearSlot(segment, slotIndex);
    return setSlotUnsafe(clearedSegment, slotIndex, slot);
  }

  /// @notice Sets a slot at the specified index without clearing existing data first
  /// @dev Unsafe version for performance optimization. Only use when you know the slot is already empty.
  ///      Using this on a non-empty slot will result in data corruption through bit OR operations.
  /// @param segment The segment to modify
  /// @param slotIndex The index of the slot to set (0, 1, or 2)
  /// @param slot The 80-bit slot data to set
  /// @return newSegment The updated segment with the new slot data
  function setSlotUnsafe(bytes32 segment, uint256 slotIndex, bytes10 slot) internal pure returns (bytes32 newSegment) {
    return bytes32(uint256(segment) | (uint256(uint80(slot)) << (slotIndex * SEGMENT_SIZE)));
  }

  /// @notice Retrieves a slot from the specified index
  /// @param segment The segment to read from
  /// @param slotIndex The index of the slot to retrieve (0, 1, or 2)
  /// @return slot The 80-bit slot data at the specified index
  function getSlot(bytes32 segment, uint256 slotIndex) internal pure returns (bytes10 slot) {
    return bytes10(uint80((uint256(segment) >> (slotIndex * SEGMENT_SIZE)) & SEGMENT_MASK));
  }

  /// @notice Compresses the segment into 3 indicator bits
  /// @param segment The segment to read from
  /// @return status with only 3 bits sets each indicating whether the corresponding
  //                 slot in the segment is EMPTY or not.
  function compressedStatus(bytes32 segment) internal pure returns (uint256 status) {
    uint256 MASK = SEGMENT_MASK;
    uint256 SIZE = SEGMENT_SIZE;

    assembly ("memory-safe") {
      // s2 s1 s0 : segment
      status := iszero(and(segment, MASK))
      segment := shr(SIZE, segment)

      //  0 s2 s1 : segment
      status := or(
        shl(1, iszero(and(segment, MASK))),
        status
      )
      segment := shr(SIZE, segment)

      //  0  0 s2 : segment
      status := or(
        shl(2, iszero(and(segment, MASK))), // still mask in case segment has dirty uppper bits
        status
      )

      // b2 b1 b0 : status bits (it would only have 3 set bits)
      // b2       : is 1 if s2 the 3rd slot of original segment was EMPTY
      //    b1    : is 1 if s1 the 2nd slot of original segment was EMPTY
      //       b0 : is 1 if s0 the 1st slot of original segment was EMPTY
    }
  }

  /// @notice Checks if the segment only contains data in the specified slot
  /// @dev Returns true if all other slots in the segment are empty (zero)
  /// @param segment The segment to check
  /// @param slotIndex The index of the slot that should be the only non-empty slot
  /// @return True if only the specified slot contains data, false otherwise
  function onlyContainsSlot(bytes32 segment, uint256 slotIndex) internal pure returns (bool) {
    return clearSlot(segment, slotIndex) == 0;
  }

  /// @notice Clears a slot at the specified index, setting all its bits to zero
  /// @param segment The segment to modify
  /// @param slotIndex The index of the slot to clear (0, 1, or 2)
  /// @return newSegment The updated segment with the specified slot cleared
  function clearSlot(bytes32 segment, uint256 slotIndex) internal pure returns (bytes32 newSegment) {
    return bytes32(uint256(segment) & ~(uint256(SEGMENT_MASK) << (slotIndex * SEGMENT_SIZE)));
  }

  /// @notice Clears slots up to the specified index, setting all its bits to zero
  /// @param segment The segment to modify
  /// @param slotIndex The index of the slot to clear up to (0, 1, or 2)
  /// @return newSegment The updated segment with the right most slots cleared up to `slotIndex`
  function clearUpToSlot(bytes32 segment, uint256 slotIndex) internal pure returns (bytes32 newSegment) {
    if (slotIndex == 0) {
      return segment;
    }

    uint256 shiftAmount = slotIndex * SEGMENT_SIZE;
    return bytes32((uint256(segment) >> (shiftAmount)) << shiftAmount);
  }

  /// @notice Returns the remaining segment data after the specified slot index
  /// @dev Shifts the segment right to remove all slots up to and including the specified index.
  ///      Useful for iterating through higher-indexed slots or processing remaining data.
  /// @param segment The segment to process
  /// @param afterSlotIndex The slot index after which to get remaining data
  /// @return remainingSegment The segment data containing only slots with indices greater than afterSlotIndex
  function getRemainingSegment(
    bytes32 segment,
    uint256 afterSlotIndex
  ) internal pure returns (bytes32 remainingSegment) {
    return bytes32(uint256(segment) >> (afterSlotIndex * SEGMENT_SIZE));
  }
}

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

import {ORDER_ID_SIZE, QUANTITY_MASK, QUANTITY_TICK} from "../shared/constants.sol";

/// @title SlotLibrary
/// @notice Library for managing slots containing packed order data
/// @dev Slots are the smallest unit of storage in the orderbook. Each slot is 80 bits containing:
///      - Order ID: 48 bits (bits 0-47, least significant)
///      - Normalized Quantity: 32 bits (bits 48-79, most significant)
///
///      Bit layout (80 bits total):
///      [normalized quantity: 32 bits][order ID: 48 bits]
///
///      Normalized quantities are converted to actual quantities by multiplying by QUANTITY_TICK.
///      There are 3 slots per segment in the orderbook structure.
library SlotLibrary {
  /// @notice Creates a new slot by packing an order ID and normalized quantity
  /// @dev Combines the order ID (lower 48 bits) with normalized quantity (upper 32 bits)
  /// @param orderId The unique identifier for the order (must fit in 48 bits)
  /// @param normalizedQuantity The quantity normalized by QUANTITY_TICK (must fit in 32 bits)
  /// @return slot The packed 80-bit slot containing both values
  function createSlot(uint48 orderId, uint32 normalizedQuantity) internal pure returns (bytes10 slot) {
    // Shift the normalized quantity to its position and combine with order ID
    return bytes10(uint80(orderId) | (uint80(normalizedQuantity) << ORDER_ID_SIZE));
  }

  /// @notice Creates a new slot by packing an order ID and normalized quantity
  /// @dev Combines the order ID (lower 48 bits) with normalized quantity (upper 32 bits)
  /// @param orderId The unique identifier for the order (must fit in 48 bits)
  /// @param normalizedQuantity The quantity normalized by QUANTITY_TICK (must fit in 32 bits)
  /// @return slot The packed 80-bit slot containing both values
  function createSlotAsBytes32(uint48 orderId, uint32 normalizedQuantity) internal pure returns (bytes32 slot) {
    return bytes32(uint256(uint80(createSlot(orderId, normalizedQuantity))));
  }

  /// @notice Extracts the normalized quantity from a slot
  /// @dev Shifts right by ORDER_ID_SIZE bits and masks to get the upper 32 bits
  /// @param slot The slot to extract from
  /// @return normalizedQuantity The normalized quantity value (32 bits)
  function getNormalizedQuantity(bytes10 slot) internal pure returns (uint32 normalizedQuantity) {
    return uint32((uint80(slot) >> ORDER_ID_SIZE) & QUANTITY_MASK);
  }

  /// @notice Updates the normalized quantity in a slot while preserving the order ID
  /// @dev Clears the existing quantity bits and sets new ones, keeping order ID intact
  /// @param slot The slot to modify
  /// @param quantity The new quantity to set
  /// @return newSlot The updated slot with the new normalized quantity
  function setQuantity(bytes10 slot, uint88 quantity) internal pure returns (bytes10 newSlot) {
    // Convert quantity to normalized quantity by dividing by QUANTITY_TICK
    uint32 normalizedQuantity = uint32(quantity / QUANTITY_TICK);
    return setNormalizedQuantity(slot, normalizedQuantity);
  }

  /// @notice Updates the normalized quantity in a slot while preserving the order ID
  /// @param slot The slot to modify
  /// @param normalizedQuantity The new normalized quantity to set
  /// @return newSlot The updated slot with the new normalized quantity
  function setNormalizedQuantity(bytes10 slot, uint32 normalizedQuantity) internal pure returns (bytes10 newSlot) {
    return createSlot(getOrderId(slot), normalizedQuantity);
  }

  /// @notice Converts normalized quantity to actual quantity by applying the quantity tick
  /// @dev Multiplies normalized quantity by QUANTITY_TICK to get the real quantity value.
  ///      Uses unchecked arithmetic for gas optimization - overflow responsibility is on caller.
  /// @param slot The slot containing the normalized quantity
  /// @return quantity The actual quantity in wei (88 bits to handle QUANTITY_TICK multiplication)
  function getQuantity(bytes10 slot) internal pure returns (uint88 quantity) {
    unchecked {
      return uint88(getNormalizedQuantity(slot) * QUANTITY_TICK);
    }
  }

  /// @notice Extracts the order ID from a slot
  /// @dev Simply casts to uint48 to get the lower 48 bits containing the order ID
  /// @param slot The slot to extract from
  /// @return orderId The order ID (48 bits)
  function getOrderId(bytes10 slot) internal pure returns (uint48 orderId) {
    return uint48(uint80(slot));
  }
}

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IWrappedSonic} from "../interfaces/IWrappedSonic.sol";
import {ISonicAirdropNFT} from "../interfaces/ISonicAirdropNFT.sol";
import {BokkyPooBahsRedBlackTreeLibrary} from "./BokkyPooBahsRedBlackTreeLibrary.sol";

import {SeasonData, Season, TokenIdInfo, OrderSide, MakerOrderInfo} from "../shared/global.sol";
import {QUANTITY_TICK, FEE_SCALING_FACTOR, NUM_SLOTS_PER_SEGMENT, MAX_ORDER_ID, MAX_CLAIMABLE_ORDERS} from "../shared/constants.sol";

import {SegmentLibrary} from "./SegmentLibrary.sol";
import {SlotLibrary} from "./SlotLibrary.sol";

/// @title SonicOrderBookLibrary
/// @notice Helper library for reducing bytecode in the SonicOrderBook
library SonicOrderBookLibrary {
  using BokkyPooBahsRedBlackTreeLibrary for BokkyPooBahsRedBlackTreeLibrary.Tree;
  using SegmentLibrary for bytes32;
  using SlotLibrary for bytes10;
  using SafeERC20 for IERC20Metadata;

  event SetTokenIdInfos(uint256[] tokenIds, TokenIdInfo[] tokenInfos);
  event SetFees(address devAddr, uint256 devFeeMakerBps, uint256 devFeeTakerBps);
  event SetMaxOrdersPerPriceLevel(uint256 maxOrdersPerPrice);
  event ClaimedTokens(address indexed maker, uint48[] orderIds, uint256 amount);
  event ClaimedNFTs(address indexed maker, uint48[] orderIds, uint256[] tokenIds, uint256[] amounts);

  error PriceTickTooHigh();
  error TokenIdZeroIsReserved();
  error TokenIdTooHigh();
  error InvalidMinQuantity();
  error PriceTickCannotBeChanged();
  error PriceTickCannotBeZero();
  error SeasonLocked();
  error LengthMismatch();
  error ZeroAddress();
  error DevFeeTooHigh();
  error DevFeeNotSet();
  error MaxOrdersNotMultipleOfOrdersInSegment();
  error PriceTickNotCorrectMultiple();
  error OrderNotFound(uint256 orderId);
  error NotMaker();
  error PriceSegmentHasAHole();
  error LastPriceSegmentCannotBeEmpty();
  error NotTokenClaimable();
  error NotNFTClaimable();
  error NothingToClaim();
  error TransferFailed();
  error ClaimingTooManyOrders();

  struct ContractInterfaces {
    ISonicAirdropNFT nft;
    IERC20Metadata quoteToken;
    IWrappedSonic wS;
    address devAddr;
    bool isQuoteTokenSonic;
  }

  uint256 private constant SET_TRADEABLE_THRESHOLD_LOCKED_BURN_TIME = 7 days;

  uint256 internal constant BASE_DECIMAL_DIVISOR = 1e18; // Assuming 18 decimals for NFT

  function setTokenIdInfos(
    uint256[] calldata tokenIds,
    TokenIdInfo[] calldata tokenIdInfos,
    ISonicAirdropNFT nft,
    mapping(uint256 tokenId => TokenIdInfo tokenIdInfo) storage tokenIdInfoMap,
    uint256 baseDecimalDivisor
  ) external {
    require(tokenIds.length == tokenIdInfos.length, LengthMismatch());

    for (uint256 i = 0; i < tokenIds.length; ++i) {
      // Cannot change priceTick once set
      uint256 existingTick = tokenIdInfoMap[tokenIds[i]].priceTick;
      uint256 newTick = tokenIdInfos[i].priceTick;
      require(newTick < type(uint64).max, PriceTickTooHigh());

      uint256 tokenId = tokenIds[i];
      require(tokenId != 0, TokenIdZeroIsReserved());
      require(tokenId <= 5, TokenIdTooHigh());

      uint256 minQuantity = tokenIdInfos[i].minQuantity;
      require(minQuantity % QUANTITY_TICK == 0 && minQuantity >= QUANTITY_TICK, InvalidMinQuantity());

      require(existingTick == 0 || existingTick == newTick, PriceTickCannotBeChanged());
      require(newTick != 0, PriceTickCannotBeZero());
      require((newTick * QUANTITY_TICK) % baseDecimalDivisor == 0, PriceTickNotCorrectMultiple());

      SeasonData memory seasonData = nft.getSeasonData(Season(tokenId));
      if (seasonData.startTime != 0 && tokenIdInfos[i].isTradeable) {
        // If this season exists make sure it hasn't ended yet if setting tradeable to true
        require(seasonData.lockedBurnTime - SET_TRADEABLE_THRESHOLD_LOCKED_BURN_TIME > block.timestamp, SeasonLocked());
      }

      tokenIdInfoMap[tokenIds[i]] = tokenIdInfos[i];
    }

    emit SetTokenIdInfos(tokenIds, tokenIdInfos);
  }

  function setFeesAndMaxOrdersPerPrice(
    address devAddr,
    uint16 devFeeMakerBps,
    uint16 devFeeTakerBps,
    uint16 maxOrdersPerPrice
  ) external {
    if (devFeeMakerBps != 0 || devFeeTakerBps != 0) {
      require(devAddr != address(0), ZeroAddress());
      require(devFeeMakerBps <= FEE_SCALING_FACTOR / 10, DevFeeTooHigh());
      require(devFeeTakerBps <= FEE_SCALING_FACTOR / 10, DevFeeTooHigh());
    } else {
      require(devAddr == address(0), DevFeeNotSet());
    }
    emit SetFees(devAddr, devFeeMakerBps, devFeeTakerBps);

    require(maxOrdersPerPrice % NUM_SLOTS_PER_SEGMENT == 0, MaxOrdersNotMultipleOfOrdersInSegment());
    emit SetMaxOrdersPerPriceLevel(maxOrdersPerPrice);
  }

  function _find(
    bytes32[] storage segments,
    uint256 begin,
    uint256 end,
    uint256 value
  ) private view returns (uint256 mid, uint256 slotIndex) {
    while (begin < end) {
      mid = begin + (end - begin) / 2;
      bytes32 segment = segments[mid];
      slotIndex = 0;

      for (uint256 i = 0; i < NUM_SLOTS_PER_SEGMENT; ++i) {
        bytes10 slot = segment.getSlot(i);
        uint48 id = slot.getOrderId();
        if (id == value) {
          return (mid, i); // Return the index where the ID is found
        } else if (id < value) {
          slotIndex = i + 1;
        } else {
          break; // Break if the searched value is smaller, as it's a binary search
        }
      }

      if (slotIndex == NUM_SLOTS_PER_SEGMENT) {
        begin = mid + 1;
      } else {
        end = mid;
      }
    }

    return (type(uint).max, type(uint).max);
  }

  function find(
    bytes32[] storage segments,
    uint256 begin,
    uint256 end,
    uint256 value
  ) external view returns (uint256 mid, uint256 slotIndex) {
    return _find(segments, begin, end, value);
  }

  function claimTokens(
    address sender,
    uint48[] calldata orderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage asksAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage asks,
    ContractInterfaces memory contracts,
    bool returnWrappedS
  ) external {
    require(orderIds.length != 0, NothingToClaim());
    require(orderIds.length <= MAX_CLAIMABLE_ORDERS, ClaimingTooManyOrders());
    _claimTokens(sender, orderIds, orders, asksAtPrice, asks, contracts, returnWrappedS);
  }

  function _claimTokens(
    address sender,
    uint48[] calldata orderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage asksAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage asks,
    ContractInterfaces memory contracts,
    bool returnWrappedS
  ) internal {
    uint256 amount;
    uint256 fees;

    for (uint256 i = 0; i < orderIds.length; ++i) {
      uint48 orderId = orderIds[i];
      MakerOrderInfo storage orderInfo = orders[orderId];
      require(orderInfo.side == OrderSide.Sell, NotTokenClaimable());
      require(orderInfo.maker == sender, NotMaker());

      // Calculate claimable amount
      (uint256 claimableAmount, uint256 filledQuantity, uint256 fee) = _calculateClaimableTokens(
        orderId,
        orderInfo,
        asksAtPrice,
        asks
      );
      require(claimableAmount > 0, NothingToClaim());
      amount += claimableAmount;
      fees += fee;

      // Mark as claimed
      orders[orderId].remainingNormalizedQuantity -= uint32(filledQuantity / QUANTITY_TICK);
    }

    emit ClaimedTokens(sender, orderIds, amount);

    // Handle transfers
    _safeTransferCoinsFromUs(contracts, sender, amount, returnWrappedS);
    _sendFees(contracts, fees);
  }

  function claimNFTs(
    address sender,
    uint48[] calldata orderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage bidsAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage bids,
    ContractInterfaces memory contracts
  ) external {
    require(orderIds.length != 0, NothingToClaim());
    require(orderIds.length <= MAX_CLAIMABLE_ORDERS, ClaimingTooManyOrders());
    _claimNFTs(sender, orderIds, orders, bidsAtPrice, bids, contracts);
  }

  function _claimNFTs(
    address sender,
    uint48[] calldata orderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage bidsAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage bids,
    ContractInterfaces memory contracts
  ) private {
    uint256[] memory nftAmountsFromUs = new uint256[](orderIds.length);
    uint256[] memory tokenIds = new uint256[](orderIds.length);
    uint256[5] memory nftFeeInSeasons;

    for (uint256 i = 0; i < orderIds.length; ++i) {
      uint48 orderId = orderIds[i];
      MakerOrderInfo storage orderInfo = orders[orderId];
      require(orderInfo.maker == sender, NotMaker());
      require(orderInfo.side == OrderSide.Buy, NotNFTClaimable());

      (uint256 claimableAmount, uint256 fee) = _calculateClaimableNFTs(orderId, orderInfo, bidsAtPrice, bids);
      require(claimableAmount > 0, NothingToClaim());

      uint256 tokenId = orderInfo.tokenId;
      tokenIds[i] = tokenId;
      nftAmountsFromUs[i] = claimableAmount;

      orders[orderId].remainingNormalizedQuantity -= uint32((claimableAmount + fee) / QUANTITY_TICK);
      nftFeeInSeasons[tokenId - 1] += fee;
    }

    emit ClaimedNFTs(sender, orderIds, tokenIds, nftAmountsFromUs);

    // Handle transfers
    _safeBatchTransferNFTsFromUs(contracts, sender, tokenIds, nftAmountsFromUs);
    _transferNFTFees(contracts, nftFeeInSeasons);
  }

  function _calculateClaimableTokens(
    uint48 orderId,
    MakerOrderInfo storage orderInfo,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage asksAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage asks
  ) internal view returns (uint256 claimableAmount, uint256 filledQuantity, uint256 fee) {
    bytes32[] storage segments = asksAtPrice[orderInfo.tokenId][orderInfo.price];
    uint32 normalizedQuantity = orderInfo.remainingNormalizedQuantity;
    // Look for a currently active order
    uint56 tombstoneOffset = asks[orderInfo.tokenId].getTombstoneSegmentOffset(uint64(orderInfo.price));
    (uint256 segmentIndex, uint256 slotIndex) = _find(segments, tombstoneOffset, segments.length, orderId);

    if (segmentIndex == type(uint).max) {
      // If it cannot be found, it means the order was already claimed or cancelled so just use the remaining quantity
      filledQuantity = normalizedQuantity * QUANTITY_TICK;
    } else {
      filledQuantity = _getFilledQuantity(segments[segmentIndex], slotIndex, normalizedQuantity);
    }

    uint256 cost = (filledQuantity * orderInfo.price) / BASE_DECIMAL_DIVISOR;
    fee = _calcFee(cost, orderInfo.devFeeBps);
    claimableAmount = cost - fee;
  }

  function _calculateClaimableNFTs(
    uint48 orderId,
    MakerOrderInfo storage orderInfo,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage bidsAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage bids
  ) internal view returns (uint256 claimableAmount, uint256 fee) {
    bytes32[] storage segments = bidsAtPrice[orderInfo.tokenId][orderInfo.price];
    uint32 normalizedQuantity = orderInfo.remainingNormalizedQuantity;

    // Look for a currently active order
    uint56 tombstoneOffset = bids[orderInfo.tokenId].getTombstoneSegmentOffset(uint64(orderInfo.price));
    (uint256 segmentIndex, uint256 slotIndex) = _find(segments, tombstoneOffset, segments.length, orderId);
    uint256 filledQuantity;
    if (segmentIndex == type(uint).max) {
      // If it cannot be found, it means the order was already claimed or cancelled so just use the remaining quantity
      filledQuantity = normalizedQuantity * QUANTITY_TICK;
    } else {
      filledQuantity = _getFilledQuantity(segments[segmentIndex], slotIndex, normalizedQuantity);
    }

    fee = _calcFee(filledQuantity, orderInfo.devFeeBps);
    claimableAmount = filledQuantity - fee;
  }

  function tokensClaimable(
    uint48[] calldata orderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage asksAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage asks
  ) external view returns (uint256 amount) {
    for (uint256 i = 0; i < orderIds.length; ++i) {
      MakerOrderInfo storage orderInfo = orders[orderIds[i]];
      if (orderInfo.remainingNormalizedQuantity > 0 && orderInfo.side == OrderSide.Sell) {
        (uint256 claimableAmount, , ) = _calculateClaimableTokens(orderIds[i], orderInfo, asksAtPrice, asks);
        unchecked {
          amount += claimableAmount;
        }
      }
    }
  }

  function nftsClaimable(
    uint48[] calldata orderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage bidsAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage bids
  ) external view returns (uint256[] memory amounts) {
    amounts = new uint256[](orderIds.length);
    for (uint256 i = 0; i < orderIds.length; ++i) {
      MakerOrderInfo storage orderInfo = orders[orderIds[i]];
      if (orderInfo.remainingNormalizedQuantity > 0 && orderInfo.side == OrderSide.Buy) {
        (amounts[i], ) = _calculateClaimableNFTs(orderIds[i], orderInfo, bidsAtPrice, bids);
      }
    }
  }

  function _getFilledQuantity(
    bytes32 segment,
    uint256 slotIndex,
    uint32 remainingNormalizedQuantity
  ) internal pure returns (uint256 filledQuantity) {
    bytes10 slot = segment.getSlot(slotIndex);
    uint256 currentNormalizedQuantity = slot.getNormalizedQuantity();
    return (remainingNormalizedQuantity - currentNormalizedQuantity) * QUANTITY_TICK;
  }

  function claimAll(
    address sender,
    uint48[] calldata quoteTokenOrderIds,
    uint48[] calldata nftOrderIds,
    MakerOrderInfo[MAX_ORDER_ID] storage orders,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage asksAtPrice,
    mapping(uint256 tokenId => mapping(uint256 price => bytes32[] segments)) storage bidsAtPrice,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage asks,
    mapping(uint256 tokenId => BokkyPooBahsRedBlackTreeLibrary.Tree) storage bids,
    ContractInterfaces memory contracts,
    bool returnWrappedS
  ) external {
    require(quoteTokenOrderIds.length != 0 || nftOrderIds.length != 0, NothingToClaim());
    require(quoteTokenOrderIds.length + nftOrderIds.length <= MAX_CLAIMABLE_ORDERS, ClaimingTooManyOrders());

    // Handle NFT claims
    if (nftOrderIds.length != 0) {
      _claimNFTs(sender, nftOrderIds, orders, bidsAtPrice, bids, contracts);
    }

    // Handle token claims
    if (quoteTokenOrderIds.length != 0) {
      _claimTokens(sender, quoteTokenOrderIds, orders, asksAtPrice, asks, contracts, returnWrappedS);
    }
  }

  // Transfer helper functions
  function _safeTransferCoinsFromUs(
    bool isQuoteTokenSonic,
    IWrappedSonic wS,
    IERC20Metadata quoteToken,
    address to,
    uint256 amount,
    bool returnWrappedS
  ) internal {
    if (isQuoteTokenSonic) {
      if (returnWrappedS) {
        // Wrap it and send it (assumes depositFor always returns true)
        wS.depositFor{value: amount}(to);
      } else {
        // Send native S
        (bool success, ) = to.call{value: amount}("");
        require(success, TransferFailed());
      }
    } else {
      quoteToken.safeTransfer(to, amount);
    }
  }

  function _safeTransferCoinsFromUs(
    ContractInterfaces memory contracts,
    address to,
    uint256 amount,
    bool returnWrappedS
  ) internal {
    _safeTransferCoinsFromUs(
      contracts.isQuoteTokenSonic,
      contracts.wS,
      contracts.quoteToken,
      to,
      amount,
      returnWrappedS
    );
  }

  function _safeBatchTransferNFTsFromUs(
    ContractInterfaces memory contracts,
    address to,
    uint256[] memory tokenIds,
    uint256[] memory amounts
  ) private {
    contracts.nft.safeBatchTransferFrom(address(this), to, tokenIds, amounts, "");
  }

  function _sendFees(ContractInterfaces memory contracts, uint256 devFees) private {
    address devAddr = contracts.devAddr;
    if (devAddr != address(0) && devFees != 0) {
      _safeTransferCoinsFromUs(contracts, devAddr, devFees, false);
    }
  }

  function _transferNFTFees(ContractInterfaces memory contracts, uint256[5] memory nftFeeInSeasons) private {
    for (uint256 i = 0; i < nftFeeInSeasons.length; ++i) {
      uint256 fee = nftFeeInSeasons[i];
      if (fee == 0) {
        continue;
      }
      uint256 tokenId = i + 1; // Seasons are 1-indexed
      contracts.nft.safeTransferFrom(address(this), contracts.devAddr, tokenId, fee, "");
    }
  }

  function _calcFee(uint256 cost, uint256 devFeeBps) internal pure returns (uint256 fee) {
    unchecked {
      return (cost * devFeeBps) / FEE_SCALING_FACTOR;
    }
  }
}

File 35 of 36 : constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

// Orderbook constants (the first 3 are connected and should be changed together)
uint8 constant NUM_SLOTS_PER_SEGMENT = 3; // How many orders can be stored in a segment (256 bits)
uint256 constant NORMALIZED_QUANTITY_SIZE = 32; // bits
uint80 constant ORDER_ID_SIZE = 48; // bits
uint256 constant SEGMENT_SIZE = NORMALIZED_QUANTITY_SIZE + ORDER_ID_SIZE; // bits
uint80 constant SEGMENT_MASK = uint80((1 << SEGMENT_SIZE) - 1);
uint32 constant QUANTITY_MASK = uint32((1 << NORMALIZED_QUANTITY_SIZE) - 1);
uint256 constant QUANTITY_TICK = 0.01 ether; // Base token quantity ticks
uint256 constant FEE_SCALING_FACTOR = 10_000;
uint256 constant MAX_ORDER_ID = 281_474_976_710_655; // type(uint48).max
uint256 constant MAX_CLAIMABLE_ORDERS = 200;

File 36 of 36 : global.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

// Enums

enum Season {
  NONE,
  SEASON1,
  SEASON2,
  SEASON3,
  SEASON4,
  SEASON5
}

// Storage Structs

struct SeasonData {
  uint40 startTime;
  uint40 maturationTime;
  uint40 claimsBurnTime;
  uint40 lockedBurnTime;
  uint16 instantClaimAvailableBps;
  bytes32 merkleRoot;
}

struct ClaimsData {
  uint128 unclaimed;
  uint128 unlocked;
  uint128 locked;
  uint128 burned;
}

// Memory structs

struct NFTData {
  address holder;
  uint256 season;
  uint256 seasonStartTimestamp;
  uint256 seasonEndTimestamp;
  uint256 vestedPercent;
  uint256 usdPricePerSonic;
  uint256 lockedSonic;
  uint256 penaltyPercent;
  uint256 penaltySonic;
}

struct NFTStrings {
  string season;
  string startTime;
  string maturationTime;
  string seasonUnlockedSonic;
  string holder;
  string lockedSonic;
  string lockedUSD;
  string vestedSonic;
  string vestedUSD;
  string penaltyFactorOrBurned;
  string penaltySonic;
  string penaltyUSD;
}

// Scaling factor for basis point calculations (100% = 10000)
uint16 constant NFT_SCALING_FACTOR = 10000;

struct TokenIdInfo {
  uint128 priceTick;
  uint88 minQuantity;
  bool isTradeable;
}

enum OrderSide {
  Buy,
  Sell
}

struct MakerOrderInfo {
  address maker;
  uint8 tokenId;
  OrderSide side; // Buy or sell
  uint80 price;
  // Slot 2
  uint16 devFeeBps; // The fee at the time of order creation
  uint32 originalNormalizedQuantity; // Stored to be future proof but not used yet
  uint32 remainingNormalizedQuantity; // This contains the amount available for claiming if the slot is fully consumed
}

Settings
{
  "evmVersion": "cancun",
  "optimizer": {
    "enabled": true,
    "runs": 175,
    "details": {
      "yul": true
    }
  },
  "viaIR": true,
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/libraries/SonicOrderBookLibrary.sol": {
      "SonicOrderBookLibrary": "0x47baa84050b964270e865a5080d90edf9864e986"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"contract ISonicAirdropNFT","name":"nft","type":"address"},{"internalType":"contract IERC20Metadata","name":"quoteToken","type":"address"},{"internalType":"contract IWrappedSonic","name":"wS","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[],"name":"BaseDecimalDivisorMustMatch","type":"error"},{"inputs":[],"name":"DevFeeNotSet","type":"error"},{"inputs":[],"name":"DevFeeTooHigh","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"FailedToTakeExactQuantityFromBook","type":"error"},{"inputs":[],"name":"IncorrectDiffBetweenLastSegmentAndTheNewTombstoneOffset","type":"error"},{"inputs":[],"name":"IncorrectDiffBetweenLastSegmentAndTombstoneOffset","type":"error"},{"inputs":[],"name":"InsufficientQuantityFulfilled","type":"error"},{"inputs":[],"name":"InsufficientQuoteReceived","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidMinQuantity","type":"error"},{"inputs":[],"name":"InvalidQuantity","type":"error"},{"inputs":[],"name":"KeyCannotBeZero","type":"error"},{"inputs":[],"name":"KeyDoesntExist","type":"error"},{"inputs":[],"name":"LastPriceSegmentCannotBeEmpty","type":"error"},{"inputs":[],"name":"LengthMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedPrice","type":"uint256"},{"internalType":"uint256","name":"actualPrice","type":"uint256"}],"name":"MakerPriceMustMatch","type":"error"},{"inputs":[],"name":"MaxOrdersNotMultipleOfOrdersInSegment","type":"error"},{"inputs":[],"name":"NoQuantity","type":"error"},{"inputs":[],"name":"NotERC1155","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotMaker","type":"error"},{"inputs":[],"name":"NotTradeable","type":"error"},{"inputs":[],"name":"OnlyTheTombstoneSegmentCanStartWithEmptySlots","type":"error"},{"inputs":[],"name":"OnlyThisContract","type":"error"},{"inputs":[{"internalType":"uint256","name":"orderId","type":"uint256"}],"name":"OrderNotFound","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PostOnly","type":"error"},{"inputs":[{"internalType":"uint256","name":"priceTick","type":"uint256"}],"name":"PriceNotMultipleOfTick","type":"error"},{"inputs":[],"name":"PriceSegmentHasAHole","type":"error"},{"inputs":[],"name":"PriceTickCannotBeChanged","type":"error"},{"inputs":[],"name":"PriceTickCannotBeZero","type":"error"},{"inputs":[],"name":"PriceTickTooHigh","type":"error"},{"inputs":[],"name":"PriceZero","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SeasonLocked","type":"error"},{"inputs":[],"name":"SellMustUseExactQuantity","type":"error"},{"inputs":[],"name":"TokenIdTooHigh","type":"error"},{"inputs":[],"name":"TokenIdZeroIsReserved","type":"error"},{"inputs":[],"name":"TooManyOrdersHit","type":"error"},{"inputs":[],"name":"TotalCostConditionNotMet","type":"error"},{"inputs":[],"name":"TransferFailed","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[],"name":"ValueMustBeZeroForNonS","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":true,"internalType":"enum OrderSide","name":"side","type":"uint8"},{"indexed":false,"internalType":"uint48","name":"orderId","type":"uint48"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"quantity","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"originalQuantity","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"devFeeBps","type":"uint16"}],"name":"AddedToBook","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":false,"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"indexed":false,"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"ClaimedNFTs","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":false,"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ClaimedTokens","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":true,"internalType":"enum OrderSide","name":"side","type":"uint8"},{"indexed":false,"internalType":"uint48","name":"orderId","type":"uint48"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"quantity","type":"uint256"}],"name":"FailedToAddToBook","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"makerOrTaker","type":"address"},{"indexed":false,"internalType":"uint48","name":"orderId","type":"uint48"}],"name":"NewOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":false,"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"indexed":false,"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"prices","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"quantities","type":"uint256[]"}],"name":"OrdersCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"taker","type":"address"},{"indexed":true,"internalType":"uint48","name":"takerOrderId","type":"uint48"},{"indexed":false,"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"prices","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"quantities","type":"uint256[]"}],"name":"OrdersMatched","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"devAddr","type":"address"},{"indexed":false,"internalType":"uint256","name":"devFeeMakerBps","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"devFeeTakerBps","type":"uint256"}],"name":"SetFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"maxOrdersPerPrice","type":"uint256"}],"name":"SetMaxOrdersPerPriceLevel","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"quantityTick","type":"uint256"}],"name":"SetQuantityTickSize","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"components":[{"internalType":"uint128","name":"priceTick","type":"uint128"},{"internalType":"uint88","name":"minQuantity","type":"uint88"},{"internalType":"bool","name":"isTradeable","type":"bool"}],"indexed":false,"internalType":"struct TokenIdInfo[]","name":"tokenInfos","type":"tuple[]"}],"name":"SetTokenIdInfos","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum OrderSide","name":"side","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint64","name":"price","type":"uint64"}],"name":"allOrdersAtPrice","outputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"uint88","name":"quantity","type":"uint88"},{"internalType":"uint48","name":"id","type":"uint48"}],"internalType":"struct SonicOrderBook.Order[]","name":"orders","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"components":[{"internalType":"enum OrderSide","name":"side","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint64","name":"price","type":"uint64"},{"internalType":"uint88","name":"quantity","type":"uint88"},{"internalType":"bool","name":"onlyPost","type":"bool"},{"internalType":"bool","name":"onlyExactPriceIfMaker","type":"bool"}],"internalType":"struct SonicOrderBook.LimitOrder[]","name":"newOrders","type":"tuple[]"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"cancelAndPlaceLimitOrders","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"cancelOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"quoteTokenOrderIds","type":"uint48[]"},{"internalType":"uint48[]","name":"nftOrderIds","type":"uint48[]"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"claimAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"orderIds","type":"uint48[]"}],"name":"claimNFTs","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"orderIds","type":"uint48[]"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"claimTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getHighestBid","outputs":[{"internalType":"uint64","name":"highestBid","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getLowestAsk","outputs":[{"internalType":"uint64","name":"lowestAsk","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint48","name":"orderId","type":"uint48"}],"name":"getMakerOrder","outputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"uint8","name":"tokenId","type":"uint8"},{"internalType":"enum OrderSide","name":"side","type":"uint8"},{"internalType":"uint80","name":"price","type":"uint80"},{"internalType":"uint16","name":"devFeeBps","type":"uint16"},{"internalType":"uint32","name":"originalNormalizedQuantity","type":"uint32"},{"internalType":"uint32","name":"remainingNormalizedQuantity","type":"uint32"}],"internalType":"struct MakerOrderInfo","name":"order","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum OrderSide","name":"side","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint64","name":"price","type":"uint64"}],"name":"getNode","outputs":[{"components":[{"internalType":"uint64","name":"parent","type":"uint64"},{"internalType":"uint64","name":"left","type":"uint64"},{"internalType":"uint64","name":"right","type":"uint64"},{"internalType":"uint56","name":"tombstoneSegmentOffset","type":"uint56"},{"internalType":"bool","name":"red","type":"bool"}],"internalType":"struct BokkyPooBahsRedBlackTreeLibrary.Node","name":"node","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getTokenIdInfo","outputs":[{"components":[{"internalType":"uint128","name":"priceTick","type":"uint128"},{"internalType":"uint88","name":"minQuantity","type":"uint88"},{"internalType":"bool","name":"isTradeable","type":"bool"}],"internalType":"struct TokenIdInfo","name":"tokenIdInfo","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"orderIds","type":"uint48[]"}],"name":"nftsClaimable","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"enum OrderSide","name":"side","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint64","name":"price","type":"uint64"},{"internalType":"uint88","name":"quantity","type":"uint88"},{"internalType":"bool","name":"onlyPost","type":"bool"},{"internalType":"bool","name":"onlyExactPriceIfMaker","type":"bool"}],"internalType":"struct SonicOrderBook.LimitOrder[]","name":"orders","type":"tuple[]"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"placeLimitOrders","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"enum OrderSide","name":"side","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint88","name":"quantity","type":"uint88"},{"internalType":"uint256","name":"totalCost","type":"uint256"},{"internalType":"bool","name":"useExactQuantity","type":"bool"}],"internalType":"struct SonicOrderBook.MarketOrder","name":"order","type":"tuple"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"placeMarketOrder","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"fees","type":"uint256"},{"internalType":"uint256","name":"quoteTokensToUs","type":"uint256"},{"internalType":"uint256","name":"quoteTokensFromUs","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bool","name":"returnWrappedS","type":"bool"}],"name":"resolveQuoteTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"devAddr","type":"address"},{"internalType":"uint16","name":"devFeeMakerBps","type":"uint16"},{"internalType":"uint16","name":"devFeeTakerBps","type":"uint16"},{"internalType":"uint16","name":"maxOrdersPerPrice","type":"uint16"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"components":[{"internalType":"uint128","name":"priceTick","type":"uint128"},{"internalType":"uint88","name":"minQuantity","type":"uint88"},{"internalType":"bool","name":"isTradeable","type":"bool"}],"internalType":"struct TokenIdInfo[]","name":"tokenIdInfos","type":"tuple[]"}],"name":"setAdminVars","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint48[]","name":"orderIds","type":"uint48[]"}],"name":"tokensClaimable","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]

61014080604052346102435760608161634480380380916100208285610309565b8339810103126102435780516001600160a01b038116918282036102435760208101516001600160a01b0381169182820361024357604001516001600160a01b0381169390919084830361024357306080525f5160206163245f395f51905f525460ff8160401c166102fa576002600160401b03196001600160401b038216016102a4575b5060a05260c05260e05214610100526040516301ffc9a760e01b8152636cdb3d1360e11b6004820152602081602481855afa90811561024f575f91610269575b501561025a5760206004916040519283809263313ce56760e01b82525afa801561024f575f9061020e575b60ff915016604d81116101fa57670de0b6b3a764000090600a0a8061012052036101eb57604051615fe3908161034182396080518181816119050152611a16015260a051818181610eb5015281816117500152818161263c015281816126fe01528181612ab301526138b6015260c0518181816102fe015281816127230152612c24015260e05181818161032a0152818161274b0152612b5f0152610100518181816103a101528181610441015281816127770152612b0b0152610120518181816117860152818161298f015281816133e501526153a80152f35b6354b4e02360e11b5f5260045ffd5b634e487b7160e01b5f52601160045260245ffd5b506020813d602011610247575b8161022860209383610309565b81010312610243575160ff811681036102435760ff90610110565b5f80fd5b3d915061021b565b6040513d5f823e3d90fd5b631a69408960e11b5f5260045ffd5b90506020813d60201161029c575b8161028460209383610309565b8101031261024357518015158103610243575f6100e5565b3d9150610277565b6001600160401b0319166001600160401b039081175f5160206163245f395f51905f52556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f6100a5565b63f92ee8a960e01b5f5260045ffd5b601f909101601f19168101906001600160401b0382119082101761032c57604052565b634e487b7160e01b5f52604160045260245ffdfe61044080604052600436101561001d575b50361561001b575f80fd5b005b5f905f3560e01c90816301ffc9a714611c345750806346d5db1a14611ba65780634f1ef286146119d957806352aa5e8f1461195957806352d1902d146118f35780635eb07a021461161c578063647880f4146115ab5780636eb8ff2314611468578063715018a6146113ff578063793052b8146113e05780638129fc1c14611244578063820f8f7f146110d75780638da5cb5b146110a25780638f28864414611072578063902eb77314610b75578063a4f2608914610a49578063ad3cb1cc146109ed578063b2885b5214610917578063b76ef174146108b3578063bc197c811461081d578063c2f129b714610707578063c44db31014610647578063d272f29014610570578063d8ff46f8146102c2578063d923cf52146101d7578063f23a6e611461017d5763f2fde38b03610010573461017a57602036600319011261017a5761017761016a611cba565b610172612562565b612304565b80f35b80fd5b503461017a5760a036600319011261017a57610197611cba565b506101a0611cd0565b506084356001600160401b0381116101d3576101c0903690600401611da3565b5060405163f23a6e6160e01b8152602090f35b5080fd5b50604036600319011261017a57806004356001600160401b0381116102bf57610204903690600401611f2c565b906024359182151583036102bc576102249161021e6125cc565b33612c62565b610260519061030051916102805192303b156102b857604051631b1fe8df60e31b8152336004820152602481019490945260448401526064830152346084830152151560a482015281818060c481015b038183305af180156102ad57610298575b505f516020615f6e5f395f51905f525d80f35b816102a291611d67565b61017a57805f610285565b6040513d84823e3d90fd5b8480fd5b50505b50fd5b503461017a5760c036600319011261017a576102dc611cba565b906024356044359260643590608435946102f4611e5f565b90303303610561577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b039081167f0000000000000000000000000000000000000000000000000000000000000000909116818114989195909181818b80610558575b1561052d5750508899508390030191805b8061043d575b5050508061042c575b505083546001600160a01b031691905081151580610423575b61039f57505050f35b7f0000000000000000000000000000000000000000000000000000000000000000156103ed575082809281925af16103d56146a8565b50156103de5780f35b6312171d8360e31b8152600490fd5b909161017793506040519263a9059cbb60e01b6020850152602484015260448301526044825261041e606483611d67565b61471b565b50821515610396565b61043592612b07565b5f808061037d565b80917f0000000000000000000000000000000000000000000000000000000000000000918261051a575b50508115610374576040516323b872dd60e01b60208201526001600160a01b0387166024820152306044820152606480820184905281526104b3906104ad608482611d67565b8861471b565b6104be575b80610374565b813b15610516578791602483926040519485938492632e1a7d4d60e01b845260048401525af190811561050b578791156104b857816104fc91611d67565b61050757855f6104b8565b8580fd5b6040513d89823e3d90fd5b8780fd5b61052592935061226b565b905f80610467565b925093991561053f575b50879861036e565b610549575f610537565b638381596f60e01b8852600488fd5b5085831161035d565b6326107fef60e11b8652600486fd5b503461017a57602036600319011261017a57806004356001600160401b0381116102bf576105a2903690600401611de9565b6105aa6125cc565b7347baa84050b964270e865a5080d90edf9864e9866105c76126d3565b90803b156102b857604051630f22e9fd60e01b8152336004820152610140602482015293859385938492839261062691610606916101448601916120d3565b9160066044850152600560648501526003608485015260a48401906122b6565b03915af480156102ad5761029857505f516020615f6e5f395f51905f525d80f35b503461017a578061065736611e7d565b6106629291926125cc565b7347baa84050b964270e865a5080d90edf9864e98661067f6126d3565b92813b156105075760405163ac13a45f60e01b815233600482015261016060248201529486948694859384936106de916106be916101648701916120d3565b9260066044860152600460648601526002608486015260a48501906122b6565b151561014483015203915af480156102ad5761029857505f516020615f6e5f395f51905f525d80f35b50606036600319011261017a57806004356001600160401b0381116102bf57610734903690600401611de9565b906024356001600160401b0381116102bc5761077461075a610786923690600401611f2c565b919094610765611e6e565b9461076e6125cc565b336127e1565b819692965161080c575b505033612c62565b610260516103005190610280519382828285115f146107f057506107ab92935061226b565b303b156102b857604051631b1fe8df60e31b8152336004820152602481019490945260448401526064830152346084830152151560a482015281818060c48101610274565b925050610806926108009161226b565b906122f7565b836107ab565b6108169133612aaf565b5f8061077e565b503461017a5760a036600319011261017a57610837611cba565b50610840611cd0565b506044356001600160401b0381116101d357610860903690600401611ecf565b506064356001600160401b0381116101d357610880903690600401611ecf565b506084356001600160401b0381116101d3576108a0903690600401611da3565b5060405163bc197c8160e01b8152602090f35b503461017a576108cf6108c536611e7d565b929161076e6125cc565b8193929351610906575b5050816108f5575b82805f516020615f6e5f395f51905f525d80f35b6108ff9133612b07565b5f806108e1565b6109109133612aaf565b5f806108d9565b503461017a57602036600319011261017a576004356001600160401b0381116101d357602061094d610970923690600401611de9565b60405163c4b595bf60e01b815260806004820152938492839260848401916120d3565b60066024830152600460448301526002606483015203817347baa84050b964270e865a5080d90edf9864e9865af49081156102ad5782916109b7575b602082604051908152f35b90506020813d6020116109e5575b816109d260209383611d67565b810103126101d35760209150515f6109ac565b3d91506109c5565b503461017a578060031936011261017a5760408051610a0c8282611d67565b6005815260208101640352e302e360dc1b81528251938492602084525180928160208601528585015e828201840152601f01601f19168101030190f35b503461017a57606036600319011261017a57806004356001600160401b0381116102bf57610a7b903690600401611de9565b906024356001600160401b0381116102bc57610a9b903690600401611de9565b92610aa4611e6e565b92610aad6125cc565b7347baa84050b964270e865a5080d90edf9864e98691610acb6126d3565b833b15610516578795610b4c610b1d610b0b976040519a8b998a988998631cfbc22560e01b8a523360048b01526101c060248b01526101c48a01916120d3565b878103600319016044890152916120d3565b926006606486015260046084860152600560a4860152600260c4860152600360e48601526101048501906122b6565b15156101a483015203915af480156102ad5761029857505f516020615f6e5f395f51905f525d80f35b50366003190160c081126101d35760a01361017a57610b92611e5f565b610b9a6125cc565b610ba2612205565b610baa612205565b610bb2612205565b9184916001600160581b03610bc561228c565b1615801590611063575b1561105457662386f26fc100006001600160581b03610bec61228c565b160661104557600435926002841015610fbe57831591828015611037575b15611028576024359485895260016020526040892060ff60405191610c2e83611ce6565b546001600160801b03811683526001600160581b038160801c16602084015260d81c1615906040821591015261101957885460d081901c906001600160d01b0319610c788361261d565b60d01b169060018060d01b03161790818b556040518181527f7c373f9adf6b75cb1728b2b96d2f541ee8ecc1f34a603794af55c3311636b10360203392a28a908615611012576001600160401b03905b5f1992610cd3612601565b1580611009575b610ffb575b610ff757610ceb61228c565b9160405195610cf987611d30565b338752610d099060208801612188565b8a60408701526001600160401b0316606086015260808501526001600160581b031660a084015260c083015283151560e083015260b01c61ffff16610100820152886101208201526101408101968988526101608201928a84526101808301968b88528b6101a08501528b6101c0850152610d83936139db565b519251945191610d91612601565b610fd1575b15610e98576064358311610e89578692918591610e56575b90610db89161226b565b94303b15610e525760405191631b1fe8df60e31b83523360048401528360248401526044830152826064830152346084830152151560a4820152818160c48183305af180156102ad57610e39575b5050610e16610e26938233612638565b83546001600160a01b0316612638565b805f516020615f6e5f395f51905f525d80f35b81610e4391611d67565b610e4e57835f610e06565b8380fd5b8280fd5b919250506001600160581b03610e6a61228c565b168110610e7a5790838692610dae565b630b306ba760e41b8652600486fd5b630b83cca560e41b8752600487fd5b5060649594929195358610610fc257610eb284869761226b565b917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691823b15610fbe57604051637921219560e11b81523360048201523060248201526044810192909252606482015260a060848201525f60a4820152908590829060c490829084905af1908115610fb3578591610f9e575b5050303b156102bc5760405192631b1fe8df60e31b845233600485015260248401528360448401526064830152346084830152151560a4820152818160c48183305af180156102ad57610f89575b5050610e26565b81610f9391611d67565b61017a57805f610f82565b81610fa891611d67565b6102bc57835f610f34565b6040513d87823e3d90fd5b8680fd5b6370ba43e160e01b8552600485fd5b6001600160581b03610fe161228c565b168314610d9657635e8d8d4560e11b8852600488fd5b8c80fd5b600197506064359350610cdf565b50508c88610cda565b8b90610cc8565b63cbd4014160e01b8952600489fd5b630391dadf60e51b8852600488fd5b50611040612601565b610c0a565b63524f409b60e01b8652600486fd5b639464023560e01b8652600486fd5b5061106c612601565b15610bcf565b503461017a57602036600319011261017a576020611091600435612194565b6001600160401b0360405191168152f35b503461017a578060031936011261017a575f516020615f2e5f395f51905f52546040516001600160a01b039091168152602090f35b503461017a57602036600319011261017a5760043565ffffffffffff811681036101d3578160c060405161110a81611d15565b8281528260208201528260408201528260608201528260808201528260a0820152015265ffffffffffff8110156112305760011b906040519061114c82611d15565b82600601549260018060a01b0384168352602083019360ff8160a01c1685526007604085019261118260ff8460a81c1685612188565b606086019260b01c8352015492608085019261ffff8516845260ff60a087019763ffffffff8760101c16895263ffffffff60c089019760301c1687526040519760018060a01b039051168852511660208701525190600282101561121c57509461ffff63ffffffff94936001600160501b03869460e09960408a01525116606088015251166080860152511660a0840152511660c0820152f35b634e487b7160e01b81526021600452602490fd5b634e487b7160e01b82526032600452602482fd5b503461017a578060031936011261017a575f516020615f8e5f395f51905f525460ff8160401c1615906001600160401b038116801590816113d8575b60011490816113ce575b1590816113c5575b506113b65767ffffffffffffffff1981166001175f516020615f8e5f395f51905f52558161138a575b506112c46139b0565b6112cc6139b0565b6112d533612304565b6112dd6139b0565b6112e56139b0565b81546001600160d01b0316600160d01b178255604051662386f26fc1000081527fe62cb286676010487ba48a94533130ea5590ad3a059c31bdb2878d1a6724659290602090a16113325780f35b68ff0000000000000000195f516020615f8e5f395f51905f5254165f516020615f8e5f395f51905f52557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a180f35b68ffffffffffffffffff191668010000000000000001175f516020615f8e5f395f51905f52555f6112bb565b63f92ee8a960e01b8352600483fd5b9050155f611292565b303b15915061128a565b839150611280565b503461017a57602036600319011261017a576020611091600435612113565b503461017a578060031936011261017a57611418612562565b5f516020615f2e5f395f51905f5280546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461017a57602036600319011261017a57600435816001600160401b03821161017a5761149d6114c0923690600401611de9565b60405163332d573b60e11b815260806004820152938492839260848401916120d3565b60066024830152600560448301526003606483015203817347baa84050b964270e865a5080d90edf9864e9865af49081156102ad578291611516575b6040516020808252819061151290820185611e19565b0390f35b90503d8083833e6115278183611d67565b810190602081830312610e52578051906001600160401b038211610e4e570181601f82011215610e525780519061155d82611eb8565b9361156b6040519586611d67565b82855260208086019360051b83010193841161017a5750602001905b82821061159b57505050611512905f6114fc565b8151815260209182019101611587565b503461017a5760a06115c56115bf36611c87565b91612035565b6080604051916001600160401b0381511683526001600160401b0360208201511660208401526001600160401b03604082015116604084015266ffffffffffffff6060820151166060840152015115156080820152f35b50346118ef5760c03660031901126118ef57611636611cba565b6024359061ffff8216918281036118ef576044359161ffff83168084036118ef576064359161ffff8316918284036118ef576084356001600160401b0381116118ef57611687903690600401611de9565b60a4356001600160401b0381116118ef57366023820112156118ef5780600401356001600160401b0381116118ef5736602460608302840101116118ef576116cd612562565b7347baa84050b964270e865a5080d90edf9864e98693843b156118ef5760405163119ea47b60e31b815260a0600482015260a48101859052936001600160fb1b0381116118ef5760e48594939260249260051b809160c488013785018360c4820160031960c489850301018589015252019201905f905b80821061188e575050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166044830152600160648301527f000000000000000000000000000000000000000000000000000000000000000060848301525f919081900381855af4801561188357611868575b509081899493923b156102b857849260849160405195869485936364a7698d60e01b855260018060a01b03169c8d60048601526024850152604484015260648301525af480156102ad57611853575b50549061ffff60c01b9060c01b169361ffff60c01b19916001600160401b0360c01b1617169061ffff60a01b9060a01b16179061ffff60b01b9060b01b161717815580f35b8161185d91611d67565b6102b857845f61180e565b6118789194939299505f90611d67565b5f979091925f6117bf565b6040513d5f823e3d90fd5b91809450929092356001600160801b0381168091036118ef57815260208401356001600160581b0381168091036118ef57602082015260408401359081151582036118ef576060809160019315156040820152019401920184939291611744565b5f80fd5b346118ef575f3660031901126118ef577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316300361194a5760206040515f516020615f4e5f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b346118ef5760203660031901126118ef57611972611fed565b506004355f526001602052606060405f206040519061199082611ce6565b546001600160581b036001600160801b0382169283815260ff60406020830192848660801c168452019360d81c1615158352604051938452511660208301525115156040820152f35b60403660031901126118ef576119ed611cba565b6024356001600160401b0381116118ef57611a0c903690600401611da3565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016308114908115611b84575b5061194a57611a4e612562565b6040516352d1902d60e01b81526001600160a01b0383169290602081600481875afa5f9181611b50575b50611a905783634c9c8ce360e01b5f5260045260245ffd5b805f516020615f4e5f395f51905f52859203611b3e5750813b15611b2c575f516020615f4e5f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115611b14575f8083602061001b95519101845af4611b0e6146a8565b91614773565b505034611b1d57005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d602011611b7c575b81611b6c60209383611d67565b810103126118ef57519085611a78565b3d9150611b5f565b5f516020615f4e5f395f51905f52546001600160a01b03161415905083611a41565b346118ef57611bbd611bb736611c87565b91611f5c565b6040518091602082016020835281518091526020604084019201905f5b818110611be8575050500390f35b825180516001600160a01b031685526020818101516001600160581b03168187015260409182015165ffffffffffff169186019190915286955060609094019390920191600101611bda565b346118ef5760203660031901126118ef576004359063ffffffff60e01b82168092036118ef57602091630271189760e51b8114908115611c76575b5015158152f35b6301ffc9a760e01b14905083611c6f565b60609060031901126118ef5760043560028110156118ef5790602435906044356001600160401b03811681036118ef5790565b600435906001600160a01b03821682036118ef57565b602435906001600160a01b03821682036118ef57565b606081019081106001600160401b03821117611d0157604052565b634e487b7160e01b5f52604160045260245ffd5b60e081019081106001600160401b03821117611d0157604052565b6101e081019081106001600160401b03821117611d0157604052565b60a081019081106001600160401b03821117611d0157604052565b90601f801991011681019081106001600160401b03821117611d0157604052565b6001600160401b038111611d0157601f01601f191660200190565b81601f820112156118ef57803590611dba82611d88565b92611dc86040519485611d67565b828452602083830101116118ef57815f926020809301838601378301015290565b9181601f840112156118ef578235916001600160401b0383116118ef576020808501948460051b0101116118ef57565b90602080835192838152019201905f5b818110611e365750505090565b8251845260209384019390920191600101611e29565b359065ffffffffffff821682036118ef57565b60a4359081151582036118ef57565b6044359081151582036118ef57565b60406003198201126118ef57600435906001600160401b0382116118ef57611ea791600401611de9565b909160243580151581036118ef5790565b6001600160401b038111611d015760051b60200190565b9080601f830112156118ef578135611ee681611eb8565b92611ef46040519485611d67565b81845260208085019260051b8201019283116118ef57602001905b828210611f1c5750505090565b8135815260209182019101611f0f565b9181601f840112156118ef578235916001600160401b0383116118ef5760208085019460c085020101116118ef57565b9190916002811015611fd957611fa45781611fa1925f52600560205260405f206001600160401b0383165f5260205260405f20905f52600360205260405f20906123e9565b90565b81611fa1925f52600460205260405f206001600160401b0383165f5260205260405f20905f52600260205260405f20906123e9565b634e487b7160e01b5f52602160045260245ffd5b60405190611ffa82611ce6565b5f6040838281528260208201520152565b6040519061201882611d4c565b5f6080838281528260208201528260408201528260608201520152565b91909161204061200b565b506002811015611fd9576120bf57612062915f52600360205260405f20612595565b6040519061206f82611d4c565b546001600160401b03811682526001600160401b038160401c1660208301526001600160401b038160801c16604083015266ffffffffffffff8160c01c16606083015260f81c1515608082015290565b612062915f52600260205260405f20612595565b916020908281520191905f5b8181106120ec5750505090565b90919260208060019265ffffffffffff61210588611e4c565b1681520194019291016120df565b5f52600260205260405f206001600160401b038154169081612133575090565b60010191905b6001600160401b0381165f52826020526001600160401b0360405f205460401c1615612184576001600160401b03165f52816020526001600160401b0360405f205460401c16612139565b9150565b6002821015611fd95752565b5f52600360205260405f206001600160401b0381541690816121b4575090565b60010191905b6001600160401b0381165f52826020526001600160401b0360405f205460801c1615612184576001600160401b03165f52816020526001600160401b0360405f205460801c166121ba565b6040516107d0919061fa2061221a8183611d67565b8382526001600160401b03829411611d0157601f190190369060200137565b9061224382611eb8565b6122506040519182611d67565b8281528092612261601f1991611eb8565b0190602036910137565b9190820391821161227857565b634e487b7160e01b5f52601160045260245ffd5b6044356001600160581b03811681036118ef5790565b356001600160581b03811681036118ef5790565b80516001600160a01b039081168352602080830151821690840152604080830151821690840152606080830151909116908301526080908101511515910152565b9190820180921161227857565b6001600160a01b03168015612362575f516020615f2e5f395f51905f5280546001600160a01b0319811683179091556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3565b631e4fbdf760e01b5f525f60045260245ffd5b9060038202918083046003149015171561227857565b8181029291811591840414171561227857565b80548210156123b3575f5260205f2001905f90565b634e487b7160e01b5f52603260045260245ffd5b80518210156123b35760209160051b010190565b5f1981146122785760010190565b9291906123f6828261393b565b1561255a5766ffffffffffffff9161240d91612595565b5460c01c168254612426612421838361226b565b612375565b9061243082611eb8565b9161243e6040519384611d67565b80835261244d601f1991611eb8565b015f5b81811061254357505081945f935b82811061246b5750505052565b612475818361239e565b90549060031b1c5f5b6003811061249057505060010161245e565b61249a818361398b565b65ffffffffffff8160b01c1690816124b7575b505060010161247e565b9091976001600160581b03662386f26fc100008360e01c021665ffffffffffff8410156123b3576001936001600160581b0361253b946601fffffffffffe878060a01b039160af1c166006015416926040519361251385611ce6565b8452166020830152604082015261252a828a6123c7565b5261253581896123c7565b506123db565b96905f6124ad565b60209061254e611fed565b82828701015201612450565b506060925050565b5f516020615f2e5f395f51905f52546001600160a01b0316330361258257565b63118cdaa760e01b5f523360045260245ffd5b61259f828261393b565b156125bd576001600160401b03600192165f520160205260405f2090565b631540107f60e11b5f5260045ffd5b5f516020615f6e5f395f51905f525c6125f25760015f516020615f6e5f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b60843580151581036118ef5790565b3580151581036118ef5790565b65ffffffffffff1665ffffffffffff81146122785760010190565b90917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316803b156118ef57604051637921219560e11b81523060048201526001600160a01b0390931660248401526044830193909352606482015260a060848201525f60a482018190529091829081838160c481015b03925af18015611883576126c75750565b5f6126d191611d67565b565b6126db61200b565b505f54604051906001600160a01b03166126f482611d4c565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811683527f0000000000000000000000000000000000000000000000000000000000000000811660208401527f000000000000000000000000000000000000000000000000000000000000000016604083015260608201527f00000000000000000000000000000000000000000000000000000000000000001515608082015290565b91908110156123b35760051b0190565b3565ffffffffffff811681036118ef5790565b81156127cd570490565b634e487b7160e01b5f52601260045260245ffd5b91925f935f906127f081612239565b946127fa82612239565b9461280483612239565b9061280e84612239565b61281785612239565b955f5b8681106128d85750808a528852604051948060808701608088525260a0860192905f5b8181106128b157505050926128938594936128858487967f492cb7bf47ebe6723b966fc96a5de53bd973fe19292b2e207784921fe5c0a34e996128ac97036020890152611e19565b908582036040870152611e19565b83810360608501526001600160a01b0390911695611e19565b0390a2565b90919360208060019265ffffffffffff6128ca89611e4c565b16815201950192910161283d565b6128eb6128e68289876127a0565b6127b0565b65ffffffffffff8110156123b35760011b6006015460ff8160a81c169c6001600160401b0360ff8360a01c169260b01c169d6002811015611fd9576129dd57908d6129b4849361080061298d6001600160581b036129858f6128e660019b8f92612954936127a0565b885f52600560205260405f20885f5260205260405f20895f5260036020528865ffffffffffff60405f209316614332565b16948561238b565b7f0000000000000000000000000000000000000000000000000000000000000000906127c3565b9e5b6129c0848a6123c7565b526129cb838c6123c7565b526129d682866123c7565b520161281a565b9c929081612a57818f8f8796612a51918f612a4b6001600160581b038f8e612a1060019f6128e6908f97612a42956127a0565b90855f52600460205260405f20815f5260205260405f2090865f52600260205265ffffffffffff60405f209316614332565b169889966123c7565b526123c7565b526123db565b946129b6565b92612a9190612a9f936020969360018060a01b0316865260018060a01b03168686015260a0604086015260a0850190611e19565b908382036060850152611e19565b9060808183039101525f81520190565b90917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316803b156118ef576126b6935f809460405196879586948593631759616b60e11b85523060048601612a5d565b90917f000000000000000000000000000000000000000000000000000000000000000015612be65715612bc25760405163aa67c91960e01b81526001600160a01b0391821660048201529160209183916024918391907f0000000000000000000000000000000000000000000000000000000000000000165af1801561188357612b8e5750565b6020813d602011612bba575b81612ba760209383611d67565b810103126118ef5751801515036118ef57565b3d9150612b9a565b5f80809381935af1612bd26146a8565b506126d1576312171d8360e31b5f5260045ffd5b5060405163a9059cbb60e01b60208201526001600160a01b0390911660248201526044808201929092529081526126d190612c22606482611d67565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661471b565b9060058110156123b35760051b0190565b610400526102e0526102c08190525f61028081905261030081905261026081905261016081905261020052612c9690612239565b61022052612ca66102c051612239565b610240525f610380526102c051612cbc90612239565b6103a052612ccc6102c051612239565b61034052612cd8612205565b6101e052612ce4612205565b6101a052612cf0612205565b610180525f546103e081905260d01c60c05260a06103c0819052604051610360819052612d1d9190611d67565b6103c0516103605136903760405161032052612d3b61032051611d30565b5f60206103205101525f60406103205101525f60606103205101525f60806103205101525f6103c0516103205101525f6101206103205101525f6101406103205101525f6101606103205101525f6101806103205101525f6101a06103205101525f6101c061032051015260018060a01b03610400511661032051525f1960c06103205101525f60e061032051015261ffff6103e05160b01c166101006103205101525f60a0525b6102c05160a05110156137ce57602060c060a051026102e0510101355f5260016020526001600160801b0360405f2054166101c0525f6102a0525f6102a0525f5f6001600160581b03612e42606060c060a051026102e05101016122a2565b16156137bf57662386f26fc100006001600160581b03612e6e606060c060a051026102e05101016122a2565b16066137b0576001600160401b03612e92604060c060a051026102e05101016146d7565b16156137a157602060c060a051026102e0510101355f52600160205260ff60405f205460d81c1615613792576001600160401b03612edc604060c060a051026102e05101016146d7565b166101c051156127cd576101c05190066001600160801b031661377c5760018060a01b036103205151167f7c373f9adf6b75cb1728b2b96d2f541ee8ecc1f34a603794af55c3311636b103602060405165ffffffffffff60c051168152a2600260c060a051026102e0510135101561012052610120516118ef57612f7160c060a051026102e051013560206103205101612188565b602060c060a051026102e05101013560406103205101526001600160401b03612fa6604060c060a051026102e05101016146d7565b16606061032051015265ffffffffffff60c0511660806103205101526001600160581b03612fe0606060c060a051026102e05101016122a2565b166103c0516103205101525f6101206103205101525f6101406103205101525f6101606103205101525f6101806103205101525f6101a06103205101525f6101c061032051015261303f610180516101a0516101e051610320516139db565b6101606103205101516101405261018061032051015160e05261014061032051015161014051613752575b613092906001600160581b0361308c606060c060a051026102e05101016122a2565b1661226b565b90602060c060a051026102e0510101355f5260016020526001600160581b0360405f205460801c168210155f146136af5750806102a05260018060a01b03610320515116610120516118ef576130f4604060c060a051026102e05101016146d7565b916001600160581b03613113606060c060a051026102e05101016122a2565b16610100528263ffffffff662386f26fc1000083041161368e5763ffffffff662386f26fc10000830416935f6101205260c060a051026102e0510135155f1461363c575060a0516102e051602060c0909202018101355f908152600582526040808220600390935290206101c0519091600f9190910b906f7fffffffffffffffffffffffffffffff198214612278576131b49387925f039360c0519261529e565b925b61ffff5f546103c0511c16906040516131ce81611d15565b8481526020810160ff602060c060a051026102e051010135168152604082019261320360c060a051026102e051013585612188565b6001600160401b0388166060840152846080840152806103c05184015260c083015265ffffffffffff60c05110156123b357815160c05160011b60060180546001600160a01b039092166001600160a01b03199092169190911790819055905192519092906002811015611fd957613315936001600160501b0360b01b606085015160b01b169260ff60a01b906103c0511b169060018060a01b0316179060ff60a81b9060a81b16171760c05160011b6006015563ffffffff60c06007815160011b019261ffff60808201511684549065ffffffff00006103c05184015160101b169165ffffffffffff19161717845501511663ffffffff60301b82549160301b169063ffffffff60301b1916179055565b5f610120526040519165ffffffffffff60c0511683526001600160401b038516602084015260408301526101005160608301526080820152602060c060a051026102e051010135917f39bcecdfb7e71a8c70cee1d2349ccf3e9f853bfdfe62c1a7939ea4971b2f2e6d60c060a051026102e0510135926103c05190a4806133aa6103c05160c060a051026102e0510101612610565b6135ce575b505b6133bc60c05161261d565b60c052610120516118ef575f6101205260c060a051026102e0510135155f1461350657613419907f0000000000000000000000000000000000000000000000000000000000000000906001600160401b036102a0519116026127c3565b610140510161030051016103005261014051613440575b505b600160a0510160a052612de3565b6134759061347060e051916134706102a0516001600160581b0361308c606060c060a051026102e05101016122a2565b61226b565b602060c060a051026102e051010135613494610380516103a0516123c7565b52610380516080526134a8610380516123db565b610380526134bb608051610340516123c7565b5260a0516102e05160c09190910201602001355f198101908111612278576134ff6134f560e0516134ef8461036051612c51565b516122f7565b9161036051612c51565b525f613430565b50806001600160581b03613526606060c060a051026102e05101016122a2565b1603613565575b5061354961354060e0516101405161226b565b610260516122f7565b6102605261355c60e051610280516122f7565b61028052613432565b6135a790602060c060a051026102e05101013561358861020051610220516123c7565b526001600160581b0361308c606060c060a051026102e05101016122a2565b6135c7610200516135ba610200516123db565b61020052610240516123c7565b525f61352d565b6001600160401b036135ec604060c060a051026102e05101016146d7565b166001600160401b0382161461360e604060c060a051026102e05101016146d7565b901561361a57506133af565b906001600160401b03809263d25073c160e01b5f52166004521660245260445ffd5b6136889150602060c060a051026102e0510101355f5260046020528460405f20602060c060a051026102e0510101355f52600260205260405f20926101c051600f0b9360c0519261529e565b926131b6565b662386f26fc10000826306dfcc6560e41b5f5260206004520460245260445ffd5b90806136bc575b506133b1565b9150506136d5604060c060a051026102e05101016146d7565b61032051515f610120526040805160c0805165ffffffffffff1682526001600160401b03851660208084019190915292820186905260a0516102e05191020191820135929135916001600160a01b0316907fe0c590fd7544972fc237bcd202330c7f935257be2b2e2b32e6c07698228ba90290606090a45f6136b6565b613768608060c060a051026102e0510101612610565b1561306a576304118ad560e31b5f5260045ffd5b631d9b7a6960e21b5f526101c05160045260245ffd5b63cbd4014160e01b5f5260045ffd5b637294708f60e11b5f5260045ffd5b63524f409b60e01b5f5260045ffd5b639464023560e01b5f5260045ffd5b5f805460c0516001600160d01b0390911660d09190911b6001600160d01b031916179055610200516138a4575b61038051613879575b610160515b600581106138145750565b6138218161036051612c51565b5190811561387057600181018082116138565761016051546001936138509290916001600160a01b0316612638565b01613809565b634e487b7160e01b61016051526011600452602461016051fd5b60019150613850565b610380516103a0515261038051610340515261389f610340516103a05161040051612aaf565b613804565b610200805161022051525161024051527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316803b156118ef575f6040518092631759616b60e11b82528183816139116102405161022051306104005160048601612a5d565b03925af1801561188357613926575b506137fb565b5f61393091611d67565b5f610160525f613920565b906001600160401b0316801515918261395357505090565b80546001600160401b03168214925090821561396e57505090565b600192505f52016020526001600160401b0360405f205416151590565b90605081029080820460501490151715612278571c60b01b6001600160b01b03191690565b60ff5f516020615f8e5f395f51905f525460401c16156139cc57565b631afcd79f60e31b5f5260045ffd5b93909291936104205260206104205101516002811015611fd957613f0c5791926107d084526107d081526107d082525b613a17610420516147d1565b80613efa575b15613e1a5760406104209493945101515f52600260205260405f2060406104205101515f52600460205260405f206001600160401b03610120610420510151165f5260205260405f20936001600160401b038061012061042051015116165f526001820160205260405f20945f965f935f9061ffff610100610420510151169366ffffffffffffff81549a5460c01c169687935b8b891080613e08575b15613c82575050869a939a90613ad0888261239e565b90549060031b1c9b5f5b6003811080613c70575b15613c61576107d06101a06104205101511015613c52576050810281810460501482151715612278578e901c15613c035765ffffffffffff613b278f839061398b565b60b01c169d8e15613bb85790613b50613b488a83613bb09561042051615359565b92919a6122f7565b9f613b636101a06104205101518d6123c7565b52613b778d6101a0610420510151906123c7565b528c612a516001600160401b0361012061042051015116916101a061042051015190613ba2826123db565b6101a06104205101526123c7565b9c959c613ada565b909d5095898603613bf4576002613bce8861532f565b14613be557613bdf613bb0916123db565b9d6123db565b6354bf4b4160e11b5f5260045ffd5b634f37cd8f60e11b5f5260045ffd5b919c92989092915f198d018d811161227857821015613c2b576354bf4b4160e11b5f5260045ffd5b15613c4357613c39906123db565b979b91949b613ab1565b636743d7e360e01b5f5260045ffd5b63c869067960e01b5f5260045ffd5b509197613c39909c919c6123db565b50613c7d610420516147d1565b613ae4565b93955095999093979a9196506001600160401b0361012061042051015116956003613caf818504886122f7565b930690848403613dd15790613cc391615cbb565b9081613d72575050506001810180911161227857915b805b838110613d4c57508203613d0b575b541115613cfb575b50509192613a0b565b613d0491614925565b5f80613cf2565b6001600160401b0383165f9081526001850160205260409020805466ffffffffffffff60c01b191660c084901b66ffffffffffffff60c01b16179055613cea565b80613d6c613d5c6001938661239e565b8154905f199060031b1b19169055565b01613cdb565b613d7f829694939661532f565b60028114613be557600310613dba575b50613d9d613db5928561239e565b90919082549060031b91821b915f19901b1916179055565b613cd9565b5f198101908111612278578203613be5575f613d8f565b509194929050600181018091116122785784149081613dff575b50613cd9576330590ff960e11b5f5260045ffd5b9050155f613deb565b50613e15610420516147d1565b613aba565b909291926101a061042051015180613e33575b50505050565b808452808352815260018060a01b036104205151169065ffffffffffff6080610420510151169260406104205101519460405192606084016060855282518091526020608086019301905f5b818110613edc575050508392613ec283613ed093867f09a6cb3f5fc8c9d590bf15e926d32bc3e88a0034ed1e8e11bd026c4ab48deed49896036020870152611e19565b908382036040850152611e19565b0390a45f808080613e2d565b825165ffffffffffff16855260209485019490920191600101613e7f565b50613f0761042051614811565b613a1d565b91926107d084526107d081526107d082525b613f2a610420516147d1565b80614320575b1561425b5760406104209493945101515f52600360205260405f2060406104205101515f52600560205260405f206001600160401b03610120610420510151165f5260205260405f20936001600160401b038061012061042051015116165f526001820160205260405f20945f965f935f9061ffff610100610420510151169366ffffffffffffff81549a5460c01c169687935b8b891080614249575b156140eb575050869a939a90613fe3888261239e565b90549060031b1c9b5f5b60038110806140d9575b156140ca576107d06101a06104205101511015613c52576050810281810460501482151715612278578e901c1561408a5765ffffffffffff61403a8f839061398b565b60b01c169d8e156140635790613b50613b488a8361405b9561042051615359565b9c959c613fed565b909d5095898603613bf45760026140798861532f565b14613be557613bdf61405b916123db565b919c92989092915f198d018d8111612278578210156140b2576354bf4b4160e11b5f5260045ffd5b15613c43576140c0906123db565b979b91949b613fc4565b5091976140c0909c919c6123db565b506140e6610420516147d1565b613ff7565b93955095999093979a9196506001600160401b0361012061042051015116956003614118818504886122f7565b930690848403614212579061412c91615cbb565b90816141cb575050506001810180911161227857915b805b8381106141b557508203614174575b541115614164575b50509192613f1e565b61416d91614925565b5f8061415b565b6001600160401b0383165f9081526001850160205260409020805466ffffffffffffff60c01b191660c084901b66ffffffffffffff60c01b16179055614153565b806141c5613d5c6001938661239e565b01614144565b6141d8829694939661532f565b60028114613be5576003106141fb575b50613d9d6141f6928561239e565b614142565b5f198101908111612278578203613be5575f6141e8565b509194929050600181018091116122785784149081614240575b50614142576330590ff960e11b5f5260045ffd5b9050155f61422c565b50614256610420516147d1565b613fcd565b909291926101a0610420510151806142735750505050565b808452808352815260018060a01b036104205151169065ffffffffffff6080610420510151169260406104205101519460405192606084016060855282518091526020608086019301905f5b818110614302575050508392613ec283613ed093867f09a6cb3f5fc8c9d590bf15e926d32bc3e88a0034ed1e8e11bd026c4ab48deed49896036020870152611e19565b825165ffffffffffff168552602094850194909201916001016142bf565b5061432d61042051614811565b613f30565b9091939266ffffffffffffff6143488483612595565b5460c01c169285549360405194638955cf2160e01b865287600487015281602487015260448601528360648601526040856084817347baa84050b964270e865a5080d90edf9864e9865af4968715611883575f955f9861466d575b505f19861461465a576001600160581b03662386f26fc100006143d68a6143ca8a8661239e565b90549060031b1c61398b565b60e01c02169586986143e8828461239e565b90549060031b1c916143fa828461398b565b65ffffffffffff808260b01c1610156123b3576601fffffffffffe60af9190911c1660060154336001600160a01b039091160361464b578354925f198401848111612278578361444c918414926148af565b1581614643575b50156144f257505050614465816146eb565b54146144e2575b50505b65ffffffffffff80821610156123b357662386f26fc100006001600160581b0360076601fffffffffffe63ffffffff9460011b16019316041663ffffffff825460301c160363ffffffff811161227857815469ffffffff000000000000191660309190911b63ffffffff60301b16179055565b6144eb91614925565b5f8061446c565b9092945061450691955061450b9350612375565b6122f7565b91600383049261451e6003820692612375565b5f19810191908211612278575b818110614571575b50508061454a575061454591506146eb565b61446f565b8261456b613d9d9261455f614545968661239e565b90549060031b1c6148af565b9261239e565b60018101945091508382116122785760038085049406918285614594818761239e565b90549060031b1c91600384049260038506916145b0858a61239e565b90549060031b1c916145c2828261398b565b946001600160b01b0319861615614601575050506145f46145fb93836145ef6001989795613d9d956148af565b615581565b918861239e565b0161452b565b95985095509550509650508454905f1982019182116122785703613be5576050808302908382041483151715612278571c613be55715613c4357915f80614533565b90505f614453565b63b331e42160e01b5f5260045ffd5b846313a42eb760e21b5f5260045260245ffd5b955096506040853d6040116146a0575b8161468a60409383611d67565b810103126118ef5760208551950151965f6143a3565b3d915061467d565b3d156146d2573d906146b982611d88565b916146c76040519384611d67565b82523d5f602084013e565b606090565b356001600160401b03811681036118ef5790565b80548015614707575f190190614704613d5c838361239e565b55565b634e487b7160e01b5f52603160045260245ffd5b905f602091828151910182855af115611883575f513d61476a57506001600160a01b0381163b155b61474a5750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415614743565b90614797575080511561478857805190602001fd5b63d6bda27560e01b5f5260045ffd5b815115806147c8575b6147a8575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156147a0565b6101c081015161480c5760e0810151156147f45760c06101608201519101511190565b6001600160581b0360a0610140830151920151161190565b505f90565b60208101516002811015611fd957600114908115614895576001600160401b0361483e6040830151612194565b1691821561488e5715614871576001600160401b03606082015116821061486b57610120905b0152600190565b50505f90565b6001600160401b03606082015116821161486b5761012090614864565b5050505f90565b6001600160401b036148aa6040830151612113565b61483e565b906001600160501b0360508202918083046050149015171561227857901b191690565b805467ffffffffffffffff60801b191660809290921b67ffffffffffffffff60801b16919091179055565b9067ffffffffffffffff60401b82549160401b169067ffffffffffffffff60401b1916179055565b6001600160401b03821690811561528f57614940838261393b565b156125bd576001810192825f52836020526001600160401b0360405f205460401c16158015615270575b156152065780925b6001600160401b0384165f52846020526001600160401b0360405f205460401c1615155f146151df576001600160401b0384165f52846020526001600160401b0360405f205460401c16915b6001600160401b038581165f908152602088905260408082205486841683529120805467ffffffffffffffff19169190921690811790915580156151bf576001600160401b03908181165f52876020528160405f205460401c16828816145f146151a657165f5285602052614a368360405f206148fd565b6001600160401b0385165f528560205260405f205460f81c1591806001600160401b03871603614ff5575b5050614a8c575b50506001600160401b03165f5260205260405f206001600160401b03198154169055565b939091935b6001600160401b03835416906001600160401b0381169182141580614fdf575b15614fae5750805f52836020526001600160401b0360405f205416906001600160401b0382165f52846020526001600160401b0360405f205460401c16145f14614d5b576001600160401b0381165f52836020526001600160401b0360405f205460801c166001600160401b0381165f528460205260405f205460f81c614cee575b6001600160401b038181165f9081526020879052604080822054811c9092168152205460f81c1580614cc0575b15614b96576001600160401b03165f90815260208590526040902080546001600160f81b0316600160f81b179055935b93614a91565b90614c3a916001600160401b0381165f52856020526001600160401b038060405f205460801c16165f528560205260405f205460f81c15614c4b575b6001600160401b038281165f908152602088905260408082208054948416835281832080546001600160f81b031960f897881c151590971b969096166001600160f81b03968716178155815486169091555460801c9092168152208054909116905583615e04565b6001600160401b0382541693614b90565b6001600160401b038082165f818152602089905260408082208054821c9094168252812080546001600160f81b03908116909155919052815416600160f81b179055614c979085615ce0565b6001600160401b0381165f52846020526001600160401b038060405f205460801c169050614bd2565b506001600160401b038181165f908152602087905260408082205460801c9092168152205460f81c15614b60565b6001600160401b039081165f9081526020869052604080822080546001600160f81b03908116909155928416825290208054909116600160f81b179055614d358184615e04565b6001600160401b0381165f52836020526001600160401b0360405f205460801c16614b33565b6001600160401b0381165f52836020526001600160401b0360405f205460401c166001600160401b0381165f528460205260405f205460f81c614f41575b6001600160401b038181165f908152602087905260408082205460801c9092168152205460f81c1580614f14575b15614dfb576001600160401b03165f90815260208590526040902080546001600160f81b0316600160f81b17905593614b90565b90614c3a916001600160401b0381165f52856020526001600160401b038060405f205460401c16165f528560205260405f205460f81c15614e9e575b6001600160401b038281165f908152602088905260408082208054948416835281832080546001600160f81b031960f897881c151590971b969096166001600160f81b039687161781558154861690915554811c9092168152208054909116905583615ce0565b6001600160401b038082165f81815260208990526040808220805460801c9094168252812080546001600160f81b03908116909155919052815416600160f81b179055614eeb9085615e04565b6001600160401b0381165f52846020526001600160401b038060405f205460401c169050614e37565b506001600160401b038181165f9081526020879052604080822054811c9092168152205460f81c15614dc7565b6001600160401b039081165f9081526020869052604080822080546001600160f81b03908116909155928416825290208054909116600160f81b179055614f888184615ce0565b6001600160401b0381165f52836020526001600160401b0360405f205460401c16614d99565b6001600160401b039081165f90815260208690526040812080546001600160f81b0316905592959350919050614a68565b50815f528460205260405f205460f81c15614ab1565b9461514d919295805f52876020526001600160401b0360405f2054166001600160401b0383165f528860205260405f206001600160401b0382166001600160401b031982541617905580155f146151555750855467ffffffffffffffff19166001600160401b0383161786555b805f52876020526150966001600160401b0360405f205460401c166001600160401b0384165f528960205260405f206148fd565b6001600160401b038281165f81815260208b905260408082208054821c85168352818320805467ffffffffffffffff19168517905585835290822054929091526150e99260809290921c909116906148d2565b6001600160401b039182165f81815260208a90526040808220805460801c9095168252808220805467ffffffffffffffff19168417905592815291822054915281546001600160f81b031660f891821c151590911b6001600160f81b031916179055565b925f80614a61565b6001600160401b03908181165f52896020528160405f205460401c1683145f1461519257165f528760205261518d8260405f206148fd565b615062565b165f528760205261518d8260405f206148d2565b165f52856020526151ba8360405f206148d2565b614a36565b50835467ffffffffffffffff19166001600160401b038416178455614a36565b6001600160401b0384165f52846020526001600160401b0360405f205460801c16916149be565b825f52836020526001600160401b0360405f205460801c165b6001600160401b0381165f52846020526001600160401b0360405f205460401c161561526a576001600160401b03165f52836020526001600160401b0360405f205460401c1661521f565b92614972565b50825f52836020526001600160401b0360405f205460801c161561496a565b63d77534c760e01b5f5260045ffd5b95939291949561ffff5f5460c01c16955b6152bb8782848661559e565b61530c576001600160401b03889116600f0b016001600160801b0381166001600160401b0381116152f557506001600160401b03166152af565b6306dfcc6560e41b5f52604060045260245260445ffd5b9550611fa19496509085916001600160401b0383165f5260205260405f20615b16565b6001600160501b038080808416161581808560501c16161560011b179260a01c16161560021b1790565b5f9391615366848261398b565b60e0838101519082901c662386f26fc10000026001600160581b0316959190156155165761012084016153a36001600160401b038251168861238b565b6153ce7f000000000000000000000000000000000000000000000000000000000000000080926127c3565b6153e260c08801516101608901519061226b565b8091115f1461550657916001600160401b0361541161541a93662386f26fc100009560016101c08c015261238b565b915116906127c3565b04662386f26fc10000810290808204662386f26fc1000014901517156122785780156154f7578261546761546d9594936001600160581b03615460856145ef969c61226b565b1690615c8e565b936148af565b915b610140820161547f8582516122f7565b905261549c61298d6001600160401b03610120850151168661238b565b61016083016154ac8282516122f7565b905260208301516002811015611fd9576001036154df576127106154da9261018092020492019182516122f7565b905292565b506101806127106154da9286020492019182516122f7565b5050509350505050905f905f90565b505050505091935060019361546f565b9061553a6001600160581b0360a0869896999597990151166101408801519061226b565b9184831061554f57505050509160019361546f565b816154676145ef926001600160581b0361546087615572999d9c9a9b989b61226b565b919260016101c083015261546f565b916050820291808304605014901517156122785760b01c901b1790565b9290926155ab838261393b565b15615646576001906001600160401b0384165f520160205261ffff6155f96124216001600160401b0366ffffffffffffff60405f205460c01c16951694855f528660205260405f205461226b565b91161191821561560857505090565b5f9182526020526040902080549091505f1981019081116122785761562c9161239e565b90546001600160b01b031960039290921b1c60101b161590565b9250506001600160401b03811692831561528f5782546001600160401b03165f5b6001600160401b0382169081156156d1575081818710156156b0576001600160401b039150165f52600184016020526001600160401b0360405f205460401c16915b9190615667565b505f52600184016020526001600160401b0360405f205460801c16916156a9565b95915050929190926001830194815f52856020526157bd66ffffffffffffff60405f205460c01c16918361579c66ffffffffffffff6001600160401b036040519461571b86611d4c565b16958685526157766001600160401b038d61576e8260208a015f815260408b01935f855260608c0197885260808c019a60018c525f52602052818060405f209c51161682198c5416178b555116896148fd565b5116866148d2565b51845466ffffffffffffff60c01b1916911660c01b66ffffffffffffff60c01b16178355565b5181546001600160f81b031690151560f81b6001600160f81b031916179055565b80615ae25750825467ffffffffffffffff19161782555b905b6001600160401b038154166001600160401b0383169081141580615abc575b15615a8f575f81815260208690526040808220546001600160401b039081168084528284205482168452928290205492939290911c16820361596757506001600160401b038181165f9081526020879052604080822054831682528082205460801c9092168082529190205490939060f81c156158c657506001600160401b039081165f8181526020879052604080822080546001600160f81b03908116825596851683528183208054881690558054851683529082208054909616600160f81b17909555529154909116906157d6565b92506001600160401b0381165f52846020526001600160401b0360405f205460801c166001600160401b03841614615955575b506001600160401b038281165f9081526020869052604080822054831680835281832080546001600160f81b03818116835590861685529284208054909316600160f81b1790925590915254615950911682615ce0565b6157d6565b91506159618282615e04565b5f6158f9565b6001600160401b038281165f90815260208890526040808220548316825280822054811c909216808252919020549094919060f81c156159fc5750506001600160401b039081165f8181526020879052604080822080546001600160f81b03908116825596851683528183208054881690558054851683529082208054909616600160f81b17909555529154909116906157d6565b9093506001600160401b0382165f52856020526001600160401b0360405f205460401c1614615a7d575b506001600160401b038281165f9081526020869052604080822054831680835281832080546001600160f81b03818116835590861685529284208054909316600160f81b1790925590915254615950911682615e04565b9150615a898282615ce0565b5f615a26565b50546001600160401b03165f90815260209390935250604090912080546001600160f81b03169055600190565b505f81815260208690526040808220546001600160401b0316825290205460f81c6157f5565b8091105f14615b03575f5283602052615afe8160405f206148fd565b6157d4565b5f5283602052615afe8160405f206148d2565b939184549182615b57575b505050615b2d91615f05565b60b01c81549168010000000000000000831015611d015782613d9d9160016126d19501815561239e565b5f1983019183831161227857615b6c91612595565b9166ffffffffffffff835460c01c1690818310155f14615c6d575050615b92818661239e565b90549060031b1c5f6050905b60038110615bed575050615bb19061532f565b60028114613be55715918215615bd6575b505015613be557615b2d915b915f80615b21565b5460c01c66ffffffffffffff161490505f80615bc2565b8181028181048314821517156122785783901c15615c0d57600101615b9e565b96959193908795939515613c43575060b084901b6001600160b01b03191615615c4e575b50916126d195615c4861456b93613d9d9695615f05565b91615581565b549093929060c01c66ffffffffffffff168303613be55791925f615c31565b9150915003615c7f57615b2d91615bce565b63222570bf60e21b5f5260045ffd5b65ffffffffffff63ffffffff662386f26fc100006001600160581b03611fa1951604169160b01c16615f05565b8115615cdb5760508202918083046050149015171561227857811c901b90565b905090565b6001600160401b038083165f8181526001840160208190526040808320805480831c87168086529285205495909452909691959193919285169160801c851690615d2b9082906148fd565b80615de7575b508386165f528460205260405f20848216851982541617905580155f14615d9a575082851683198254161790555b8184165f5282602052615d758160405f206148d2565b165f526020526001600160401b0360405f2091166001600160401b0319825416179055565b8391508181165f52846020528160405f205460801c16828416145f14615dd357165f5282602052615dce8460405f206148d2565b615d5f565b165f5282602052615dce8460405f206148fd565b84165f528460205260405f2084841685198254161790555f615d31565b6001600160401b038083165f81815260018401602081905260408083208054608081901c87168086528386205496909552939792969294929386169290911c851690615e519082906148d2565b80615ee8575b508386165f528460205260405f20848216851982541617905580155f14615e9b575082851683198254161790555b8184165f5282602052615d758160405f206148fd565b8391508181165f52846020528160405f205460401c16828416145f14615ed457165f5282602052615ecf8460405f206148fd565b615e85565b165f5282602052615ecf8460405f206148d2565b84165f528460205260405f2084841685198254161790555f615e57565b65ffffffffffff1660309190911b63ffffffff60301b161760b01b6001600160b01b0319169056fe9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00a2646970667358221220e40a5e49865076890d8a3ec89090b7ada300c212bf7019cdf43d515f5f352ca064736f6c634300081e0033f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f3567000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38

Deployed Bytecode

0x61044080604052600436101561001d575b50361561001b575f80fd5b005b5f905f3560e01c90816301ffc9a714611c345750806346d5db1a14611ba65780634f1ef286146119d957806352aa5e8f1461195957806352d1902d146118f35780635eb07a021461161c578063647880f4146115ab5780636eb8ff2314611468578063715018a6146113ff578063793052b8146113e05780638129fc1c14611244578063820f8f7f146110d75780638da5cb5b146110a25780638f28864414611072578063902eb77314610b75578063a4f2608914610a49578063ad3cb1cc146109ed578063b2885b5214610917578063b76ef174146108b3578063bc197c811461081d578063c2f129b714610707578063c44db31014610647578063d272f29014610570578063d8ff46f8146102c2578063d923cf52146101d7578063f23a6e611461017d5763f2fde38b03610010573461017a57602036600319011261017a5761017761016a611cba565b610172612562565b612304565b80f35b80fd5b503461017a5760a036600319011261017a57610197611cba565b506101a0611cd0565b506084356001600160401b0381116101d3576101c0903690600401611da3565b5060405163f23a6e6160e01b8152602090f35b5080fd5b50604036600319011261017a57806004356001600160401b0381116102bf57610204903690600401611f2c565b906024359182151583036102bc576102249161021e6125cc565b33612c62565b610260519061030051916102805192303b156102b857604051631b1fe8df60e31b8152336004820152602481019490945260448401526064830152346084830152151560a482015281818060c481015b038183305af180156102ad57610298575b505f516020615f6e5f395f51905f525d80f35b816102a291611d67565b61017a57805f610285565b6040513d84823e3d90fd5b8480fd5b50505b50fd5b503461017a5760c036600319011261017a576102dc611cba565b906024356044359260643590608435946102f4611e5f565b90303303610561577f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad386001600160a01b039081167f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38909116818114989195909181818b80610558575b1561052d5750508899508390030191805b8061043d575b5050508061042c575b505083546001600160a01b031691905081151580610423575b61039f57505050f35b7f0000000000000000000000000000000000000000000000000000000000000001156103ed575082809281925af16103d56146a8565b50156103de5780f35b6312171d8360e31b8152600490fd5b909161017793506040519263a9059cbb60e01b6020850152602484015260448301526044825261041e606483611d67565b61471b565b50821515610396565b61043592612b07565b5f808061037d565b80917f0000000000000000000000000000000000000000000000000000000000000001918261051a575b50508115610374576040516323b872dd60e01b60208201526001600160a01b0387166024820152306044820152606480820184905281526104b3906104ad608482611d67565b8861471b565b6104be575b80610374565b813b15610516578791602483926040519485938492632e1a7d4d60e01b845260048401525af190811561050b578791156104b857816104fc91611d67565b61050757855f6104b8565b8580fd5b6040513d89823e3d90fd5b8780fd5b61052592935061226b565b905f80610467565b925093991561053f575b50879861036e565b610549575f610537565b638381596f60e01b8852600488fd5b5085831161035d565b6326107fef60e11b8652600486fd5b503461017a57602036600319011261017a57806004356001600160401b0381116102bf576105a2903690600401611de9565b6105aa6125cc565b7347baa84050b964270e865a5080d90edf9864e9866105c76126d3565b90803b156102b857604051630f22e9fd60e01b8152336004820152610140602482015293859385938492839261062691610606916101448601916120d3565b9160066044850152600560648501526003608485015260a48401906122b6565b03915af480156102ad5761029857505f516020615f6e5f395f51905f525d80f35b503461017a578061065736611e7d565b6106629291926125cc565b7347baa84050b964270e865a5080d90edf9864e98661067f6126d3565b92813b156105075760405163ac13a45f60e01b815233600482015261016060248201529486948694859384936106de916106be916101648701916120d3565b9260066044860152600460648601526002608486015260a48501906122b6565b151561014483015203915af480156102ad5761029857505f516020615f6e5f395f51905f525d80f35b50606036600319011261017a57806004356001600160401b0381116102bf57610734903690600401611de9565b906024356001600160401b0381116102bc5761077461075a610786923690600401611f2c565b919094610765611e6e565b9461076e6125cc565b336127e1565b819692965161080c575b505033612c62565b610260516103005190610280519382828285115f146107f057506107ab92935061226b565b303b156102b857604051631b1fe8df60e31b8152336004820152602481019490945260448401526064830152346084830152151560a482015281818060c48101610274565b925050610806926108009161226b565b906122f7565b836107ab565b6108169133612aaf565b5f8061077e565b503461017a5760a036600319011261017a57610837611cba565b50610840611cd0565b506044356001600160401b0381116101d357610860903690600401611ecf565b506064356001600160401b0381116101d357610880903690600401611ecf565b506084356001600160401b0381116101d3576108a0903690600401611da3565b5060405163bc197c8160e01b8152602090f35b503461017a576108cf6108c536611e7d565b929161076e6125cc565b8193929351610906575b5050816108f5575b82805f516020615f6e5f395f51905f525d80f35b6108ff9133612b07565b5f806108e1565b6109109133612aaf565b5f806108d9565b503461017a57602036600319011261017a576004356001600160401b0381116101d357602061094d610970923690600401611de9565b60405163c4b595bf60e01b815260806004820152938492839260848401916120d3565b60066024830152600460448301526002606483015203817347baa84050b964270e865a5080d90edf9864e9865af49081156102ad5782916109b7575b602082604051908152f35b90506020813d6020116109e5575b816109d260209383611d67565b810103126101d35760209150515f6109ac565b3d91506109c5565b503461017a578060031936011261017a5760408051610a0c8282611d67565b6005815260208101640352e302e360dc1b81528251938492602084525180928160208601528585015e828201840152601f01601f19168101030190f35b503461017a57606036600319011261017a57806004356001600160401b0381116102bf57610a7b903690600401611de9565b906024356001600160401b0381116102bc57610a9b903690600401611de9565b92610aa4611e6e565b92610aad6125cc565b7347baa84050b964270e865a5080d90edf9864e98691610acb6126d3565b833b15610516578795610b4c610b1d610b0b976040519a8b998a988998631cfbc22560e01b8a523360048b01526101c060248b01526101c48a01916120d3565b878103600319016044890152916120d3565b926006606486015260046084860152600560a4860152600260c4860152600360e48601526101048501906122b6565b15156101a483015203915af480156102ad5761029857505f516020615f6e5f395f51905f525d80f35b50366003190160c081126101d35760a01361017a57610b92611e5f565b610b9a6125cc565b610ba2612205565b610baa612205565b610bb2612205565b9184916001600160581b03610bc561228c565b1615801590611063575b1561105457662386f26fc100006001600160581b03610bec61228c565b160661104557600435926002841015610fbe57831591828015611037575b15611028576024359485895260016020526040892060ff60405191610c2e83611ce6565b546001600160801b03811683526001600160581b038160801c16602084015260d81c1615906040821591015261101957885460d081901c906001600160d01b0319610c788361261d565b60d01b169060018060d01b03161790818b556040518181527f7c373f9adf6b75cb1728b2b96d2f541ee8ecc1f34a603794af55c3311636b10360203392a28a908615611012576001600160401b03905b5f1992610cd3612601565b1580611009575b610ffb575b610ff757610ceb61228c565b9160405195610cf987611d30565b338752610d099060208801612188565b8a60408701526001600160401b0316606086015260808501526001600160581b031660a084015260c083015283151560e083015260b01c61ffff16610100820152886101208201526101408101968988526101608201928a84526101808301968b88528b6101a08501528b6101c0850152610d83936139db565b519251945191610d91612601565b610fd1575b15610e98576064358311610e89578692918591610e56575b90610db89161226b565b94303b15610e525760405191631b1fe8df60e31b83523360048401528360248401526044830152826064830152346084830152151560a4820152818160c48183305af180156102ad57610e39575b5050610e16610e26938233612638565b83546001600160a01b0316612638565b805f516020615f6e5f395f51905f525d80f35b81610e4391611d67565b610e4e57835f610e06565b8380fd5b8280fd5b919250506001600160581b03610e6a61228c565b168110610e7a5790838692610dae565b630b306ba760e41b8652600486fd5b630b83cca560e41b8752600487fd5b5060649594929195358610610fc257610eb284869761226b565b917f000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f35676001600160a01b031691823b15610fbe57604051637921219560e11b81523360048201523060248201526044810192909252606482015260a060848201525f60a4820152908590829060c490829084905af1908115610fb3578591610f9e575b5050303b156102bc5760405192631b1fe8df60e31b845233600485015260248401528360448401526064830152346084830152151560a4820152818160c48183305af180156102ad57610f89575b5050610e26565b81610f9391611d67565b61017a57805f610f82565b81610fa891611d67565b6102bc57835f610f34565b6040513d87823e3d90fd5b8680fd5b6370ba43e160e01b8552600485fd5b6001600160581b03610fe161228c565b168314610d9657635e8d8d4560e11b8852600488fd5b8c80fd5b600197506064359350610cdf565b50508c88610cda565b8b90610cc8565b63cbd4014160e01b8952600489fd5b630391dadf60e51b8852600488fd5b50611040612601565b610c0a565b63524f409b60e01b8652600486fd5b639464023560e01b8652600486fd5b5061106c612601565b15610bcf565b503461017a57602036600319011261017a576020611091600435612194565b6001600160401b0360405191168152f35b503461017a578060031936011261017a575f516020615f2e5f395f51905f52546040516001600160a01b039091168152602090f35b503461017a57602036600319011261017a5760043565ffffffffffff811681036101d3578160c060405161110a81611d15565b8281528260208201528260408201528260608201528260808201528260a0820152015265ffffffffffff8110156112305760011b906040519061114c82611d15565b82600601549260018060a01b0384168352602083019360ff8160a01c1685526007604085019261118260ff8460a81c1685612188565b606086019260b01c8352015492608085019261ffff8516845260ff60a087019763ffffffff8760101c16895263ffffffff60c089019760301c1687526040519760018060a01b039051168852511660208701525190600282101561121c57509461ffff63ffffffff94936001600160501b03869460e09960408a01525116606088015251166080860152511660a0840152511660c0820152f35b634e487b7160e01b81526021600452602490fd5b634e487b7160e01b82526032600452602482fd5b503461017a578060031936011261017a575f516020615f8e5f395f51905f525460ff8160401c1615906001600160401b038116801590816113d8575b60011490816113ce575b1590816113c5575b506113b65767ffffffffffffffff1981166001175f516020615f8e5f395f51905f52558161138a575b506112c46139b0565b6112cc6139b0565b6112d533612304565b6112dd6139b0565b6112e56139b0565b81546001600160d01b0316600160d01b178255604051662386f26fc1000081527fe62cb286676010487ba48a94533130ea5590ad3a059c31bdb2878d1a6724659290602090a16113325780f35b68ff0000000000000000195f516020615f8e5f395f51905f5254165f516020615f8e5f395f51905f52557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a180f35b68ffffffffffffffffff191668010000000000000001175f516020615f8e5f395f51905f52555f6112bb565b63f92ee8a960e01b8352600483fd5b9050155f611292565b303b15915061128a565b839150611280565b503461017a57602036600319011261017a576020611091600435612113565b503461017a578060031936011261017a57611418612562565b5f516020615f2e5f395f51905f5280546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461017a57602036600319011261017a57600435816001600160401b03821161017a5761149d6114c0923690600401611de9565b60405163332d573b60e11b815260806004820152938492839260848401916120d3565b60066024830152600560448301526003606483015203817347baa84050b964270e865a5080d90edf9864e9865af49081156102ad578291611516575b6040516020808252819061151290820185611e19565b0390f35b90503d8083833e6115278183611d67565b810190602081830312610e52578051906001600160401b038211610e4e570181601f82011215610e525780519061155d82611eb8565b9361156b6040519586611d67565b82855260208086019360051b83010193841161017a5750602001905b82821061159b57505050611512905f6114fc565b8151815260209182019101611587565b503461017a5760a06115c56115bf36611c87565b91612035565b6080604051916001600160401b0381511683526001600160401b0360208201511660208401526001600160401b03604082015116604084015266ffffffffffffff6060820151166060840152015115156080820152f35b50346118ef5760c03660031901126118ef57611636611cba565b6024359061ffff8216918281036118ef576044359161ffff83168084036118ef576064359161ffff8316918284036118ef576084356001600160401b0381116118ef57611687903690600401611de9565b60a4356001600160401b0381116118ef57366023820112156118ef5780600401356001600160401b0381116118ef5736602460608302840101116118ef576116cd612562565b7347baa84050b964270e865a5080d90edf9864e98693843b156118ef5760405163119ea47b60e31b815260a0600482015260a48101859052936001600160fb1b0381116118ef5760e48594939260249260051b809160c488013785018360c4820160031960c489850301018589015252019201905f905b80821061188e575050507f000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f35676001600160a01b03166044830152600160648301527f0000000000000000000000000000000000000000000000000de0b6b3a764000060848301525f919081900381855af4801561188357611868575b509081899493923b156102b857849260849160405195869485936364a7698d60e01b855260018060a01b03169c8d60048601526024850152604484015260648301525af480156102ad57611853575b50549061ffff60c01b9060c01b169361ffff60c01b19916001600160401b0360c01b1617169061ffff60a01b9060a01b16179061ffff60b01b9060b01b161717815580f35b8161185d91611d67565b6102b857845f61180e565b6118789194939299505f90611d67565b5f979091925f6117bf565b6040513d5f823e3d90fd5b91809450929092356001600160801b0381168091036118ef57815260208401356001600160581b0381168091036118ef57602082015260408401359081151582036118ef576060809160019315156040820152019401920184939291611744565b5f80fd5b346118ef575f3660031901126118ef577f00000000000000000000000045b35e5ba5f5a337fc170d47e1ce2a45954cb1106001600160a01b0316300361194a5760206040515f516020615f4e5f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b346118ef5760203660031901126118ef57611972611fed565b506004355f526001602052606060405f206040519061199082611ce6565b546001600160581b036001600160801b0382169283815260ff60406020830192848660801c168452019360d81c1615158352604051938452511660208301525115156040820152f35b60403660031901126118ef576119ed611cba565b6024356001600160401b0381116118ef57611a0c903690600401611da3565b6001600160a01b037f00000000000000000000000045b35e5ba5f5a337fc170d47e1ce2a45954cb11016308114908115611b84575b5061194a57611a4e612562565b6040516352d1902d60e01b81526001600160a01b0383169290602081600481875afa5f9181611b50575b50611a905783634c9c8ce360e01b5f5260045260245ffd5b805f516020615f4e5f395f51905f52859203611b3e5750813b15611b2c575f516020615f4e5f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115611b14575f8083602061001b95519101845af4611b0e6146a8565b91614773565b505034611b1d57005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d602011611b7c575b81611b6c60209383611d67565b810103126118ef57519085611a78565b3d9150611b5f565b5f516020615f4e5f395f51905f52546001600160a01b03161415905083611a41565b346118ef57611bbd611bb736611c87565b91611f5c565b6040518091602082016020835281518091526020604084019201905f5b818110611be8575050500390f35b825180516001600160a01b031685526020818101516001600160581b03168187015260409182015165ffffffffffff169186019190915286955060609094019390920191600101611bda565b346118ef5760203660031901126118ef576004359063ffffffff60e01b82168092036118ef57602091630271189760e51b8114908115611c76575b5015158152f35b6301ffc9a760e01b14905083611c6f565b60609060031901126118ef5760043560028110156118ef5790602435906044356001600160401b03811681036118ef5790565b600435906001600160a01b03821682036118ef57565b602435906001600160a01b03821682036118ef57565b606081019081106001600160401b03821117611d0157604052565b634e487b7160e01b5f52604160045260245ffd5b60e081019081106001600160401b03821117611d0157604052565b6101e081019081106001600160401b03821117611d0157604052565b60a081019081106001600160401b03821117611d0157604052565b90601f801991011681019081106001600160401b03821117611d0157604052565b6001600160401b038111611d0157601f01601f191660200190565b81601f820112156118ef57803590611dba82611d88565b92611dc86040519485611d67565b828452602083830101116118ef57815f926020809301838601378301015290565b9181601f840112156118ef578235916001600160401b0383116118ef576020808501948460051b0101116118ef57565b90602080835192838152019201905f5b818110611e365750505090565b8251845260209384019390920191600101611e29565b359065ffffffffffff821682036118ef57565b60a4359081151582036118ef57565b6044359081151582036118ef57565b60406003198201126118ef57600435906001600160401b0382116118ef57611ea791600401611de9565b909160243580151581036118ef5790565b6001600160401b038111611d015760051b60200190565b9080601f830112156118ef578135611ee681611eb8565b92611ef46040519485611d67565b81845260208085019260051b8201019283116118ef57602001905b828210611f1c5750505090565b8135815260209182019101611f0f565b9181601f840112156118ef578235916001600160401b0383116118ef5760208085019460c085020101116118ef57565b9190916002811015611fd957611fa45781611fa1925f52600560205260405f206001600160401b0383165f5260205260405f20905f52600360205260405f20906123e9565b90565b81611fa1925f52600460205260405f206001600160401b0383165f5260205260405f20905f52600260205260405f20906123e9565b634e487b7160e01b5f52602160045260245ffd5b60405190611ffa82611ce6565b5f6040838281528260208201520152565b6040519061201882611d4c565b5f6080838281528260208201528260408201528260608201520152565b91909161204061200b565b506002811015611fd9576120bf57612062915f52600360205260405f20612595565b6040519061206f82611d4c565b546001600160401b03811682526001600160401b038160401c1660208301526001600160401b038160801c16604083015266ffffffffffffff8160c01c16606083015260f81c1515608082015290565b612062915f52600260205260405f20612595565b916020908281520191905f5b8181106120ec5750505090565b90919260208060019265ffffffffffff61210588611e4c565b1681520194019291016120df565b5f52600260205260405f206001600160401b038154169081612133575090565b60010191905b6001600160401b0381165f52826020526001600160401b0360405f205460401c1615612184576001600160401b03165f52816020526001600160401b0360405f205460401c16612139565b9150565b6002821015611fd95752565b5f52600360205260405f206001600160401b0381541690816121b4575090565b60010191905b6001600160401b0381165f52826020526001600160401b0360405f205460801c1615612184576001600160401b03165f52816020526001600160401b0360405f205460801c166121ba565b6040516107d0919061fa2061221a8183611d67565b8382526001600160401b03829411611d0157601f190190369060200137565b9061224382611eb8565b6122506040519182611d67565b8281528092612261601f1991611eb8565b0190602036910137565b9190820391821161227857565b634e487b7160e01b5f52601160045260245ffd5b6044356001600160581b03811681036118ef5790565b356001600160581b03811681036118ef5790565b80516001600160a01b039081168352602080830151821690840152604080830151821690840152606080830151909116908301526080908101511515910152565b9190820180921161227857565b6001600160a01b03168015612362575f516020615f2e5f395f51905f5280546001600160a01b0319811683179091556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3565b631e4fbdf760e01b5f525f60045260245ffd5b9060038202918083046003149015171561227857565b8181029291811591840414171561227857565b80548210156123b3575f5260205f2001905f90565b634e487b7160e01b5f52603260045260245ffd5b80518210156123b35760209160051b010190565b5f1981146122785760010190565b9291906123f6828261393b565b1561255a5766ffffffffffffff9161240d91612595565b5460c01c168254612426612421838361226b565b612375565b9061243082611eb8565b9161243e6040519384611d67565b80835261244d601f1991611eb8565b015f5b81811061254357505081945f935b82811061246b5750505052565b612475818361239e565b90549060031b1c5f5b6003811061249057505060010161245e565b61249a818361398b565b65ffffffffffff8160b01c1690816124b7575b505060010161247e565b9091976001600160581b03662386f26fc100008360e01c021665ffffffffffff8410156123b3576001936001600160581b0361253b946601fffffffffffe878060a01b039160af1c166006015416926040519361251385611ce6565b8452166020830152604082015261252a828a6123c7565b5261253581896123c7565b506123db565b96905f6124ad565b60209061254e611fed565b82828701015201612450565b506060925050565b5f516020615f2e5f395f51905f52546001600160a01b0316330361258257565b63118cdaa760e01b5f523360045260245ffd5b61259f828261393b565b156125bd576001600160401b03600192165f520160205260405f2090565b631540107f60e11b5f5260045ffd5b5f516020615f6e5f395f51905f525c6125f25760015f516020615f6e5f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b60843580151581036118ef5790565b3580151581036118ef5790565b65ffffffffffff1665ffffffffffff81146122785760010190565b90917f000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f35676001600160a01b0316803b156118ef57604051637921219560e11b81523060048201526001600160a01b0390931660248401526044830193909352606482015260a060848201525f60a482018190529091829081838160c481015b03925af18015611883576126c75750565b5f6126d191611d67565b565b6126db61200b565b505f54604051906001600160a01b03166126f482611d4c565b6001600160a01b037f000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f3567811683527f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38811660208401527f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad3816604083015260608201527f00000000000000000000000000000000000000000000000000000000000000011515608082015290565b91908110156123b35760051b0190565b3565ffffffffffff811681036118ef5790565b81156127cd570490565b634e487b7160e01b5f52601260045260245ffd5b91925f935f906127f081612239565b946127fa82612239565b9461280483612239565b9061280e84612239565b61281785612239565b955f5b8681106128d85750808a528852604051948060808701608088525260a0860192905f5b8181106128b157505050926128938594936128858487967f492cb7bf47ebe6723b966fc96a5de53bd973fe19292b2e207784921fe5c0a34e996128ac97036020890152611e19565b908582036040870152611e19565b83810360608501526001600160a01b0390911695611e19565b0390a2565b90919360208060019265ffffffffffff6128ca89611e4c565b16815201950192910161283d565b6128eb6128e68289876127a0565b6127b0565b65ffffffffffff8110156123b35760011b6006015460ff8160a81c169c6001600160401b0360ff8360a01c169260b01c169d6002811015611fd9576129dd57908d6129b4849361080061298d6001600160581b036129858f6128e660019b8f92612954936127a0565b885f52600560205260405f20885f5260205260405f20895f5260036020528865ffffffffffff60405f209316614332565b16948561238b565b7f0000000000000000000000000000000000000000000000000de0b6b3a7640000906127c3565b9e5b6129c0848a6123c7565b526129cb838c6123c7565b526129d682866123c7565b520161281a565b9c929081612a57818f8f8796612a51918f612a4b6001600160581b038f8e612a1060019f6128e6908f97612a42956127a0565b90855f52600460205260405f20815f5260205260405f2090865f52600260205265ffffffffffff60405f209316614332565b169889966123c7565b526123c7565b526123db565b946129b6565b92612a9190612a9f936020969360018060a01b0316865260018060a01b03168686015260a0604086015260a0850190611e19565b908382036060850152611e19565b9060808183039101525f81520190565b90917f000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f35676001600160a01b0316803b156118ef576126b6935f809460405196879586948593631759616b60e11b85523060048601612a5d565b90917f000000000000000000000000000000000000000000000000000000000000000115612be65715612bc25760405163aa67c91960e01b81526001600160a01b0391821660048201529160209183916024918391907f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38165af1801561188357612b8e5750565b6020813d602011612bba575b81612ba760209383611d67565b810103126118ef5751801515036118ef57565b3d9150612b9a565b5f80809381935af1612bd26146a8565b506126d1576312171d8360e31b5f5260045ffd5b5060405163a9059cbb60e01b60208201526001600160a01b0390911660248201526044808201929092529081526126d190612c22606482611d67565b7f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad386001600160a01b031661471b565b9060058110156123b35760051b0190565b610400526102e0526102c08190525f61028081905261030081905261026081905261016081905261020052612c9690612239565b61022052612ca66102c051612239565b610240525f610380526102c051612cbc90612239565b6103a052612ccc6102c051612239565b61034052612cd8612205565b6101e052612ce4612205565b6101a052612cf0612205565b610180525f546103e081905260d01c60c05260a06103c0819052604051610360819052612d1d9190611d67565b6103c0516103605136903760405161032052612d3b61032051611d30565b5f60206103205101525f60406103205101525f60606103205101525f60806103205101525f6103c0516103205101525f6101206103205101525f6101406103205101525f6101606103205101525f6101806103205101525f6101a06103205101525f6101c061032051015260018060a01b03610400511661032051525f1960c06103205101525f60e061032051015261ffff6103e05160b01c166101006103205101525f60a0525b6102c05160a05110156137ce57602060c060a051026102e0510101355f5260016020526001600160801b0360405f2054166101c0525f6102a0525f6102a0525f5f6001600160581b03612e42606060c060a051026102e05101016122a2565b16156137bf57662386f26fc100006001600160581b03612e6e606060c060a051026102e05101016122a2565b16066137b0576001600160401b03612e92604060c060a051026102e05101016146d7565b16156137a157602060c060a051026102e0510101355f52600160205260ff60405f205460d81c1615613792576001600160401b03612edc604060c060a051026102e05101016146d7565b166101c051156127cd576101c05190066001600160801b031661377c5760018060a01b036103205151167f7c373f9adf6b75cb1728b2b96d2f541ee8ecc1f34a603794af55c3311636b103602060405165ffffffffffff60c051168152a2600260c060a051026102e0510135101561012052610120516118ef57612f7160c060a051026102e051013560206103205101612188565b602060c060a051026102e05101013560406103205101526001600160401b03612fa6604060c060a051026102e05101016146d7565b16606061032051015265ffffffffffff60c0511660806103205101526001600160581b03612fe0606060c060a051026102e05101016122a2565b166103c0516103205101525f6101206103205101525f6101406103205101525f6101606103205101525f6101806103205101525f6101a06103205101525f6101c061032051015261303f610180516101a0516101e051610320516139db565b6101606103205101516101405261018061032051015160e05261014061032051015161014051613752575b613092906001600160581b0361308c606060c060a051026102e05101016122a2565b1661226b565b90602060c060a051026102e0510101355f5260016020526001600160581b0360405f205460801c168210155f146136af5750806102a05260018060a01b03610320515116610120516118ef576130f4604060c060a051026102e05101016146d7565b916001600160581b03613113606060c060a051026102e05101016122a2565b16610100528263ffffffff662386f26fc1000083041161368e5763ffffffff662386f26fc10000830416935f6101205260c060a051026102e0510135155f1461363c575060a0516102e051602060c0909202018101355f908152600582526040808220600390935290206101c0519091600f9190910b906f7fffffffffffffffffffffffffffffff198214612278576131b49387925f039360c0519261529e565b925b61ffff5f546103c0511c16906040516131ce81611d15565b8481526020810160ff602060c060a051026102e051010135168152604082019261320360c060a051026102e051013585612188565b6001600160401b0388166060840152846080840152806103c05184015260c083015265ffffffffffff60c05110156123b357815160c05160011b60060180546001600160a01b039092166001600160a01b03199092169190911790819055905192519092906002811015611fd957613315936001600160501b0360b01b606085015160b01b169260ff60a01b906103c0511b169060018060a01b0316179060ff60a81b9060a81b16171760c05160011b6006015563ffffffff60c06007815160011b019261ffff60808201511684549065ffffffff00006103c05184015160101b169165ffffffffffff19161717845501511663ffffffff60301b82549160301b169063ffffffff60301b1916179055565b5f610120526040519165ffffffffffff60c0511683526001600160401b038516602084015260408301526101005160608301526080820152602060c060a051026102e051010135917f39bcecdfb7e71a8c70cee1d2349ccf3e9f853bfdfe62c1a7939ea4971b2f2e6d60c060a051026102e0510135926103c05190a4806133aa6103c05160c060a051026102e0510101612610565b6135ce575b505b6133bc60c05161261d565b60c052610120516118ef575f6101205260c060a051026102e0510135155f1461350657613419907f0000000000000000000000000000000000000000000000000de0b6b3a7640000906001600160401b036102a0519116026127c3565b610140510161030051016103005261014051613440575b505b600160a0510160a052612de3565b6134759061347060e051916134706102a0516001600160581b0361308c606060c060a051026102e05101016122a2565b61226b565b602060c060a051026102e051010135613494610380516103a0516123c7565b52610380516080526134a8610380516123db565b610380526134bb608051610340516123c7565b5260a0516102e05160c09190910201602001355f198101908111612278576134ff6134f560e0516134ef8461036051612c51565b516122f7565b9161036051612c51565b525f613430565b50806001600160581b03613526606060c060a051026102e05101016122a2565b1603613565575b5061354961354060e0516101405161226b565b610260516122f7565b6102605261355c60e051610280516122f7565b61028052613432565b6135a790602060c060a051026102e05101013561358861020051610220516123c7565b526001600160581b0361308c606060c060a051026102e05101016122a2565b6135c7610200516135ba610200516123db565b61020052610240516123c7565b525f61352d565b6001600160401b036135ec604060c060a051026102e05101016146d7565b166001600160401b0382161461360e604060c060a051026102e05101016146d7565b901561361a57506133af565b906001600160401b03809263d25073c160e01b5f52166004521660245260445ffd5b6136889150602060c060a051026102e0510101355f5260046020528460405f20602060c060a051026102e0510101355f52600260205260405f20926101c051600f0b9360c0519261529e565b926131b6565b662386f26fc10000826306dfcc6560e41b5f5260206004520460245260445ffd5b90806136bc575b506133b1565b9150506136d5604060c060a051026102e05101016146d7565b61032051515f610120526040805160c0805165ffffffffffff1682526001600160401b03851660208084019190915292820186905260a0516102e05191020191820135929135916001600160a01b0316907fe0c590fd7544972fc237bcd202330c7f935257be2b2e2b32e6c07698228ba90290606090a45f6136b6565b613768608060c060a051026102e0510101612610565b1561306a576304118ad560e31b5f5260045ffd5b631d9b7a6960e21b5f526101c05160045260245ffd5b63cbd4014160e01b5f5260045ffd5b637294708f60e11b5f5260045ffd5b63524f409b60e01b5f5260045ffd5b639464023560e01b5f5260045ffd5b5f805460c0516001600160d01b0390911660d09190911b6001600160d01b031916179055610200516138a4575b61038051613879575b610160515b600581106138145750565b6138218161036051612c51565b5190811561387057600181018082116138565761016051546001936138509290916001600160a01b0316612638565b01613809565b634e487b7160e01b61016051526011600452602461016051fd5b60019150613850565b610380516103a0515261038051610340515261389f610340516103a05161040051612aaf565b613804565b610200805161022051525161024051527f000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f35676001600160a01b0316803b156118ef575f6040518092631759616b60e11b82528183816139116102405161022051306104005160048601612a5d565b03925af1801561188357613926575b506137fb565b5f61393091611d67565b5f610160525f613920565b906001600160401b0316801515918261395357505090565b80546001600160401b03168214925090821561396e57505090565b600192505f52016020526001600160401b0360405f205416151590565b90605081029080820460501490151715612278571c60b01b6001600160b01b03191690565b60ff5f516020615f8e5f395f51905f525460401c16156139cc57565b631afcd79f60e31b5f5260045ffd5b93909291936104205260206104205101516002811015611fd957613f0c5791926107d084526107d081526107d082525b613a17610420516147d1565b80613efa575b15613e1a5760406104209493945101515f52600260205260405f2060406104205101515f52600460205260405f206001600160401b03610120610420510151165f5260205260405f20936001600160401b038061012061042051015116165f526001820160205260405f20945f965f935f9061ffff610100610420510151169366ffffffffffffff81549a5460c01c169687935b8b891080613e08575b15613c82575050869a939a90613ad0888261239e565b90549060031b1c9b5f5b6003811080613c70575b15613c61576107d06101a06104205101511015613c52576050810281810460501482151715612278578e901c15613c035765ffffffffffff613b278f839061398b565b60b01c169d8e15613bb85790613b50613b488a83613bb09561042051615359565b92919a6122f7565b9f613b636101a06104205101518d6123c7565b52613b778d6101a0610420510151906123c7565b528c612a516001600160401b0361012061042051015116916101a061042051015190613ba2826123db565b6101a06104205101526123c7565b9c959c613ada565b909d5095898603613bf4576002613bce8861532f565b14613be557613bdf613bb0916123db565b9d6123db565b6354bf4b4160e11b5f5260045ffd5b634f37cd8f60e11b5f5260045ffd5b919c92989092915f198d018d811161227857821015613c2b576354bf4b4160e11b5f5260045ffd5b15613c4357613c39906123db565b979b91949b613ab1565b636743d7e360e01b5f5260045ffd5b63c869067960e01b5f5260045ffd5b509197613c39909c919c6123db565b50613c7d610420516147d1565b613ae4565b93955095999093979a9196506001600160401b0361012061042051015116956003613caf818504886122f7565b930690848403613dd15790613cc391615cbb565b9081613d72575050506001810180911161227857915b805b838110613d4c57508203613d0b575b541115613cfb575b50509192613a0b565b613d0491614925565b5f80613cf2565b6001600160401b0383165f9081526001850160205260409020805466ffffffffffffff60c01b191660c084901b66ffffffffffffff60c01b16179055613cea565b80613d6c613d5c6001938661239e565b8154905f199060031b1b19169055565b01613cdb565b613d7f829694939661532f565b60028114613be557600310613dba575b50613d9d613db5928561239e565b90919082549060031b91821b915f19901b1916179055565b613cd9565b5f198101908111612278578203613be5575f613d8f565b509194929050600181018091116122785784149081613dff575b50613cd9576330590ff960e11b5f5260045ffd5b9050155f613deb565b50613e15610420516147d1565b613aba565b909291926101a061042051015180613e33575b50505050565b808452808352815260018060a01b036104205151169065ffffffffffff6080610420510151169260406104205101519460405192606084016060855282518091526020608086019301905f5b818110613edc575050508392613ec283613ed093867f09a6cb3f5fc8c9d590bf15e926d32bc3e88a0034ed1e8e11bd026c4ab48deed49896036020870152611e19565b908382036040850152611e19565b0390a45f808080613e2d565b825165ffffffffffff16855260209485019490920191600101613e7f565b50613f0761042051614811565b613a1d565b91926107d084526107d081526107d082525b613f2a610420516147d1565b80614320575b1561425b5760406104209493945101515f52600360205260405f2060406104205101515f52600560205260405f206001600160401b03610120610420510151165f5260205260405f20936001600160401b038061012061042051015116165f526001820160205260405f20945f965f935f9061ffff610100610420510151169366ffffffffffffff81549a5460c01c169687935b8b891080614249575b156140eb575050869a939a90613fe3888261239e565b90549060031b1c9b5f5b60038110806140d9575b156140ca576107d06101a06104205101511015613c52576050810281810460501482151715612278578e901c1561408a5765ffffffffffff61403a8f839061398b565b60b01c169d8e156140635790613b50613b488a8361405b9561042051615359565b9c959c613fed565b909d5095898603613bf45760026140798861532f565b14613be557613bdf61405b916123db565b919c92989092915f198d018d8111612278578210156140b2576354bf4b4160e11b5f5260045ffd5b15613c43576140c0906123db565b979b91949b613fc4565b5091976140c0909c919c6123db565b506140e6610420516147d1565b613ff7565b93955095999093979a9196506001600160401b0361012061042051015116956003614118818504886122f7565b930690848403614212579061412c91615cbb565b90816141cb575050506001810180911161227857915b805b8381106141b557508203614174575b541115614164575b50509192613f1e565b61416d91614925565b5f8061415b565b6001600160401b0383165f9081526001850160205260409020805466ffffffffffffff60c01b191660c084901b66ffffffffffffff60c01b16179055614153565b806141c5613d5c6001938661239e565b01614144565b6141d8829694939661532f565b60028114613be5576003106141fb575b50613d9d6141f6928561239e565b614142565b5f198101908111612278578203613be5575f6141e8565b509194929050600181018091116122785784149081614240575b50614142576330590ff960e11b5f5260045ffd5b9050155f61422c565b50614256610420516147d1565b613fcd565b909291926101a0610420510151806142735750505050565b808452808352815260018060a01b036104205151169065ffffffffffff6080610420510151169260406104205101519460405192606084016060855282518091526020608086019301905f5b818110614302575050508392613ec283613ed093867f09a6cb3f5fc8c9d590bf15e926d32bc3e88a0034ed1e8e11bd026c4ab48deed49896036020870152611e19565b825165ffffffffffff168552602094850194909201916001016142bf565b5061432d61042051614811565b613f30565b9091939266ffffffffffffff6143488483612595565b5460c01c169285549360405194638955cf2160e01b865287600487015281602487015260448601528360648601526040856084817347baa84050b964270e865a5080d90edf9864e9865af4968715611883575f955f9861466d575b505f19861461465a576001600160581b03662386f26fc100006143d68a6143ca8a8661239e565b90549060031b1c61398b565b60e01c02169586986143e8828461239e565b90549060031b1c916143fa828461398b565b65ffffffffffff808260b01c1610156123b3576601fffffffffffe60af9190911c1660060154336001600160a01b039091160361464b578354925f198401848111612278578361444c918414926148af565b1581614643575b50156144f257505050614465816146eb565b54146144e2575b50505b65ffffffffffff80821610156123b357662386f26fc100006001600160581b0360076601fffffffffffe63ffffffff9460011b16019316041663ffffffff825460301c160363ffffffff811161227857815469ffffffff000000000000191660309190911b63ffffffff60301b16179055565b6144eb91614925565b5f8061446c565b9092945061450691955061450b9350612375565b6122f7565b91600383049261451e6003820692612375565b5f19810191908211612278575b818110614571575b50508061454a575061454591506146eb565b61446f565b8261456b613d9d9261455f614545968661239e565b90549060031b1c6148af565b9261239e565b60018101945091508382116122785760038085049406918285614594818761239e565b90549060031b1c91600384049260038506916145b0858a61239e565b90549060031b1c916145c2828261398b565b946001600160b01b0319861615614601575050506145f46145fb93836145ef6001989795613d9d956148af565b615581565b918861239e565b0161452b565b95985095509550509650508454905f1982019182116122785703613be5576050808302908382041483151715612278571c613be55715613c4357915f80614533565b90505f614453565b63b331e42160e01b5f5260045ffd5b846313a42eb760e21b5f5260045260245ffd5b955096506040853d6040116146a0575b8161468a60409383611d67565b810103126118ef5760208551950151965f6143a3565b3d915061467d565b3d156146d2573d906146b982611d88565b916146c76040519384611d67565b82523d5f602084013e565b606090565b356001600160401b03811681036118ef5790565b80548015614707575f190190614704613d5c838361239e565b55565b634e487b7160e01b5f52603160045260245ffd5b905f602091828151910182855af115611883575f513d61476a57506001600160a01b0381163b155b61474a5750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415614743565b90614797575080511561478857805190602001fd5b63d6bda27560e01b5f5260045ffd5b815115806147c8575b6147a8575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156147a0565b6101c081015161480c5760e0810151156147f45760c06101608201519101511190565b6001600160581b0360a0610140830151920151161190565b505f90565b60208101516002811015611fd957600114908115614895576001600160401b0361483e6040830151612194565b1691821561488e5715614871576001600160401b03606082015116821061486b57610120905b0152600190565b50505f90565b6001600160401b03606082015116821161486b5761012090614864565b5050505f90565b6001600160401b036148aa6040830151612113565b61483e565b906001600160501b0360508202918083046050149015171561227857901b191690565b805467ffffffffffffffff60801b191660809290921b67ffffffffffffffff60801b16919091179055565b9067ffffffffffffffff60401b82549160401b169067ffffffffffffffff60401b1916179055565b6001600160401b03821690811561528f57614940838261393b565b156125bd576001810192825f52836020526001600160401b0360405f205460401c16158015615270575b156152065780925b6001600160401b0384165f52846020526001600160401b0360405f205460401c1615155f146151df576001600160401b0384165f52846020526001600160401b0360405f205460401c16915b6001600160401b038581165f908152602088905260408082205486841683529120805467ffffffffffffffff19169190921690811790915580156151bf576001600160401b03908181165f52876020528160405f205460401c16828816145f146151a657165f5285602052614a368360405f206148fd565b6001600160401b0385165f528560205260405f205460f81c1591806001600160401b03871603614ff5575b5050614a8c575b50506001600160401b03165f5260205260405f206001600160401b03198154169055565b939091935b6001600160401b03835416906001600160401b0381169182141580614fdf575b15614fae5750805f52836020526001600160401b0360405f205416906001600160401b0382165f52846020526001600160401b0360405f205460401c16145f14614d5b576001600160401b0381165f52836020526001600160401b0360405f205460801c166001600160401b0381165f528460205260405f205460f81c614cee575b6001600160401b038181165f9081526020879052604080822054811c9092168152205460f81c1580614cc0575b15614b96576001600160401b03165f90815260208590526040902080546001600160f81b0316600160f81b179055935b93614a91565b90614c3a916001600160401b0381165f52856020526001600160401b038060405f205460801c16165f528560205260405f205460f81c15614c4b575b6001600160401b038281165f908152602088905260408082208054948416835281832080546001600160f81b031960f897881c151590971b969096166001600160f81b03968716178155815486169091555460801c9092168152208054909116905583615e04565b6001600160401b0382541693614b90565b6001600160401b038082165f818152602089905260408082208054821c9094168252812080546001600160f81b03908116909155919052815416600160f81b179055614c979085615ce0565b6001600160401b0381165f52846020526001600160401b038060405f205460801c169050614bd2565b506001600160401b038181165f908152602087905260408082205460801c9092168152205460f81c15614b60565b6001600160401b039081165f9081526020869052604080822080546001600160f81b03908116909155928416825290208054909116600160f81b179055614d358184615e04565b6001600160401b0381165f52836020526001600160401b0360405f205460801c16614b33565b6001600160401b0381165f52836020526001600160401b0360405f205460401c166001600160401b0381165f528460205260405f205460f81c614f41575b6001600160401b038181165f908152602087905260408082205460801c9092168152205460f81c1580614f14575b15614dfb576001600160401b03165f90815260208590526040902080546001600160f81b0316600160f81b17905593614b90565b90614c3a916001600160401b0381165f52856020526001600160401b038060405f205460401c16165f528560205260405f205460f81c15614e9e575b6001600160401b038281165f908152602088905260408082208054948416835281832080546001600160f81b031960f897881c151590971b969096166001600160f81b039687161781558154861690915554811c9092168152208054909116905583615ce0565b6001600160401b038082165f81815260208990526040808220805460801c9094168252812080546001600160f81b03908116909155919052815416600160f81b179055614eeb9085615e04565b6001600160401b0381165f52846020526001600160401b038060405f205460401c169050614e37565b506001600160401b038181165f9081526020879052604080822054811c9092168152205460f81c15614dc7565b6001600160401b039081165f9081526020869052604080822080546001600160f81b03908116909155928416825290208054909116600160f81b179055614f888184615ce0565b6001600160401b0381165f52836020526001600160401b0360405f205460401c16614d99565b6001600160401b039081165f90815260208690526040812080546001600160f81b0316905592959350919050614a68565b50815f528460205260405f205460f81c15614ab1565b9461514d919295805f52876020526001600160401b0360405f2054166001600160401b0383165f528860205260405f206001600160401b0382166001600160401b031982541617905580155f146151555750855467ffffffffffffffff19166001600160401b0383161786555b805f52876020526150966001600160401b0360405f205460401c166001600160401b0384165f528960205260405f206148fd565b6001600160401b038281165f81815260208b905260408082208054821c85168352818320805467ffffffffffffffff19168517905585835290822054929091526150e99260809290921c909116906148d2565b6001600160401b039182165f81815260208a90526040808220805460801c9095168252808220805467ffffffffffffffff19168417905592815291822054915281546001600160f81b031660f891821c151590911b6001600160f81b031916179055565b925f80614a61565b6001600160401b03908181165f52896020528160405f205460401c1683145f1461519257165f528760205261518d8260405f206148fd565b615062565b165f528760205261518d8260405f206148d2565b165f52856020526151ba8360405f206148d2565b614a36565b50835467ffffffffffffffff19166001600160401b038416178455614a36565b6001600160401b0384165f52846020526001600160401b0360405f205460801c16916149be565b825f52836020526001600160401b0360405f205460801c165b6001600160401b0381165f52846020526001600160401b0360405f205460401c161561526a576001600160401b03165f52836020526001600160401b0360405f205460401c1661521f565b92614972565b50825f52836020526001600160401b0360405f205460801c161561496a565b63d77534c760e01b5f5260045ffd5b95939291949561ffff5f5460c01c16955b6152bb8782848661559e565b61530c576001600160401b03889116600f0b016001600160801b0381166001600160401b0381116152f557506001600160401b03166152af565b6306dfcc6560e41b5f52604060045260245260445ffd5b9550611fa19496509085916001600160401b0383165f5260205260405f20615b16565b6001600160501b038080808416161581808560501c16161560011b179260a01c16161560021b1790565b5f9391615366848261398b565b60e0838101519082901c662386f26fc10000026001600160581b0316959190156155165761012084016153a36001600160401b038251168861238b565b6153ce7f0000000000000000000000000000000000000000000000000de0b6b3a764000080926127c3565b6153e260c08801516101608901519061226b565b8091115f1461550657916001600160401b0361541161541a93662386f26fc100009560016101c08c015261238b565b915116906127c3565b04662386f26fc10000810290808204662386f26fc1000014901517156122785780156154f7578261546761546d9594936001600160581b03615460856145ef969c61226b565b1690615c8e565b936148af565b915b610140820161547f8582516122f7565b905261549c61298d6001600160401b03610120850151168661238b565b61016083016154ac8282516122f7565b905260208301516002811015611fd9576001036154df576127106154da9261018092020492019182516122f7565b905292565b506101806127106154da9286020492019182516122f7565b5050509350505050905f905f90565b505050505091935060019361546f565b9061553a6001600160581b0360a0869896999597990151166101408801519061226b565b9184831061554f57505050509160019361546f565b816154676145ef926001600160581b0361546087615572999d9c9a9b989b61226b565b919260016101c083015261546f565b916050820291808304605014901517156122785760b01c901b1790565b9290926155ab838261393b565b15615646576001906001600160401b0384165f520160205261ffff6155f96124216001600160401b0366ffffffffffffff60405f205460c01c16951694855f528660205260405f205461226b565b91161191821561560857505090565b5f9182526020526040902080549091505f1981019081116122785761562c9161239e565b90546001600160b01b031960039290921b1c60101b161590565b9250506001600160401b03811692831561528f5782546001600160401b03165f5b6001600160401b0382169081156156d1575081818710156156b0576001600160401b039150165f52600184016020526001600160401b0360405f205460401c16915b9190615667565b505f52600184016020526001600160401b0360405f205460801c16916156a9565b95915050929190926001830194815f52856020526157bd66ffffffffffffff60405f205460c01c16918361579c66ffffffffffffff6001600160401b036040519461571b86611d4c565b16958685526157766001600160401b038d61576e8260208a015f815260408b01935f855260608c0197885260808c019a60018c525f52602052818060405f209c51161682198c5416178b555116896148fd565b5116866148d2565b51845466ffffffffffffff60c01b1916911660c01b66ffffffffffffff60c01b16178355565b5181546001600160f81b031690151560f81b6001600160f81b031916179055565b80615ae25750825467ffffffffffffffff19161782555b905b6001600160401b038154166001600160401b0383169081141580615abc575b15615a8f575f81815260208690526040808220546001600160401b039081168084528284205482168452928290205492939290911c16820361596757506001600160401b038181165f9081526020879052604080822054831682528082205460801c9092168082529190205490939060f81c156158c657506001600160401b039081165f8181526020879052604080822080546001600160f81b03908116825596851683528183208054881690558054851683529082208054909616600160f81b17909555529154909116906157d6565b92506001600160401b0381165f52846020526001600160401b0360405f205460801c166001600160401b03841614615955575b506001600160401b038281165f9081526020869052604080822054831680835281832080546001600160f81b03818116835590861685529284208054909316600160f81b1790925590915254615950911682615ce0565b6157d6565b91506159618282615e04565b5f6158f9565b6001600160401b038281165f90815260208890526040808220548316825280822054811c909216808252919020549094919060f81c156159fc5750506001600160401b039081165f8181526020879052604080822080546001600160f81b03908116825596851683528183208054881690558054851683529082208054909616600160f81b17909555529154909116906157d6565b9093506001600160401b0382165f52856020526001600160401b0360405f205460401c1614615a7d575b506001600160401b038281165f9081526020869052604080822054831680835281832080546001600160f81b03818116835590861685529284208054909316600160f81b1790925590915254615950911682615e04565b9150615a898282615ce0565b5f615a26565b50546001600160401b03165f90815260209390935250604090912080546001600160f81b03169055600190565b505f81815260208690526040808220546001600160401b0316825290205460f81c6157f5565b8091105f14615b03575f5283602052615afe8160405f206148fd565b6157d4565b5f5283602052615afe8160405f206148d2565b939184549182615b57575b505050615b2d91615f05565b60b01c81549168010000000000000000831015611d015782613d9d9160016126d19501815561239e565b5f1983019183831161227857615b6c91612595565b9166ffffffffffffff835460c01c1690818310155f14615c6d575050615b92818661239e565b90549060031b1c5f6050905b60038110615bed575050615bb19061532f565b60028114613be55715918215615bd6575b505015613be557615b2d915b915f80615b21565b5460c01c66ffffffffffffff161490505f80615bc2565b8181028181048314821517156122785783901c15615c0d57600101615b9e565b96959193908795939515613c43575060b084901b6001600160b01b03191615615c4e575b50916126d195615c4861456b93613d9d9695615f05565b91615581565b549093929060c01c66ffffffffffffff168303613be55791925f615c31565b9150915003615c7f57615b2d91615bce565b63222570bf60e21b5f5260045ffd5b65ffffffffffff63ffffffff662386f26fc100006001600160581b03611fa1951604169160b01c16615f05565b8115615cdb5760508202918083046050149015171561227857811c901b90565b905090565b6001600160401b038083165f8181526001840160208190526040808320805480831c87168086529285205495909452909691959193919285169160801c851690615d2b9082906148fd565b80615de7575b508386165f528460205260405f20848216851982541617905580155f14615d9a575082851683198254161790555b8184165f5282602052615d758160405f206148d2565b165f526020526001600160401b0360405f2091166001600160401b0319825416179055565b8391508181165f52846020528160405f205460801c16828416145f14615dd357165f5282602052615dce8460405f206148d2565b615d5f565b165f5282602052615dce8460405f206148fd565b84165f528460205260405f2084841685198254161790555f615d31565b6001600160401b038083165f81815260018401602081905260408083208054608081901c87168086528386205496909552939792969294929386169290911c851690615e519082906148d2565b80615ee8575b508386165f528460205260405f20848216851982541617905580155f14615e9b575082851683198254161790555b8184165f5282602052615d758160405f206148fd565b8391508181165f52846020528160405f205460401c16828416145f14615ed457165f5282602052615ecf8460405f206148fd565b615e85565b165f5282602052615ecf8460405f206148d2565b84165f528460205260405f2084841685198254161790555f615e57565b65ffffffffffff1660309190911b63ffffffff60301b161760b01b6001600160b01b0319169056fe9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00a2646970667358221220e40a5e49865076890d8a3ec89090b7ada300c212bf7019cdf43d515f5f352ca064736f6c634300081e0033

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

000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f3567000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38

-----Decoded View---------------
Arg [0] : nft (address): 0xE1401171219FD2fD37c8C04a8A753B07706F3567
Arg [1] : quoteToken (address): 0x039e2fB66102314Ce7b64Ce5Ce3E5183bc94aD38
Arg [2] : wS (address): 0x039e2fB66102314Ce7b64Ce5Ce3E5183bc94aD38

-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 000000000000000000000000e1401171219fd2fd37c8c04a8a753b07706f3567
Arg [1] : 000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38
Arg [2] : 000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38


Block Transaction Gas Used Reward
view all blocks ##produced##

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

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