FTM Price: $0.67 (-6.75%)
Gas: 25 GWei

Contract

0x450D81f80D0f29Ba8F12Ea6d291Cc3A52cBF9718
 

Overview

FTM Balance

Fantom LogoFantom LogoFantom Logo0 FTM

FTM Value

$0.00

Sponsored

Transaction Hash
Method
Block
From
To
Value
0x60806040669660462023-08-14 4:59:58246 days ago1691989198IN
 Create: OrderBook
0 FTM0.3847045380.9029177

Latest 1 internal transaction

Parent Txn Hash Block From To Value
669660462023-08-14 4:59:58246 days ago1691989198  Contract Creation0 FTM
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
OrderBook

Compiler Version
v0.8.10+commit.fc410830

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 23 : OrderBook.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../libraries/LibSubAccount.sol";
import "../libraries/LibMath.sol";
import "../libraries/LibOrderBook.sol";
import "../interfaces/IReferralManager.sol";
import "../interfaces/ILiquidityCallback.sol";
import "./Types.sol";
import "./Admin.sol";

contract OrderBook is Storage, Admin, ReentrancyGuardUpgradeable {
    using LibSubAccount for bytes32;
    using SafeERC20Upgradeable for IERC20Upgradeable;
    using LibOrder for LibOrder.OrderList;
    using LibOrder for bytes32[3];
    using LibOrder for PositionOrder;
    using LibOrder for LiquidityOrder;
    using LibOrder for WithdrawalOrder;
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;

    // do not forget to update LibOrderBook if this line updates
    event NewPositionOrder(
        bytes32 indexed subAccountId,
        uint64 indexed orderId,
        uint96 collateral, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline // 1e0. 0 if market order. > 0 if limit order
    );
    // do not forget to update LibOrderBook if this line updates
    event NewLiquidityOrder(
        address indexed account,
        uint64 indexed orderId,
        uint8 assetId,
        uint96 rawAmount, // erc20.decimals
        bool isAdding
    );
    event NewWithdrawalOrder(
        bytes32 indexed subAccountId,
        uint64 indexed orderId,
        uint96 rawAmount, // erc20.decimals
        uint8 profitTokenId,
        bool isProfit
    );
    event NewRebalanceOrder(
        address indexed rebalancer,
        uint64 indexed orderId,
        uint8 tokenId0,
        uint8 tokenId1,
        uint96 rawAmount0,
        uint96 maxRawAmount1,
        bytes32 userData
    );
    event FillOrder(uint64 orderId, OrderType orderType, bytes32[3] orderData);
    // do not forget to update LibOrderBook if this line updates
    event CancelOrder(uint64 orderId, OrderType orderType, bytes32[3] orderData);
    // do not forget to update LibOrderBook if this line updates
    event NewPositionOrderExtra(
        bytes32 indexed subAccountId,
        uint64 indexed orderId,
        uint96 collateral, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline, // 1e0. 0 if market order. > 0 if limit order
        PositionOrderExtra extra
    );

    function initialize(address pool, address mlp, address weth, address nativeUnwrapper) external initializer {
        __SafeOwnable_init();

        _storage.pool = ILiquidityPool(pool);
        _storage.mlp = IERC20Upgradeable(mlp);
        _storage.weth = IWETH(weth);
        _storage.nativeUnwrapper = INativeUnwrapper(nativeUnwrapper);
        _storage.maintainer = owner();
    }

    function getOrderCount() external view returns (uint256) {
        return _storage.orders.length();
    }

    /**
     * @notice Get an Order by orderId.
     */
    function getOrder(uint64 orderId) external view returns (bytes32[3] memory, bool) {
        return (_storage.orders.get(orderId), _storage.orders.contains(orderId));
    }

    function getOrders(
        uint256 begin,
        uint256 end
    ) external view returns (bytes32[3][] memory orderArray, uint256 totalCount) {
        totalCount = _storage.orders.length();
        if (begin >= end || begin >= totalCount) {
            return (orderArray, totalCount);
        }
        end = end <= totalCount ? end : totalCount;
        uint256 size = end - begin;
        orderArray = new bytes32[3][](size);
        for (uint256 i = 0; i < size; i++) {
            orderArray[i] = _storage.orders.at(i + begin);
        }
    }

    /**
     * @notice Open/close position. called by Trader.
     *
     *         Market order will expire after marketOrderTimeout seconds.
     *         Limit/Trigger order will expire after deadline.
     * @param  subAccountId       sub account id. see LibSubAccount.decodeSubAccountId.
     * @param  collateralAmount   deposit collateral before open; or withdraw collateral after close. decimals = erc20.decimals.
     * @param  size               position size. decimals = 18.
     * @param  price              limit price. decimals = 18.
     * @param  profitTokenId      specify the profitable asset.id when closing a position and making a profit.
     *                            take no effect when opening a position or loss.
     * @param  flags              a bitset of LibOrder.POSITION_*.
     *                            POSITION_OPEN                     this flag means openPosition; otherwise closePosition
     *                            POSITION_MARKET_ORDER             this flag means ignore limitPrice
     *                            POSITION_WITHDRAW_ALL_IF_EMPTY    this flag means auto withdraw all collateral if position.size == 0
     *                            POSITION_TRIGGER_ORDER            this flag means this is a trigger order (ex: stop-loss order). otherwise this is a limit order (ex: take-profit order)
     *                            POSITION_TPSL_STRATEGY            for open-position-order, this flag auto place take-profit and stop-loss orders when open-position-order fills.
     *                                                              for close-position-order, this flag means ignore limitPrice and profitTokenId, and use extra.tpPrice, extra.slPrice, extra.tpslProfitTokenId instead.
     * @param  deadline           a unix timestamp after which the limit/trigger order MUST NOT be filled. fill 0 for market order.
     * @param  referralCode       set referral code of the trading account.
     * @param  extra              more strategy like tp/sl.
     */
    function placePositionOrder3(
        bytes32 subAccountId,
        uint96 collateralAmount, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline, // 1e0
        bytes32 referralCode,
        PositionOrderExtra memory extra
    ) public payable nonReentrant {
        address msgSender = _msgSender();
        address accountOwner = subAccountId.getSubAccountOwner();
        if (_storage.aggregators[msgSender]) {
            // we trust aggregator
        } else {
            // otherwise only account owner can place order
            require(accountOwner == msgSender, "SND"); // SeNDer is not authorized
        }
        if (referralCode != bytes32(0) && _storage.referralManager != address(0)) {
            IReferralManager(_storage.referralManager).setReferrerCodeFor(accountOwner, referralCode);
        }
        LibOrderBook.placePositionOrder(
            _storage,
            _blockTimestamp(),
            subAccountId,
            collateralAmount,
            size,
            price,
            profitTokenId,
            flags,
            deadline,
            extra
        );
    }

    /**
     * @notice Add/remove liquidity. called by Liquidity Provider.
     *
     *         Can be filled after liquidityLockPeriod seconds.
     * @param  assetId   asset.id that added/removed to.
     * @param  rawAmount asset token amount. decimals = erc20.decimals.
     * @param  isAdding  true for add liquidity, false for remove liquidity.
     */
    function placeLiquidityOrder(
        uint8 assetId,
        uint96 rawAmount, // erc20.decimals
        bool isAdding
    ) external payable nonReentrant {
        address account = _msgSender();
        LibOrderBook.placeLiquidityOrder(_storage, _blockTimestamp(), account, assetId, rawAmount, isAdding);
    }

    /**
     * @notice Withdraw collateral/profit. called by Trader.
     *
     *         This order will expire after marketOrderTimeout seconds.
     * @param  subAccountId       sub account id. see LibSubAccount.decodeSubAccountId.
     * @param  rawAmount          collateral or profit asset amount. decimals = erc20.decimals.
     * @param  profitTokenId      specify the profitable asset.id.
     * @param  isProfit           true for withdraw profit. false for withdraw collateral.
     */
    function placeWithdrawalOrder(
        bytes32 subAccountId,
        uint96 rawAmount, // erc20.decimals
        uint8 profitTokenId,
        bool isProfit
    ) external nonReentrant {
        address trader = subAccountId.getSubAccountOwner();
        require(trader == _msgSender(), "SND"); // SeNDer is not authorized
        require(rawAmount != 0, "A=0"); // Amount Is Zero

        uint64 orderId = _storage.nextOrderId++;
        bytes32[3] memory data = LibOrder.encodeWithdrawalOrder(
            orderId,
            subAccountId,
            rawAmount,
            profitTokenId,
            isProfit,
            _blockTimestamp()
        );
        _storage.orders.add(orderId, data);

        emit NewWithdrawalOrder(subAccountId, orderId, rawAmount, profitTokenId, isProfit);
    }

    /**
     * @notice Rebalance pool liquidity. Swap token 0 for token 1.
     *
     *         msg.sender must implement IMuxRebalancerCallback.
     * @param  tokenId0      asset.id to be swapped out of the pool.
     * @param  tokenId1      asset.id to be swapped into the pool.
     * @param  rawAmount0    token 0 amount. decimals = erc20.decimals.
     * @param  maxRawAmount1 max token 1 that rebalancer is willing to pay. decimals = erc20.decimals.
     * @param  userData      any user defined data.
     */
    function placeRebalanceOrder(
        uint8 tokenId0,
        uint8 tokenId1,
        uint96 rawAmount0, // erc20.decimals
        uint96 maxRawAmount1, // erc20.decimals
        bytes32 userData
    ) external onlyRebalancer nonReentrant {
        require(rawAmount0 != 0, "A=0"); // Amount Is Zero
        address rebalancer = _msgSender();
        uint64 orderId = _storage.nextOrderId++;
        bytes32[3] memory data = LibOrder.encodeRebalanceOrder(
            orderId,
            rebalancer,
            tokenId0,
            tokenId1,
            rawAmount0,
            maxRawAmount1,
            userData
        );
        _storage.orders.add(orderId, data);
        emit NewRebalanceOrder(rebalancer, orderId, tokenId0, tokenId1, rawAmount0, maxRawAmount1, userData);
    }

    /**
     * @dev   Open/close a position. called by Broker.
     *
     * @param orderId           order id.
     * @param collateralPrice   collateral price. decimals = 18.
     * @param assetPrice        asset price. decimals = 18.
     * @param profitAssetPrice  profit asset price. decimals = 18.
     */
    function fillPositionOrder(
        uint64 orderId,
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice // only used when !isLong
    ) external onlyBroker whenPositionOrderEnabled nonReentrant {
        require(_storage.orders.contains(orderId), "OID"); // can not find this OrderID
        bytes32[3] memory orderData = _storage.orders.get(orderId);
        _storage.orders.remove(orderId);
        OrderType orderType = LibOrder.getOrderType(orderData);
        require(orderType == OrderType.PositionOrder, "TYP"); // order TYPe mismatch

        PositionOrder memory order = orderData.decodePositionOrder();
        require(_blockTimestamp() <= _positionOrderDeadline(order), "EXP"); // EXPired
        uint96 tradingPrice;
        if (order.isOpenPosition()) {
            tradingPrice = LibOrderBook.fillOpenPositionOrder(
                _storage,
                _blockTimestamp(),
                orderId,
                collateralPrice,
                assetPrice,
                order
            );
        } else {
            tradingPrice = LibOrderBook.fillClosePositionOrder(
                _storage,
                _blockTimestamp(),
                orderId,
                collateralPrice,
                assetPrice,
                profitAssetPrice,
                order
            );
        }
        // price check
        if (!order.isMarketOrder()) {
            // open,long      0,0   0,1   1,1   1,0
            // limitOrder     <=    >=    <=    >=
            // triggerOrder   >=    <=    >=    <=
            bool isLess = (order.subAccountId.isLong() == order.isOpenPosition());
            if (order.isTriggerOrder()) {
                isLess = !isLess;
            }
            if (isLess) {
                require(tradingPrice <= order.price, "LMT"); // LiMiTed by limitPrice
            } else {
                require(tradingPrice >= order.price, "LMT"); // LiMiTed by limitPrice
            }
        }

        emit FillOrder(orderId, orderType, orderData);
    }

    /**
     * @dev   Add/remove liquidity. called by Broker.
     *
     *        Check _getLiquidityFeeRate in Liquidity.sol on how to calculate liquidity fee.
     * @param orderId           order id.
     * @param assetPrice        token price that added/removed to. decimals = 18.
     * @param mlpPrice          mlp price. decimals = 18.
     * @param currentAssetValue liquidity USD value of a single asset in all chains (even if tokenId is a stable asset). decimals = 18.
     * @param targetAssetValue  weight / Σ weight * total liquidity USD value in all chains. decimals = 18.
     */
    function fillLiquidityOrder(
        uint64 orderId,
        uint96 assetPrice,
        uint96 mlpPrice,
        uint96 currentAssetValue,
        uint96 targetAssetValue
    ) external onlyBroker whenLiquidityOrderEnabled nonReentrant {
        require(_storage.orders.contains(orderId), "OID"); // can not find this OrderID
        bytes32[3] memory orderData = _storage.orders.get(orderId);
        _storage.orders.remove(orderId);
        LiquidityOrder memory order = LibOrder.decodeLiquidityOrder(orderData);
        if (_storage.callbackWhitelist[order.account]) {
            bool isValid;
            try
                ILiquidityCallback(order.account).beforeFillLiquidityOrder{ gas: _callbackGasLimit() }(
                    order,
                    assetPrice,
                    mlpPrice,
                    currentAssetValue,
                    targetAssetValue
                )
            returns (bool _isValid) {
                isValid = _isValid;
            } catch {
                isValid = false;
            }
            if (!isValid) {
                _cancelLiquidityOrder(order);
                emit CancelOrder(orderId, LibOrder.getOrderType(orderData), orderData);
                return;
            }
        }
        OrderType orderType = LibOrder.getOrderType(orderData);
        require(orderType == OrderType.LiquidityOrder, "TYP"); // order TYPe mismatch
        uint256 mlpAmount = LibOrderBook.fillLiquidityOrder(
            _storage,
            _blockTimestamp(),
            assetPrice,
            mlpPrice,
            currentAssetValue,
            targetAssetValue,
            orderData
        );
        if (_storage.callbackWhitelist[order.account]) {
            try
                ILiquidityCallback(order.account).afterFillLiquidityOrder{ gas: _callbackGasLimit() }(
                    order,
                    mlpAmount,
                    assetPrice,
                    mlpPrice,
                    currentAssetValue,
                    targetAssetValue
                )
            {} catch {}
        }
        emit FillOrder(orderId, orderType, orderData);
    }

    /**
     * @dev   Withdraw collateral/profit. called by Broker.
     *
     * @param orderId           order id.
     * @param collateralPrice   collateral price. decimals = 18.
     * @param assetPrice        asset price. decimals = 18.
     * @param profitAssetPrice  profit asset price. decimals = 18.
     */
    function fillWithdrawalOrder(
        uint64 orderId,
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice // only used when !isLong
    ) external onlyBroker nonReentrant {
        require(_storage.orders.contains(orderId), "OID"); // can not find this OrderID
        bytes32[3] memory orderData = _storage.orders.get(orderId);
        _storage.orders.remove(orderId);
        OrderType orderType = LibOrder.getOrderType(orderData);
        require(orderType == OrderType.WithdrawalOrder, "TYP"); // order TYPe mismatch

        WithdrawalOrder memory order = orderData.decodeWithdrawalOrder();
        require(_blockTimestamp() <= order.placeOrderTime + _storage.marketOrderTimeout, "EXP"); // EXPired
        if (order.isProfit) {
            _storage.pool.withdrawProfit(
                order.subAccountId,
                order.rawAmount,
                order.profitTokenId,
                collateralPrice,
                assetPrice,
                profitAssetPrice
            );
        } else {
            _storage.pool.withdrawCollateral(order.subAccountId, order.rawAmount, collateralPrice, assetPrice);
        }

        emit FillOrder(orderId, orderType, orderData);
    }

    /**
     * @dev   Rebalance. called by Broker.
     *
     * @param orderId  order id.
     * @param price0   price of token 0. decimals = 18.
     * @param price1   price of token 1. decimals = 18.
     */
    function fillRebalanceOrder(
        uint64 orderId,
        uint96 price0,
        uint96 price1
    ) external onlyBroker whenLiquidityOrderEnabled nonReentrant {
        require(_storage.orders.contains(orderId), "OID"); // can not find this OrderID
        bytes32[3] memory orderData = _storage.orders.get(orderId);
        _storage.orders.remove(orderId);
        OrderType orderType = LibOrder.getOrderType(orderData);
        require(orderType == OrderType.RebalanceOrder, "TYP"); // order TYPe mismatch

        RebalanceOrder memory order = orderData.decodeRebalanceOrder();
        _storage.pool.rebalance(
            order.rebalancer,
            order.tokenId0,
            order.tokenId1,
            order.rawAmount0,
            order.maxRawAmount1,
            order.userData,
            price0,
            price1
        );

        emit FillOrder(orderId, orderType, orderData);
    }

    /**
     * @notice Cancel an Order by orderId.
     */
    function cancelOrder(uint64 orderId) external nonReentrant {
        require(_storage.orders.contains(orderId), "OID"); // can not find this OrderID
        bytes32[3] memory orderData = _storage.orders.get(orderId);
        _storage.orders.remove(orderId);
        address account = orderData.getOrderOwner();
        OrderType orderType = LibOrder.getOrderType(orderData);
        if (orderType == OrderType.PositionOrder) {
            PositionOrder memory order = orderData.decodePositionOrder();
            if (_storage.brokers[_msgSender()]) {
                require(_blockTimestamp() > _positionOrderDeadline(order), "EXP"); // not EXPired yet
            } else {
                require(_msgSender() == account, "SND"); // SeNDer is not authorized
            }
            if (order.isOpenPosition() && order.collateral > 0) {
                address collateralAddress = _storage.pool.getAssetAddress(
                    order.subAccountId.getSubAccountCollateralId()
                );
                LibOrderBook._transferOut(_storage, collateralAddress, account, order.collateral);
            }
            // tp/sl strategy
            delete _storage.positionOrderExtras[orderId];
            _storage.activatedTpslOrders[order.subAccountId].remove(uint256(orderId));
        } else if (orderType == OrderType.LiquidityOrder) {
            require(_msgSender() == account, "SND"); // SeNDer is not authorized
            LiquidityOrder memory order = orderData.decodeLiquidityOrder();
            _cancelLiquidityOrder(order);
        } else if (orderType == OrderType.WithdrawalOrder) {
            if (_storage.brokers[_msgSender()]) {
                WithdrawalOrder memory order = orderData.decodeWithdrawalOrder();
                uint256 deadline = order.placeOrderTime + _storage.marketOrderTimeout;
                require(_blockTimestamp() > deadline, "EXP"); // not EXPired yet
            } else {
                require(_msgSender() == account, "SND"); // SeNDer is not authorized
            }
        } else if (orderType == OrderType.RebalanceOrder) {
            require(_msgSender() == account, "SND"); // SeNDer is not authorized
        } else {
            revert();
        }
        emit CancelOrder(orderId, LibOrder.getOrderType(orderData), orderData);
    }

    function _cancelLiquidityOrder(LiquidityOrder memory order) internal {
        if (order.isAdding) {
            address collateralAddress = _storage.pool.getAssetAddress(order.assetId);
            LibOrderBook._transferOut(_storage, collateralAddress, order.account, order.rawAmount);
        } else {
            _storage.mlp.safeTransfer(order.account, order.rawAmount);
        }
        if (_storage.callbackWhitelist[order.account]) {
            try
                ILiquidityCallback(order.account).afterCancelLiquidityOrder{ gas: _callbackGasLimit() }(order)
            {} catch {}
        }
    }

    /**
     * @notice Trader can withdraw all collateral only when position = 0.
     */
    function withdrawAllCollateral(bytes32 subAccountId) external {
        require(subAccountId.getSubAccountOwner() == _msgSender(), "SND"); // SeNDer is not authorized
        _storage.pool.withdrawAllCollateral(subAccountId);
    }

    /**
     * @notice Broker can update funding each [fundingInterval] seconds by specifying utilizations.
     *
     *         Check _getFundingRate in Liquidity.sol on how to calculate funding rate.
     * @param  stableUtilization    Stable coin utilization in all chains. decimals = 5.
     * @param  unstableTokenIds     All unstable Asset id(s) MUST be passed in order. ex: 1, 2, 5, 6, ...
     * @param  unstableUtilizations Unstable Asset utilizations in all chains decimals = 5.
     * @param  unstablePrices       Unstable Asset prices decimals = 18.
     */
    function updateFundingState(
        uint32 stableUtilization, // 1e5
        uint8[] calldata unstableTokenIds,
        uint32[] calldata unstableUtilizations, // 1e5
        uint96[] calldata unstablePrices // 1e18
    ) external onlyBroker {
        _storage.pool.updateFundingState(stableUtilization, unstableTokenIds, unstableUtilizations, unstablePrices);
    }

    /**
     * @notice Deposit collateral into a subAccount.
     *
     * @param  subAccountId       sub account id. see LibSubAccount.decodeSubAccountId.
     * @param  collateralAmount   collateral amount. decimals = erc20.decimals.
     */
    function depositCollateral(bytes32 subAccountId, uint256 collateralAmount) external payable {
        LibSubAccount.DecodedSubAccountId memory account = subAccountId.decodeSubAccountId();
        require(account.account == _msgSender(), "SND"); // SeNDer is not authorized
        require(collateralAmount != 0, "C=0"); // Collateral Is Zero
        address collateralAddress = _storage.pool.getAssetAddress(account.collateralId);
        LibOrderBook._transferIn(_storage, _msgSender(), collateralAddress, address(_storage.pool), collateralAmount);
        _storage.pool.depositCollateral(subAccountId, collateralAmount);
    }

    function liquidate(
        bytes32 subAccountId,
        uint8 profitAssetId, // only used when !isLong
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice // only used when !isLong
    ) external onlyBroker {
        _storage.pool.liquidate(subAccountId, profitAssetId, collateralPrice, assetPrice, profitAssetPrice);
        // auto withdraw
        (uint96 collateral, , , , ) = _storage.pool.getSubAccount(subAccountId);
        if (collateral > 0) {
            _storage.pool.withdrawAllCollateral(subAccountId);
        }
        // cancel activated tp/sl orders
        LibOrderBook.cancelActivatedTpslOrders(_storage, subAccountId);
    }

    function redeemMuxToken(uint8 tokenId, uint96 muxTokenAmount) external {
        address trader = _msgSender();
        LibOrderBook.redeemMuxToken(_storage, trader, tokenId, muxTokenAmount);
    }

    /**
     * @dev Broker can withdraw brokerGasRebate.
     */
    function claimBrokerGasRebate() external onlyBroker returns (uint256 rawAmount) {
        return _storage.pool.claimBrokerGasRebate(msg.sender);
    }

    function _callbackGasLimit() internal view returns (uint256) {
        return _storage.callbackGasLimit == 0 ? gasleft() : _storage.callbackGasLimit;
    }

    function _blockTimestamp() internal view virtual returns (uint32) {
        return uint32(block.timestamp);
    }

    function _positionOrderDeadline(PositionOrder memory order) internal view returns (uint32) {
        if (order.isMarketOrder()) {
            return order.placeOrderTime + _storage.marketOrderTimeout;
        } else {
            return order.placeOrderTime + LibMath.min32(uint32(order.expire10s) * 10, _storage.maxLimitOrderTimeout);
        }
    }
}

File 1 of 23 : OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

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

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

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

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

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

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

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

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

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

File 1 of 23 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * 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 initialize the implementation contract, you can either invoke the
 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() initializer {}
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

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

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
        // contract may have been reentered.
        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

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

    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}

File 1 of 23 : ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

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

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

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

    uint256 private _status;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

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

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

File 1 of 23 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

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

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 1 of 23 : EnumerableSetUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSetUpgradeable {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastvalue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastvalue;
                // Update the index for the moved value
                set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        return _values(set._inner);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly {
            result := store
        }

        return result;
    }
}

File 1 of 23 : SafeOwnableUpgradeable.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract SafeOwnableUpgradeable is OwnableUpgradeable {
    address internal _pendingOwner;

    event PrepareToTransferOwnership(address indexed pendingOwner);

    function __SafeOwnable_init() internal onlyInitializing {
        __Ownable_init();
    }

    function transferOwnership(address newOwner) public virtual override onlyOwner {
        require(newOwner != address(0), "O=0"); // Owner Is Zero
        require(newOwner != owner(), "O=O"); // Owner is the same as the old Owner
        _pendingOwner = newOwner;
        emit PrepareToTransferOwnership(_pendingOwner);
    }

    function takeOwnership() public virtual {
        require(_msgSender() == _pendingOwner, "SND"); // SeNDer is not authorized
        _transferOwnership(_pendingOwner);
        _pendingOwner = address(0);
    }

    function renounceOwnership() public virtual override onlyOwner {
        _pendingOwner = address(0);
        _transferOwnership(address(0));
    }
}

File 1 of 23 : Types.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

struct LiquidityPoolStorage {
    // slot
    address orderBook;
    // slot
    address mlp;
    // slot
    address _reserved6; // was liquidityManager
    // slot
    address weth;
    // slot
    uint128 _reserved1;
    uint32 shortFundingBaseRate8H; // 1e5
    uint32 shortFundingLimitRate8H; // 1e5
    uint32 fundingInterval; // 1e0
    uint32 lastFundingTime; // 1e0
    // slot
    uint32 _reserved2;
    // slot
    Asset[] assets;
    // slot
    mapping(bytes32 => SubAccount) accounts;
    // slot
    mapping(address => bytes32) _reserved3;
    // slot
    address _reserved4;
    uint96 _reserved5;
    // slot
    uint96 mlpPriceLowerBound; // safeguard against mlp price attacks
    uint96 mlpPriceUpperBound; // safeguard against mlp price attacks
    uint32 liquidityBaseFeeRate; // 1e5
    uint32 liquidityDynamicFeeRate; // 1e5
    // slot
    address nativeUnwrapper;
    // a sequence number that changes when LiquidityPoolStorage updated. this helps to keep track the state of LiquidityPool.
    uint32 sequence; // 1e0. note: will be 0 after 0xffffffff
    uint32 strictStableDeviation; // 1e5. strictStable price is 1.0 if in this damping range
    uint32 brokerTransactions; // transaction count for broker gas rebates
    // slot
    address vault;
    uint96 brokerGasRebate; // the number of native tokens for broker gas rebates per transaction
    // slot
    address maintainer;
    // slot
    mapping(address => bool) liquidityManager;
    bytes32[50] _gap;
}

struct Asset {
    // slot
    // assets with the same symbol in different chains are the same asset. they shares the same muxToken. so debts of the same symbol
    // can be accumulated across chains (see Reader.AssetState.deduct). ex: ERC20(fBNB).symbol should be "BNB", so that BNBs of
    // different chains are the same.
    // since muxToken of all stable coins is the same and is calculated separately (see Reader.ChainState.stableDeduct), stable coin
    // symbol can be different (ex: "USDT", "USDT.e" and "fUSDT").
    bytes32 symbol;
    // slot
    address tokenAddress; // erc20.address
    uint8 id;
    uint8 decimals; // erc20.decimals
    uint56 flags; // a bitset of ASSET_*
    uint24 _flagsPadding;
    // slot
    uint32 initialMarginRate; // 1e5
    uint32 maintenanceMarginRate; // 1e5
    uint32 minProfitRate; // 1e5
    uint32 minProfitTime; // 1e0
    uint32 positionFeeRate; // 1e5
    // note: 96 bits remaining
    // slot
    address referenceOracle;
    uint32 referenceDeviation; // 1e5
    uint8 referenceOracleType;
    uint32 halfSpread; // 1e5
    // note: 24 bits remaining
    // slot
    uint96 credit;
    uint128 _reserved2;
    // slot
    uint96 collectedFee;
    uint32 liquidationFeeRate; // 1e5
    uint96 spotLiquidity;
    // note: 32 bits remaining
    // slot
    uint96 maxLongPositionSize;
    uint96 totalLongPosition;
    // note: 64 bits remaining
    // slot
    uint96 averageLongPrice;
    uint96 maxShortPositionSize;
    // note: 64 bits remaining
    // slot
    uint96 totalShortPosition;
    uint96 averageShortPrice;
    // note: 64 bits remaining
    // slot, less used
    address muxTokenAddress; // muxToken.address. all stable coins share the same muxTokenAddress
    uint32 spotWeight; // 1e0
    uint32 longFundingBaseRate8H; // 1e5
    uint32 longFundingLimitRate8H; // 1e5
    // slot
    uint128 longCumulativeFundingRate; // Σ_t fundingRate_t
    uint128 shortCumulativeFunding; // Σ_t fundingRate_t * indexPrice_t
}

uint32 constant FUNDING_PERIOD = 3600 * 8;

uint56 constant ASSET_IS_STABLE = 0x00000000000001; // is a usdt, usdc, ...
uint56 constant ASSET_CAN_ADD_REMOVE_LIQUIDITY = 0x00000000000002; // can call addLiquidity and removeLiquidity with this token
uint56 constant ASSET_IS_TRADABLE = 0x00000000000100; // allowed to be assetId
uint56 constant ASSET_IS_OPENABLE = 0x00000000010000; // can open position
uint56 constant ASSET_IS_SHORTABLE = 0x00000001000000; // allow shorting this asset
uint56 constant ASSET_USE_STABLE_TOKEN_FOR_PROFIT = 0x00000100000000; // take profit will get stable coin
uint56 constant ASSET_IS_ENABLED = 0x00010000000000; // allowed to be assetId and collateralId
uint56 constant ASSET_IS_STRICT_STABLE = 0x01000000000000; // assetPrice is always 1 unless volatility exceeds strictStableDeviation

struct SubAccount {
    // slot
    uint96 collateral;
    uint96 size;
    uint32 lastIncreasedTime;
    // slot
    uint96 entryPrice;
    uint128 entryFunding; // entry longCumulativeFundingRate for long position. entry shortCumulativeFunding for short position
}

enum ReferenceOracleType {
    None,
    Chainlink
}

File 1 of 23 : ILiquidityCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "../orderbook/Types.sol";

interface ILiquidityCallback {
    function beforeFillLiquidityOrder(
        LiquidityOrder calldata order,
        uint96 assetPrice,
        uint96 mlpPrice,
        uint96 currentAssetValue,
        uint96 targetAssetValue
    ) external returns (bool);

    function afterFillLiquidityOrder(
        LiquidityOrder calldata order,
        uint256 outAmount,
        uint96 assetPrice,
        uint96 mlpPrice,
        uint96 currentAssetValue,
        uint96 targetAssetValue
    ) external;

    function afterCancelLiquidityOrder(LiquidityOrder calldata order) external;
}

File 1 of 23 : ILiquidityPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "../core/Types.sol";

interface ILiquidityPool {
    /////////////////////////////////////////////////////////////////////////////////
    //                                 getters

    function getAssetInfo(uint8 assetId) external view returns (Asset memory);

    function getAllAssetInfo() external view returns (Asset[] memory);

    function getAssetAddress(uint8 assetId) external view returns (address);

    function getLiquidityPoolStorage()
        external
        view
        returns (
            // [0] shortFundingBaseRate8H
            // [1] shortFundingLimitRate8H
            // [2] lastFundingTime
            // [3] fundingInterval
            // [4] liquidityBaseFeeRate
            // [5] liquidityDynamicFeeRate
            // [6] sequence. note: will be 0 after 0xffffffff
            // [7] strictStableDeviation
            uint32[8] memory u32s,
            // [0] mlpPriceLowerBound
            // [1] mlpPriceUpperBound
            uint96[2] memory u96s
        );

    function getSubAccount(
        bytes32 subAccountId
    )
        external
        view
        returns (uint96 collateral, uint96 size, uint32 lastIncreasedTime, uint96 entryPrice, uint128 entryFunding);

    /////////////////////////////////////////////////////////////////////////////////
    //                             for Trader / Broker

    function withdrawAllCollateral(bytes32 subAccountId) external;

    /////////////////////////////////////////////////////////////////////////////////
    //                                 only Broker

    function depositCollateral(
        bytes32 subAccountId,
        uint256 rawAmount // NOTE: OrderBook SHOULD transfer rawAmount collateral to LiquidityPool
    ) external;

    function withdrawCollateral(
        bytes32 subAccountId,
        uint256 rawAmount,
        uint96 collateralPrice,
        uint96 assetPrice
    ) external;

    function withdrawProfit(
        bytes32 subAccountId,
        uint256 rawAmount,
        uint8 profitAssetId, // only used when !isLong
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice // only used when !isLong
    ) external;

    /**
     * @dev   Add liquidity.
     *
     * @param trader            liquidity provider address.
     * @param tokenId           asset.id that added.
     * @param rawAmount         asset token amount. decimals = erc20.decimals.
     * @param tokenPrice        token price. decimals = 18.
     * @param mlpPrice          mlp price.  decimals = 18.
     * @param currentAssetValue liquidity USD value of a single asset in all chains (even if tokenId is a stable asset).
     * @param targetAssetValue  weight / Σ weight * total liquidity USD value in all chains.
     */
    function addLiquidity(
        address trader,
        uint8 tokenId,
        uint256 rawAmount, // NOTE: OrderBook SHOULD transfer rawAmount collateral to LiquidityPool
        uint96 tokenPrice,
        uint96 mlpPrice,
        uint96 currentAssetValue,
        uint96 targetAssetValue
    ) external returns (uint96 mlpAmount);

    /**
     * @dev   Remove liquidity.
     *
     * @param trader            liquidity provider address.
     * @param mlpAmount         mlp amount. decimals = 18.
     * @param tokenId           asset.id that removed to.
     * @param tokenPrice        token price. decimals = 18.
     * @param mlpPrice          mlp price. decimals = 18.
     * @param currentAssetValue liquidity USD value of a single asset in all chains (even if tokenId is a stable asset). decimals = 18.
     * @param targetAssetValue  weight / Σ weight * total liquidity USD value in all chains. decimals = 18.
     */
    function removeLiquidity(
        address trader,
        uint96 mlpAmount, // NOTE: OrderBook SHOULD transfer mlpAmount mlp to LiquidityPool
        uint8 tokenId,
        uint96 tokenPrice,
        uint96 mlpPrice,
        uint96 currentAssetValue,
        uint96 targetAssetValue
    ) external returns (uint256 rawAmount);

    /**
     * @notice Open a position.
     *
     * @param  subAccountId     check LibSubAccount.decodeSubAccountId for detail.
     * @param  amount           position size. decimals = 18.
     * @param  collateralPrice  price of subAccount.collateral.
     * @param  assetPrice       price of subAccount.asset.
     */
    function openPosition(
        bytes32 subAccountId,
        uint96 amount,
        uint96 collateralPrice,
        uint96 assetPrice
    ) external returns (uint96);

    /**
     * @notice Close a position.
     *
     * @param  subAccountId     check LibSubAccount.decodeSubAccountId for detail.
     * @param  amount           position size. decimals = 18.
     * @param  profitAssetId    for long position (unless asset.useStable is true), ignore this argument;
     *                          for short position, the profit asset should be one of the stable coin.
     * @param  collateralPrice  price of subAccount.collateral. decimals = 18.
     * @param  assetPrice       price of subAccount.asset. decimals = 18.
     * @param  profitAssetPrice price of profitAssetId. ignore this argument if profitAssetId is ignored. decimals = 18.
     */
    function closePosition(
        bytes32 subAccountId,
        uint96 amount,
        uint8 profitAssetId, // only used when !isLong
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice // only used when !isLong
    ) external returns (uint96 tradingPrice);

    /**
     * @notice Broker can update funding each [fundingInterval] seconds by specifying utilizations.
     *
     *         Check _getFundingRate in Liquidity.sol on how to calculate funding rate.
     * @param  stableUtilization    Stable coin utilization in all chains. decimals = 5.
     * @param  unstableTokenIds     All unstable Asset id(s) MUST be passed in order. ex: 1, 2, 5, 6, ...
     * @param  unstableUtilizations Unstable Asset utilizations in all chains. decimals = 5.
     * @param  unstablePrices       Unstable Asset prices.
     */
    function updateFundingState(
        uint32 stableUtilization, // 1e5
        uint8[] calldata unstableTokenIds,
        uint32[] calldata unstableUtilizations, // 1e5
        uint96[] calldata unstablePrices
    ) external;

    function liquidate(
        bytes32 subAccountId,
        uint8 profitAssetId, // only used when !isLong
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice // only used when !isLong
    ) external returns (uint96);

    /**
     * @notice Redeem mux token into original tokens.
     *
     *         Only strict stable coins and un-stable coins are supported.
     */
    function redeemMuxToken(
        address trader,
        uint8 tokenId,
        uint96 muxTokenAmount // NOTE: OrderBook SHOULD transfer muxTokenAmount to LiquidityPool
    ) external;

    /**
     * @dev  Rebalance pool liquidity. Swap token 0 for token 1.
     *
     *       rebalancer must implement IMuxRebalancerCallback.
     */
    function rebalance(
        address rebalancer,
        uint8 tokenId0,
        uint8 tokenId1,
        uint96 rawAmount0,
        uint96 maxRawAmount1,
        bytes32 userData,
        uint96 price0,
        uint96 price1
    ) external;

    /**
     * @dev Broker can withdraw brokerGasRebate.
     */
    function claimBrokerGasRebate(address receiver) external returns (uint256 rawAmount);

    /////////////////////////////////////////////////////////////////////////////////
    //                            only LiquidityManager

    function transferLiquidityOut(uint8[] memory assetIds, uint256[] memory amounts) external;

    function transferLiquidityIn(uint8[] memory assetIds, uint256[] memory amounts) external;
}

File 1 of 23 : INativeUnwrapper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

interface INativeUnwrapper {
    function unwrap(address payable to, uint256 rawAmount) external;
}

File 1 of 23 : IReferralManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

interface IReferralManager {
    struct TierSetting {
        uint8 tier;
        uint64 stakeThreshold;
        uint64 discountRate;
        uint64 rebateRate;
    }

    event RegisterReferralCode(address referralCodeOwner, bytes32 referralCode);
    event SetReferralCode(address trader, bytes32 referralCode);
    event SetHandler(address handler, bool enable);
    event SetTiers(TierSetting[] newTierSettings);
    event SetMaintainer(address previousMaintainer, address newMaintainer);
    event SetRebateRecipient(bytes32 referralCode, address referralCodeOwner, address rebateRecipient);
    event TransferReferralCode(bytes32 referralCode, address previousOwner, address newOwner);

    function isHandler(address handler) external view returns (bool);

    function rebateRecipients(bytes32 referralCode) external view returns (address);

    // management methods
    function setHandler(address handler, bool enable) external;

    function setTiers(TierSetting[] memory newTierSettings) external;

    // methods only available on primary network
    function isValidReferralCode(bytes32 referralCode) external view returns (bool);

    function registerReferralCode(bytes32 referralCode, address rebateRecipient) external;

    function setRebateRecipient(bytes32 referralCode, address rebateRecipient) external;

    function transferReferralCode(bytes32 referralCode, address newOwner) external;

    // methods available on secondary network
    function getReferralCodeOf(address trader) external view returns (bytes32, uint256);

    function setReferrerCode(bytes32 referralCode) external;

    function setReferrerCodeFor(address trader, bytes32 referralCode) external;
}

File 1 of 23 : IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

interface IWETH {
    function deposit() external payable;

    function transfer(address to, uint256 value) external returns (bool);

    function withdraw(uint256) external;
}

File 1 of 23 : LibMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

library LibMath {
    function min(uint96 a, uint96 b) internal pure returns (uint96) {
        return a <= b ? a : b;
    }

    function min32(uint32 a, uint32 b) internal pure returns (uint32) {
        return a <= b ? a : b;
    }

    function max32(uint32 a, uint32 b) internal pure returns (uint32) {
        return a >= b ? a : b;
    }

    function wmul(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a * b) / 1e18;
    }

    function rmul(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a * b) / 1e5;
    }

    function wdiv(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a * 1e18) / b;
    }

    function safeUint32(uint256 n) internal pure returns (uint32) {
        require(n <= type(uint32).max, "O32"); // uint32 Overflow
        return uint32(n);
    }

    function safeUint96(uint256 n) internal pure returns (uint96) {
        require(n <= type(uint96).max, "O96"); // uint96 Overflow
        return uint96(n);
    }

    function safeUint128(uint256 n) internal pure returns (uint128) {
        require(n <= type(uint128).max, "O12"); // uint128 Overflow
        return uint128(n);
    }
}

File 1 of 23 : LibOrder.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "../orderbook/Types.sol";
import "./LibSubAccount.sol";

library LibOrder {
    // position order flags
    uint8 constant POSITION_OPEN = 0x80; // this flag means openPosition; otherwise closePosition
    uint8 constant POSITION_MARKET_ORDER = 0x40; // this flag means ignore limitPrice
    uint8 constant POSITION_WITHDRAW_ALL_IF_EMPTY = 0x20; // this flag means auto withdraw all collateral if position.size == 0
    uint8 constant POSITION_TRIGGER_ORDER = 0x10; // this flag means this is a trigger order (ex: stop-loss order). otherwise this is a limit order (ex: take-profit order)
    uint8 constant POSITION_TPSL_STRATEGY = 0x08; // for open-position-order, this flag auto place take-profit and stop-loss orders when open-position-order fills.
    //                                               for close-position-order, this flag means ignore limitPrice and profitTokenId, and use extra.tpPrice, extra.slPrice, extra.tpslProfitTokenId instead.
    uint8 constant POSITION_SHOULD_REACH_MIN_PROFIT = 0x04; // this flag is used to ensure that either the minProfitTime is met or the minProfitRate ratio is reached when close a position. only available when minProfitTime > 0.

    // order data[1] SHOULD reserve lower 64bits for enumIndex
    bytes32 constant ENUM_INDEX_BITS = bytes32(uint256(0xffffffffffffffff));

    struct OrderList {
        uint64[] _orderIds;
        mapping(uint64 => bytes32[3]) _orders;
    }

    function add(OrderList storage list, uint64 orderId, bytes32[3] memory order) internal {
        require(!contains(list, orderId), "DUP"); // already seen this orderId
        list._orderIds.push(orderId);
        // The value is stored at length-1, but we add 1 to all indexes
        // and use 0 as a sentinel value
        uint256 enumIndex = list._orderIds.length;
        require(enumIndex <= type(uint64).max, "O64"); // Overflow uint64
        // order data[1] SHOULD reserve lower 64bits for enumIndex
        require((order[1] & ENUM_INDEX_BITS) == 0, "O1F"); // bad Order[1] Field
        order[1] = bytes32(uint256(order[1]) | uint256(enumIndex));
        list._orders[orderId] = order;
    }

    function remove(OrderList storage list, uint64 orderId) internal {
        bytes32[3] storage orderToRemove = list._orders[orderId];
        uint64 enumIndexToRemove = uint64(uint256(orderToRemove[1]));
        require(enumIndexToRemove != 0, "OID"); // orderId is not found
        // swap and pop
        uint256 indexToRemove = enumIndexToRemove - 1;
        uint256 lastIndex = list._orderIds.length - 1;
        if (lastIndex != indexToRemove) {
            uint64 lastOrderId = list._orderIds[lastIndex];
            // move the last orderId
            list._orderIds[indexToRemove] = lastOrderId;
            // replace enumIndex
            bytes32[3] storage lastOrder = list._orders[lastOrderId];
            lastOrder[1] = (lastOrder[1] & (~ENUM_INDEX_BITS)) | bytes32(uint256(enumIndexToRemove));
        }
        list._orderIds.pop();
        delete list._orders[orderId];
    }

    function contains(OrderList storage list, uint64 orderId) internal view returns (bool) {
        bytes32[3] storage order = list._orders[orderId];
        // order data[1] always contains enumIndex
        return order[1] != bytes32(0);
    }

    function length(OrderList storage list) internal view returns (uint256) {
        return list._orderIds.length;
    }

    function at(OrderList storage list, uint256 index) internal view returns (bytes32[3] memory order) {
        require(index < list._orderIds.length, "IDX"); // InDex overflow
        uint64 orderId = list._orderIds[index];
        order = list._orders[orderId];
    }

    function get(OrderList storage list, uint64 orderId) internal view returns (bytes32[3] memory) {
        return list._orders[orderId];
    }

    function getOrderType(bytes32[3] memory orderData) internal pure returns (OrderType) {
        return OrderType(uint8(uint256(orderData[0])));
    }

    function getOrderOwner(bytes32[3] memory orderData) internal pure returns (address) {
        return address(bytes20(orderData[0]));
    }

    // check Types.PositionOrder for schema
    function encodePositionOrder(
        uint64 orderId,
        bytes32 subAccountId,
        uint96 collateral, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 placeOrderTime,
        uint24 expire10s
    ) internal pure returns (bytes32[3] memory data) {
        require((subAccountId & LibSubAccount.SUB_ACCOUNT_ID_FORBIDDEN_BITS) == 0, "AID"); // bad subAccount ID
        data[0] = subAccountId | bytes32(uint256(orderId) << 8) | bytes32(uint256(OrderType.PositionOrder));
        data[1] = bytes32(
            (uint256(size) << 160) |
                (uint256(profitTokenId) << 152) |
                (uint256(flags) << 144) |
                (uint256(expire10s) << 96) |
                (uint256(placeOrderTime) << 64)
        );
        data[2] = bytes32((uint256(price) << 160) | (uint256(collateral) << 64));
    }

    // check Types.PositionOrder for schema
    function decodePositionOrder(bytes32[3] memory data) internal pure returns (PositionOrder memory order) {
        order.subAccountId = bytes32(bytes23(data[0]));
        order.collateral = uint96(bytes12(data[2] << 96));
        order.size = uint96(bytes12(data[1]));
        order.flags = uint8(bytes1(data[1] << 104));
        order.price = uint96(bytes12(data[2]));
        order.profitTokenId = uint8(bytes1(data[1] << 96));
        order.expire10s = uint24(bytes3(data[1] << 136));
        order.placeOrderTime = uint32(bytes4(data[1] << 160));
    }

    // check Types.LiquidityOrder for schema
    function encodeLiquidityOrder(
        uint64 orderId,
        address account,
        uint8 assetId,
        uint96 rawAmount, // erc20.decimals
        bool isAdding,
        uint32 placeOrderTime
    ) internal pure returns (bytes32[3] memory data) {
        uint8 flags = isAdding ? 1 : 0;
        data[0] = bytes32(
            (uint256(uint160(account)) << 96) | (uint256(orderId) << 8) | uint256(OrderType.LiquidityOrder)
        );
        data[1] = bytes32(
            (uint256(rawAmount) << 160) |
                (uint256(assetId) << 152) |
                (uint256(flags) << 144) |
                (uint256(placeOrderTime) << 64)
        );
    }

    // check Types.LiquidityOrder for schema
    function decodeLiquidityOrder(bytes32[3] memory data) internal pure returns (LiquidityOrder memory order) {
        order.id = uint64(bytes8(data[0] << 184));
        order.account = address(bytes20(data[0]));
        order.rawAmount = uint96(bytes12(data[1]));
        order.assetId = uint8(bytes1(data[1] << 96));
        uint8 flags = uint8(bytes1(data[1] << 104));
        order.isAdding = flags > 0;
        order.placeOrderTime = uint32(bytes4(data[1] << 160));
    }

    // check Types.WithdrawalOrder for schema
    function encodeWithdrawalOrder(
        uint64 orderId,
        bytes32 subAccountId,
        uint96 rawAmount, // erc20.decimals
        uint8 profitTokenId,
        bool isProfit,
        uint32 placeOrderTime
    ) internal pure returns (bytes32[3] memory data) {
        require((subAccountId & LibSubAccount.SUB_ACCOUNT_ID_FORBIDDEN_BITS) == 0, "AID"); // bad subAccount ID
        uint8 flags = isProfit ? 1 : 0;
        data[0] = subAccountId | bytes32(uint256(orderId) << 8) | bytes32(uint256(OrderType.WithdrawalOrder));
        data[1] = bytes32(
            (uint256(rawAmount) << 160) |
                (uint256(profitTokenId) << 152) |
                (uint256(flags) << 144) |
                (uint256(placeOrderTime) << 64)
        );
    }

    // check Types.WithdrawalOrder for schema
    function decodeWithdrawalOrder(bytes32[3] memory data) internal pure returns (WithdrawalOrder memory order) {
        order.subAccountId = bytes32(bytes23(data[0]));
        order.rawAmount = uint96(bytes12(data[1]));
        order.profitTokenId = uint8(bytes1(data[1] << 96));
        uint8 flags = uint8(bytes1(data[1] << 104));
        order.isProfit = flags > 0;
        order.placeOrderTime = uint32(bytes4(data[1] << 160));
    }

    // check Types.RebalanceOrder for schema
    function encodeRebalanceOrder(
        uint64 orderId,
        address rebalancer,
        uint8 tokenId0,
        uint8 tokenId1,
        uint96 rawAmount0, // erc20.decimals
        uint96 maxRawAmount1, // erc20.decimals
        bytes32 userData
    ) internal pure returns (bytes32[3] memory data) {
        data[0] = bytes32(
            (uint256(uint160(rebalancer)) << 96) |
                (uint256(tokenId0) << 88) |
                (uint256(tokenId1) << 80) |
                (uint256(orderId) << 8) |
                uint256(OrderType.RebalanceOrder)
        );
        data[1] = bytes32((uint256(rawAmount0) << 160) | (uint256(maxRawAmount1) << 64));
        data[2] = userData;
    }

    // check Types.RebalanceOrder for schema
    function decodeRebalanceOrder(bytes32[3] memory data) internal pure returns (RebalanceOrder memory order) {
        order.rebalancer = address(bytes20(data[0]));
        order.tokenId0 = uint8(bytes1(data[0] << 160));
        order.tokenId1 = uint8(bytes1(data[0] << 168));
        order.rawAmount0 = uint96(bytes12(data[1]));
        order.maxRawAmount1 = uint96(bytes12(data[1] << 96));
        order.userData = data[2];
    }

    function isOpenPosition(PositionOrder memory order) internal pure returns (bool) {
        return (order.flags & POSITION_OPEN) != 0;
    }

    function isMarketOrder(PositionOrder memory order) internal pure returns (bool) {
        return (order.flags & POSITION_MARKET_ORDER) != 0;
    }

    function isWithdrawIfEmpty(PositionOrder memory order) internal pure returns (bool) {
        return (order.flags & POSITION_WITHDRAW_ALL_IF_EMPTY) != 0;
    }

    function isTriggerOrder(PositionOrder memory order) internal pure returns (bool) {
        return (order.flags & POSITION_TRIGGER_ORDER) != 0;
    }

    function isTpslStrategy(PositionOrder memory order) internal pure returns (bool) {
        return (order.flags & POSITION_TPSL_STRATEGY) != 0;
    }

    function shouldReachMinProfit(PositionOrder memory order) internal pure returns (bool) {
        return (order.flags & POSITION_SHOULD_REACH_MIN_PROFIT) != 0;
    }
}

File 1 of 23 : LibOrderBook.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../libraries/LibSubAccount.sol";
import "../libraries/LibMath.sol";
import "../interfaces/IReferralManager.sol";
import "../orderbook/Types.sol";
import "../orderbook/Storage.sol";

library LibOrderBook {
    using LibSubAccount for bytes32;
    using SafeERC20Upgradeable for IERC20Upgradeable;
    using LibOrder for LibOrder.OrderList;
    using LibOrder for bytes32[3];
    using LibOrder for PositionOrder;
    using LibOrder for LiquidityOrder;
    using LibOrder for WithdrawalOrder;
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
    using LibMath for uint256;

    // do not forget to update OrderBook if this line updates
    event CancelOrder(uint64 orderId, OrderType orderType, bytes32[3] orderData);
    // do not forget to update OrderBook if this line updates
    event NewLiquidityOrder(
        address indexed account,
        uint64 indexed orderId,
        uint8 assetId,
        uint96 rawAmount, // erc20.decimals
        bool isAdding
    );
    // do not forget to update OrderBook if this line updates
    event NewPositionOrder(
        bytes32 indexed subAccountId,
        uint64 indexed orderId,
        uint96 collateral, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline // 1e0. 0 if market order. > 0 if limit order
    );
    // do not forget to update OrderBook if this line updates
    event NewPositionOrderExtra(
        bytes32 indexed subAccountId,
        uint64 indexed orderId,
        uint96 collateral, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline, // 1e0. 0 if market order. > 0 if limit order
        PositionOrderExtra extra
    );

    function _transferIn(
        OrderBookStorage storage _storage,
        address trader,
        address tokenAddress,
        address recipient,
        uint256 rawAmount
    ) internal {
        if (tokenAddress == address(_storage.weth)) {
            require(msg.value > 0 && msg.value == rawAmount, "VAL"); // transaction VALue SHOULD equal to rawAmount
            _storage.weth.deposit{ value: rawAmount }();
            if (recipient != address(this)) {
                _storage.weth.transfer(recipient, rawAmount);
            }
        } else {
            require(msg.value == 0, "VAL"); // transaction VALue SHOULD be 0
            IERC20Upgradeable(tokenAddress).safeTransferFrom(trader, recipient, rawAmount);
        }
    }

    function _transferOut(
        OrderBookStorage storage _storage,
        address tokenAddress,
        address recipient,
        uint256 rawAmount
    ) internal {
        if (tokenAddress == address(_storage.weth)) {
            _storage.weth.transfer(address(_storage.nativeUnwrapper), rawAmount);
            INativeUnwrapper(_storage.nativeUnwrapper).unwrap(payable(recipient), rawAmount);
        } else {
            IERC20Upgradeable(tokenAddress).safeTransfer(recipient, rawAmount);
        }
    }

    function placeLiquidityOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        address account,
        uint8 assetId,
        uint96 rawAmount, // erc20.decimals
        bool isAdding
    ) external {
        require(rawAmount != 0, "A=0"); // Amount Is Zero
        if (isAdding) {
            address collateralAddress = _storage.pool.getAssetAddress(assetId);
            _transferIn(_storage, account, collateralAddress, address(this), rawAmount);
        } else {
            _storage.mlp.safeTransferFrom(account, address(this), rawAmount);
        }
        uint64 orderId = _storage.nextOrderId++;
        bytes32[3] memory data = LibOrder.encodeLiquidityOrder(
            orderId,
            account,
            assetId,
            rawAmount,
            isAdding,
            blockTimestamp
        );
        _storage.orders.add(orderId, data);

        emit NewLiquidityOrder(account, orderId, assetId, rawAmount, isAdding);
    }

    function fillLiquidityOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        uint96 assetPrice,
        uint96 mlpPrice,
        uint96 currentAssetValue,
        uint96 targetAssetValue,
        bytes32[3] memory orderData
    ) external returns (uint256 outAmount) {
        LiquidityOrder memory order = orderData.decodeLiquidityOrder();
        require(blockTimestamp >= order.placeOrderTime + _storage.liquidityLockPeriod, "LCK"); // mlp token is LoCKed
        uint96 rawAmount = order.rawAmount;
        if (order.isAdding) {
            IERC20Upgradeable collateral = IERC20Upgradeable(_storage.pool.getAssetAddress(order.assetId));
            collateral.safeTransfer(address(_storage.pool), rawAmount);
            outAmount = _storage.pool.addLiquidity(
                order.account,
                order.assetId,
                rawAmount,
                assetPrice,
                mlpPrice,
                currentAssetValue,
                targetAssetValue
            );
        } else {
            _storage.mlp.safeTransfer(address(_storage.pool), rawAmount);
            outAmount = _storage.pool.removeLiquidity(
                order.account,
                rawAmount,
                order.assetId,
                assetPrice,
                mlpPrice,
                currentAssetValue,
                targetAssetValue
            );
        }
    }

    function redeemMuxToken(
        OrderBookStorage storage _storage,
        address trader,
        uint8 tokenId,
        uint96 muxTokenAmount
    ) external {
        Asset memory asset = _storage.pool.getAssetInfo(tokenId);
        _transferIn(_storage, trader, asset.muxTokenAddress, address(_storage.pool), muxTokenAmount);
        _storage.pool.redeemMuxToken(trader, tokenId, muxTokenAmount);
    }

    function cancelActivatedTpslOrders(OrderBookStorage storage _storage, bytes32 subAccountId) public {
        EnumerableSetUpgradeable.UintSet storage orderIds = _storage.activatedTpslOrders[subAccountId];
        uint256 length = orderIds.length();
        for (uint256 i = 0; i < length; i++) {
            uint64 orderId = uint64(orderIds.at(i));
            require(_storage.orders.contains(orderId), "OID"); // can not find this OrderID
            bytes32[3] memory orderData = _storage.orders.get(orderId);
            _storage.orders.remove(orderId);

            OrderType orderType = LibOrder.getOrderType(orderData);
            require(orderType == OrderType.PositionOrder, "TYP"); // order TYPe mismatch

            PositionOrder memory order = orderData.decodePositionOrder();
            require(!order.isOpenPosition() && order.collateral == 0, "CLS"); // should be CLoSe position order and no withdraw

            delete _storage.positionOrderExtras[orderId]; // tp/sl strategy

            emit CancelOrder(orderId, orderType, orderData);
        }

        delete _storage.activatedTpslOrders[subAccountId]; // tp/sl strategy
    }

    function placePositionOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        bytes32 subAccountId,
        uint96 collateralAmount, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline, // 1e0
        PositionOrderExtra memory extra
    ) external {
        require(size != 0, "S=0"); // order Size Is Zero
        if ((flags & LibOrder.POSITION_MARKET_ORDER) != 0) {
            require(price == 0, "P!0"); // market order does not need a limit Price
            require(deadline == 0, "D!0"); // market order does not need a deadline
        } else {
            require(deadline > blockTimestamp, "D<0"); // Deadline is earlier than now
        }
        if (profitTokenId > 0) {
            // note: profitTokenId == 0 is also valid, this only partially protects the function from misuse
            require((flags & LibOrder.POSITION_OPEN) == 0, "T!0"); // opening position does not need a profit Token id
        }
        if ((flags & LibOrder.POSITION_OPEN) != 0) {
            _placeOpenPositionOrder(
                _storage,
                blockTimestamp,
                subAccountId,
                collateralAmount,
                size,
                price,
                flags,
                deadline,
                extra
            );
        } else {
            _placeClosePositionOrder(
                _storage,
                blockTimestamp,
                subAccountId,
                collateralAmount,
                size,
                price,
                profitTokenId,
                flags,
                deadline,
                extra
            );
        }
    }

    function _placeOpenPositionOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        bytes32 subAccountId,
        uint96 collateralAmount, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 flags,
        uint32 deadline, // 1e0
        PositionOrderExtra memory extra
    ) private {
        // add order
        uint64 orderId = _placePositionOrder(
            _storage,
            blockTimestamp,
            deadline,
            PositionOrder({
                id: 0, // ignored
                subAccountId: subAccountId,
                collateral: collateralAmount,
                size: size,
                price: price,
                profitTokenId: 0, // open-position-order does not have a profitTokenId
                flags: flags,
                placeOrderTime: 0, // ignored
                expire10s: 0 // ignored
            })
        );
        // fetch collateral
        if (collateralAmount > 0) {
            address accountOwner = subAccountId.getSubAccountOwner();
            uint8 collateralId = subAccountId.getSubAccountCollateralId();
            address collateralAddress = _storage.pool.getAssetAddress(collateralId);
            _transferIn(_storage, accountOwner, collateralAddress, address(this), collateralAmount);
        }
        if ((flags & LibOrder.POSITION_TPSL_STRATEGY) != 0) {
            // tp/sl strategy
            require((extra.tpPrice > 0 || extra.slPrice > 0), "TPSL"); // TP/SL strategy need tpPrice and/or slPrice
            require(extra.tpslDeadline > blockTimestamp, "D<0"); // Deadline is earlier than now
            require((extra.tpslDeadline - blockTimestamp) / 10 <= type(uint24).max, "DTL"); // Deadline is Too Large
            _storage.positionOrderExtras[orderId] = extra;
            emit NewPositionOrderExtra(
                subAccountId,
                orderId,
                collateralAmount,
                size,
                price,
                0 /* profitTokenId */,
                flags,
                deadline,
                extra
            );
        }
    }

    function _placeClosePositionOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        bytes32 subAccountId,
        uint96 collateralAmount, // erc20.decimals
        uint96 size, // 1e18
        uint96 price, // 1e18
        uint8 profitTokenId,
        uint8 flags,
        uint32 deadline, // 1e0
        PositionOrderExtra memory extra
    ) private {
        if ((flags & LibOrder.POSITION_TPSL_STRATEGY) != 0) {
            // tp/sl strategy
            require(price == 0, "P!0"); // use extra.tpPrice and extra.slPrice instead
            require(collateralAmount == 0, "C!0"); // tp/sl strategy only supports POSITION_WITHDRAW_ALL_IF_EMPTY
            require(profitTokenId == 0, "T!0"); // use extra.tpProfitTokenId instead
            require((flags & LibOrder.POSITION_MARKET_ORDER) == 0, "MKT"); // tp/sl strategy does not support MarKeT order
            require(extra.tpPrice > 0 && extra.slPrice > 0, "TPSL"); // tp/sl strategy need tpPrice and slPrice. otherwise use POSITION_TRIGGER_ORDER instead
            require(extra.tpslDeadline > blockTimestamp, "D<0"); // Deadline is earlier than now
            require((extra.tpslDeadline - blockTimestamp) / 10 <= type(uint24).max, "DTL"); // Deadline is Too Large
            _placeTpslOrdersWhenClose(_storage, blockTimestamp, subAccountId, size, extra);
        } else {
            // normal close-position-order
            if (flags & LibOrder.POSITION_SHOULD_REACH_MIN_PROFIT != 0) {
                // POSITION_MUST_PROFIT is only available if asset.minProfitTime > 0
                uint8 assetId = subAccountId.getSubAccountAssetId();
                Asset memory asset = _storage.pool.getAssetInfo(assetId);
                require(asset.minProfitTime > 0, "MPT"); // asset MinProfitTime is 0
            }
            _placePositionOrder(
                _storage,
                blockTimestamp,
                deadline,
                PositionOrder({
                    id: 0, // ignored
                    subAccountId: subAccountId,
                    collateral: collateralAmount,
                    size: size,
                    price: price,
                    profitTokenId: profitTokenId,
                    flags: flags,
                    placeOrderTime: 0, // ignored
                    expire10s: 0 // ignored
                })
            );
        }
    }

    function _placePositionOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        uint32 deadline, // 1e0. NOTE: deadline should be 0 for market order; > _blockTimestamp() for limit/trigger order
        PositionOrder memory order // NOTE: id, placeOrderTime, expire10s will be ignored
    ) private returns (uint64 newOrderId) {
        uint32 expire10s;
        if (deadline > 0) {
            expire10s = (deadline - blockTimestamp) / 10;
            require(expire10s <= type(uint24).max, "DTL"); // Deadline is Too Large
        }
        newOrderId = _storage.nextOrderId++;
        bytes32[3] memory newOrderData = LibOrder.encodePositionOrder(
            newOrderId,
            order.subAccountId,
            order.collateral,
            order.size,
            order.price,
            order.profitTokenId,
            order.flags,
            blockTimestamp,
            uint24(expire10s)
        );
        _storage.orders.add(newOrderId, newOrderData);
        emit NewPositionOrder(
            order.subAccountId,
            newOrderId,
            order.collateral,
            order.size,
            order.price,
            order.profitTokenId,
            order.flags,
            deadline
        );
    }

    function fillOpenPositionOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        uint64 orderId,
        uint96 collateralPrice,
        uint96 assetPrice,
        PositionOrder memory order
    ) external returns (uint96 tradingPrice) {
        // auto deposit
        uint96 collateralAmount = order.collateral;
        if (collateralAmount > 0) {
            IERC20Upgradeable collateral = IERC20Upgradeable(
                _storage.pool.getAssetAddress(order.subAccountId.getSubAccountCollateralId())
            );
            collateral.safeTransfer(address(_storage.pool), collateralAmount);
            _storage.pool.depositCollateral(order.subAccountId, collateralAmount);
        }
        // open
        tradingPrice = _storage.pool.openPosition(order.subAccountId, order.size, collateralPrice, assetPrice);
        // tp/sl strategy
        if (order.isTpslStrategy()) {
            PositionOrderExtra memory extra = _storage.positionOrderExtras[orderId];
            delete _storage.positionOrderExtras[orderId];
            _placeTpslOrdersWhenOpen(_storage, blockTimestamp, order, extra);
        }
    }

    function fillClosePositionOrder(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        uint64 orderId,
        uint96 collateralPrice,
        uint96 assetPrice,
        uint96 profitAssetPrice, // only used when !isLong
        PositionOrder memory order
    ) external returns (uint96 tradingPrice) {
        // check min profit
        SubAccount memory oldSubAccount;
        if (order.shouldReachMinProfit()) {
            (
                oldSubAccount.collateral,
                oldSubAccount.size,
                oldSubAccount.lastIncreasedTime,
                oldSubAccount.entryPrice,
                oldSubAccount.entryFunding
            ) = _storage.pool.getSubAccount(order.subAccountId);
        }
        // close
        tradingPrice = _storage.pool.closePosition(
            order.subAccountId,
            order.size,
            order.profitTokenId,
            collateralPrice,
            assetPrice,
            profitAssetPrice
        );
        // check min profit
        if (order.shouldReachMinProfit()) {
            require(_hasPassMinProfit(_storage, order, blockTimestamp, oldSubAccount, tradingPrice), "PFT"); // order must have ProFiT
        }
        // auto withdraw
        uint96 collateralAmount = order.collateral;
        if (collateralAmount > 0) {
            _storage.pool.withdrawCollateral(order.subAccountId, collateralAmount, collateralPrice, assetPrice);
        }
        // tp/sl strategy
        _storage.activatedTpslOrders[order.subAccountId].remove(uint256(orderId));
        // is the position completely closed
        (uint96 collateral, uint96 size, , , ) = _storage.pool.getSubAccount(order.subAccountId);
        if (size == 0) {
            // auto withdraw
            if (order.isWithdrawIfEmpty() && collateral > 0) {
                _storage.pool.withdrawAllCollateral(order.subAccountId);
            }

            // cancel activated tp/sl orders
            cancelActivatedTpslOrders(_storage, order.subAccountId);
        }
    }

    function _placeTpslOrdersWhenOpen(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        PositionOrder memory order,
        PositionOrderExtra memory extra
    ) private {
        if (extra.tpPrice > 0) {
            uint8 flags = LibOrder.POSITION_WITHDRAW_ALL_IF_EMPTY;
            uint8 assetId = order.subAccountId.getSubAccountAssetId();
            Asset memory asset = _storage.pool.getAssetInfo(assetId);
            if (asset.minProfitTime > 0) {
                flags |= LibOrder.POSITION_SHOULD_REACH_MIN_PROFIT;
            }
            uint64 orderId = _placePositionOrder(
                _storage,
                blockTimestamp,
                extra.tpslDeadline,
                PositionOrder({
                    id: 0, // ignored
                    subAccountId: order.subAccountId,
                    collateral: 0, // tp/sl strategy only supports POSITION_WITHDRAW_ALL_IF_EMPTY
                    size: order.size,
                    price: extra.tpPrice,
                    profitTokenId: extra.tpslProfitTokenId,
                    flags: flags,
                    placeOrderTime: 0, // ignored
                    expire10s: 0 // ignored
                })
            );
            _storage.activatedTpslOrders[order.subAccountId].add(uint256(orderId));
        }
        if (extra.slPrice > 0) {
            uint64 orderId = _placePositionOrder(
                _storage,
                blockTimestamp,
                extra.tpslDeadline,
                PositionOrder({
                    id: 0, // ignored
                    subAccountId: order.subAccountId,
                    collateral: 0, // tp/sl strategy only supports POSITION_WITHDRAW_ALL_IF_EMPTY
                    size: order.size,
                    price: extra.slPrice,
                    profitTokenId: extra.tpslProfitTokenId,
                    flags: LibOrder.POSITION_WITHDRAW_ALL_IF_EMPTY | LibOrder.POSITION_TRIGGER_ORDER,
                    placeOrderTime: 0, // ignored
                    expire10s: 0 // ignored
                })
            );
            _storage.activatedTpslOrders[order.subAccountId].add(uint256(orderId));
        }
    }

    function _placeTpslOrdersWhenClose(
        OrderBookStorage storage _storage,
        uint32 blockTimestamp,
        bytes32 subAccountId,
        uint96 size, // 1e18
        PositionOrderExtra memory extra
    ) private {
        if (extra.tpPrice > 0) {
            uint8 flags = LibOrder.POSITION_WITHDRAW_ALL_IF_EMPTY;
            uint8 assetId = subAccountId.getSubAccountAssetId();
            Asset memory asset = _storage.pool.getAssetInfo(assetId);
            if (asset.minProfitTime > 0) {
                flags |= LibOrder.POSITION_SHOULD_REACH_MIN_PROFIT;
            }
            uint64 orderId = _placePositionOrder(
                _storage,
                blockTimestamp,
                extra.tpslDeadline,
                PositionOrder({
                    id: 0, // ignored
                    subAccountId: subAccountId,
                    collateral: 0, // tp/sl strategy only supports POSITION_WITHDRAW_ALL_IF_EMPTY
                    size: size,
                    price: extra.tpPrice,
                    profitTokenId: extra.tpslProfitTokenId,
                    flags: flags,
                    placeOrderTime: 0, // ignored
                    expire10s: 0 // ignored
                })
            );
            _storage.activatedTpslOrders[subAccountId].add(uint256(orderId));
        }
        if (extra.slPrice > 0) {
            uint64 orderId = _placePositionOrder(
                _storage,
                blockTimestamp,
                extra.tpslDeadline,
                PositionOrder({
                    id: 0, // ignored
                    subAccountId: subAccountId,
                    collateral: 0, // tp/sl strategy only supports POSITION_WITHDRAW_ALL_IF_EMPTY
                    size: size,
                    price: extra.slPrice,
                    profitTokenId: extra.tpslProfitTokenId,
                    flags: LibOrder.POSITION_WITHDRAW_ALL_IF_EMPTY | LibOrder.POSITION_TRIGGER_ORDER,
                    placeOrderTime: 0, // ignored
                    expire10s: 0 // ignored
                })
            );
            _storage.activatedTpslOrders[subAccountId].add(uint256(orderId));
        }
    }

    function _hasPassMinProfit(
        OrderBookStorage storage _storage,
        PositionOrder memory order,
        uint32 blockTimestamp,
        SubAccount memory oldSubAccount,
        uint96 tradingPrice
    ) private view returns (bool) {
        if (oldSubAccount.size == 0) {
            return true;
        }
        LibSubAccount.DecodedSubAccountId memory decoded = order.subAccountId.decodeSubAccountId();
        require(tradingPrice > 0, "P=0"); // Price Is Zero
        bool hasProfit = decoded.isLong
            ? tradingPrice > oldSubAccount.entryPrice
            : tradingPrice < oldSubAccount.entryPrice;
        if (!hasProfit) {
            return true;
        }
        Asset memory asset = _storage.pool.getAssetInfo(decoded.assetId);
        if (blockTimestamp >= oldSubAccount.lastIncreasedTime + asset.minProfitTime) {
            return true;
        }
        uint96 priceDelta = tradingPrice >= oldSubAccount.entryPrice
            ? tradingPrice - oldSubAccount.entryPrice
            : oldSubAccount.entryPrice - tradingPrice;
        if (priceDelta >= uint256(oldSubAccount.entryPrice).rmul(asset.minProfitRate).safeUint96()) {
            return true;
        }
        return false;
    }
}

File 1 of 23 : LibSubAccount.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "../core/Types.sol";

/**
 * SubAccountId
 *         96             88        80       72        0
 * +---------+--------------+---------+--------+--------+
 * | Account | collateralId | assetId | isLong | unused |
 * +---------+--------------+---------+--------+--------+
 */
library LibSubAccount {
    bytes32 constant SUB_ACCOUNT_ID_FORBIDDEN_BITS = bytes32(uint256(0xffffffffffffffffff));

    function getSubAccountOwner(bytes32 subAccountId) internal pure returns (address account) {
        account = address(uint160(uint256(subAccountId) >> 96));
    }

    function getSubAccountCollateralId(bytes32 subAccountId) internal pure returns (uint8) {
        return uint8(uint256(subAccountId) >> 88);
    }

    function getSubAccountAssetId(bytes32 subAccountId) internal pure returns (uint8) {
        return uint8(uint256(subAccountId) >> 80);
    }

    function isLong(bytes32 subAccountId) internal pure returns (bool) {
        return uint8((uint256(subAccountId) >> 72)) > 0;
    }

    struct DecodedSubAccountId {
        address account;
        uint8 collateralId;
        uint8 assetId;
        bool isLong;
    }

    function decodeSubAccountId(bytes32 subAccountId) internal pure returns (DecodedSubAccountId memory decoded) {
        require((subAccountId & SUB_ACCOUNT_ID_FORBIDDEN_BITS) == 0, "AID"); // bad subAccount ID
        decoded.account = address(uint160(uint256(subAccountId) >> 96));
        decoded.collateralId = uint8(uint256(subAccountId) >> 88);
        decoded.assetId = uint8(uint256(subAccountId) >> 80);
        decoded.isLong = uint8((uint256(subAccountId) >> 72)) > 0;
    }
}

File 1 of 23 : Admin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "./Storage.sol";

contract Admin is Storage {
    event AddBroker(address indexed newBroker);
    event RemoveBroker(address indexed broker);
    event AddRebalancer(address indexed newRebalancer);
    event RemoveRebalancer(address indexed rebalancer);
    event SetLiquidityLockPeriod(uint32 oldLockPeriod, uint32 newLockPeriod);
    event SetOrderTimeout(uint32 marketOrderTimeout, uint32 maxLimitOrderTimeout);
    event PausePositionOrder(bool isPaused);
    event PauseLiquidityOrder(bool isPaused);
    event SetMaintainer(address indexed newMaintainer);
    event SetReferralManager(address newReferralManager);
    event SetAggregator(address indexed aggregatorAddress, bool isEnable);

    modifier onlyBroker() {
        require(_storage.brokers[_msgSender()], "BKR"); // only BroKeR
        _;
    }

    modifier onlyRebalancer() {
        require(_storage.rebalancers[_msgSender()], "BAL"); // only reBALancer
        _;
    }

    modifier onlyMaintainer() {
        require(_msgSender() == _storage.maintainer || _msgSender() == owner(), "S!M"); // Sender is Not MaiNTainer
        _;
    }

    function addBroker(address newBroker) external onlyMaintainer {
        require(!_storage.brokers[newBroker], "CHG"); // not CHanGed
        _storage.brokers[newBroker] = true;
        emit AddBroker(newBroker);
    }

    function removeBroker(address broker) external onlyMaintainer {
        _removeBroker(broker);
    }

    function renounceBroker() external {
        _removeBroker(msg.sender);
    }

    function addRebalancer(address newRebalancer) external onlyOwner {
        require(!_storage.rebalancers[newRebalancer], "CHG"); // not CHanGed
        _storage.rebalancers[newRebalancer] = true;
        emit AddRebalancer(newRebalancer);
    }

    function removeRebalancer(address rebalancer) external onlyOwner {
        _removeRebalancer(rebalancer);
    }

    function renounceRebalancer() external {
        _removeRebalancer(msg.sender);
    }

    function setLiquidityLockPeriod(uint32 newLiquidityLockPeriod) external onlyOwner {
        require(newLiquidityLockPeriod <= 86400 * 30, "LCK"); // LoCK time is too large
        require(_storage.liquidityLockPeriod != newLiquidityLockPeriod, "CHG"); // setting is not CHanGed
        emit SetLiquidityLockPeriod(_storage.liquidityLockPeriod, newLiquidityLockPeriod);
        _storage.liquidityLockPeriod = newLiquidityLockPeriod;
    }

    function setOrderTimeout(uint32 marketOrderTimeout_, uint32 maxLimitOrderTimeout_) external onlyOwner {
        require(marketOrderTimeout_ != 0, "T=0"); // Timeout Is Zero
        require(marketOrderTimeout_ / 10 <= type(uint24).max, "T>M"); // Timeout is Larger than Max
        require(maxLimitOrderTimeout_ != 0, "T=0"); // Timeout Is Zero
        require(maxLimitOrderTimeout_ / 10 <= type(uint24).max, "T>M"); // Timeout is Larger than Max
        require(
            _storage.marketOrderTimeout != marketOrderTimeout_ ||
                _storage.maxLimitOrderTimeout != maxLimitOrderTimeout_,
            "CHG"
        ); // setting is not CHanGed
        _storage.marketOrderTimeout = marketOrderTimeout_;
        _storage.maxLimitOrderTimeout = maxLimitOrderTimeout_;
        emit SetOrderTimeout(marketOrderTimeout_, maxLimitOrderTimeout_);
    }

    function pause(bool isPositionOrderPaused_, bool isLiquidityOrderPaused_) external onlyMaintainer {
        if (_storage.isPositionOrderPaused != isPositionOrderPaused_) {
            _storage.isPositionOrderPaused = isPositionOrderPaused_;
            emit PausePositionOrder(isPositionOrderPaused_);
        }
        if (_storage.isLiquidityOrderPaused != isLiquidityOrderPaused_) {
            _storage.isLiquidityOrderPaused = isLiquidityOrderPaused_;
            emit PauseLiquidityOrder(isLiquidityOrderPaused_);
        }
    }

    function setMaintainer(address newMaintainer) external onlyOwner {
        require(_storage.maintainer != newMaintainer, "CHG"); // not CHanGed
        _storage.maintainer = newMaintainer;
        emit SetMaintainer(newMaintainer);
    }

    function setReferralManager(address newReferralManager) external onlyOwner {
        require(newReferralManager != address(0), "ZAD");
        _storage.referralManager = newReferralManager;
        emit SetReferralManager(newReferralManager);
    }

    function setAggregator(address aggregatorAddress, bool isEnable) external onlyOwner {
        require(aggregatorAddress != address(0), "ZAD");
        _storage.aggregators[aggregatorAddress] = isEnable;
        emit SetAggregator(aggregatorAddress, isEnable);
    }

    function setCallbackGasLimit(uint256 gasLimit) external onlyOwner {
        _storage.callbackGasLimit = gasLimit;
    }

    function setCallbackWhitelist(address caller, bool enable) external onlyOwner {
        _storage.callbackWhitelist[caller] = enable;
    }

    function _removeBroker(address broker) internal {
        require(_storage.brokers[broker], "CHG"); // not CHanGed
        _storage.brokers[broker] = false;
        emit RemoveBroker(broker);
    }

    function _removeRebalancer(address rebalancer) internal {
        require(_storage.rebalancers[rebalancer], "CHG"); // not CHanGed
        _storage.rebalancers[rebalancer] = false;
        emit RemoveRebalancer(rebalancer);
    }
}

File 2 of 23 : Storage.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "../components/SafeOwnableUpgradeable.sol";
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IWETH9.sol";
import "../interfaces/INativeUnwrapper.sol";
import "../libraries/LibOrder.sol";

contract Storage is Initializable, SafeOwnableUpgradeable {
    bool private _reserved1; // this variable shares the same slot as SafeOwnableUpgradeable._pendingOwner
    OrderBookStorage internal _storage;
    bytes32[38] _gap;

    modifier whenPositionOrderEnabled() {
        require(!_storage.isPositionOrderPaused, "POP"); // Position Order Paused
        _;
    }

    modifier whenLiquidityOrderEnabled() {
        require(!_storage.isLiquidityOrderPaused, "LOP"); // Liquidity Order Paused
        _;
    }

    function brokers(address broker) external view returns (bool) {
        return _storage.brokers[broker];
    }

    function nextOrderId() external view returns (uint64) {
        return _storage.nextOrderId;
    }

    // 1e0
    function liquidityLockPeriod() external view returns (uint32) {
        return _storage.liquidityLockPeriod;
    }

    function rebalancers(address rebalancer) external view returns (bool) {
        return _storage.rebalancers[rebalancer];
    }

    function isPositionOrderPaused() external view returns (bool) {
        return _storage.isPositionOrderPaused;
    }

    function isLiquidityOrderPaused() external view returns (bool) {
        return _storage.isLiquidityOrderPaused;
    }

    function marketOrderTimeout() external view returns (uint32) {
        return _storage.marketOrderTimeout;
    }

    function maxLimitOrderTimeout() external view returns (uint32) {
        return _storage.maxLimitOrderTimeout;
    }

    function maintainer() external view returns (address) {
        return _storage.maintainer;
    }

    function referralManager() external view returns (address) {
        return _storage.referralManager;
    }

    function positionOrderExtras(uint64 orderId) external view returns (PositionOrderExtra memory) {
        return _storage.positionOrderExtras[orderId];
    }
}

File 2 of 23 : Types.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;

import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IWETH9.sol";
import "../interfaces/INativeUnwrapper.sol";
import "../libraries/LibOrder.sol";

enum OrderType {
    None, // 0
    PositionOrder, // 1
    LiquidityOrder, // 2
    WithdrawalOrder, // 3
    RebalanceOrder // 4
}

struct OrderBookStorage {
    mapping(address => bool) brokers;
    ILiquidityPool pool;
    uint64 nextOrderId;
    LibOrder.OrderList orders;
    IERC20Upgradeable mlp;
    IWETH weth;
    uint32 liquidityLockPeriod; // 1e0
    INativeUnwrapper nativeUnwrapper;
    mapping(address => bool) rebalancers;
    bool isPositionOrderPaused;
    bool isLiquidityOrderPaused;
    uint32 marketOrderTimeout;
    uint32 maxLimitOrderTimeout;
    address maintainer;
    address referralManager;
    mapping(uint64 => PositionOrderExtra) positionOrderExtras; // more strategy params for a position order
    mapping(bytes32 => EnumerableSetUpgradeable.UintSet) activatedTpslOrders;
    mapping(address => bool) aggregators; // aggregator can placeOrder for a user
    uint256 callbackGasLimit;
    mapping(address => bool) callbackWhitelist;
}

//                                  160        152       144         120        96   72   64               8        0
// +----------------------------------------------------------------------------------+--------------------+--------+
// |              subAccountId 184 (already shifted by 72bits)                        |     orderId 64     | type 8 |
// +----------------------------------+----------+---------+-----------+---------+---------+---------------+--------+
// |              size 96             | profit 8 | flags 8 | unused 24 | exp 24  | time 32 |      enumIndex 64      |
// +----------------------------------+----------+---------+-----------+---------+---------+---------------+--------+
// |             price 96             |                    collateral 96                   |        unused 64       |
// +----------------------------------+----------------------------------------------------+------------------------+
struct PositionOrder {
    uint64 id;
    bytes32 subAccountId; // 160 + 8 + 8 + 8 = 184
    uint96 collateral; // erc20.decimals
    uint96 size; // 1e18
    uint96 price; // 1e18
    uint8 profitTokenId;
    uint8 flags;
    uint32 placeOrderTime; // 1e0
    uint24 expire10s; // 10 seconds. deadline = placeOrderTime + expire * 10
}

struct PositionOrderExtra {
    // tp/sl strategy
    uint96 tpPrice; // take-profit price. decimals = 18. only valid when flags.POSITION_TPSL_STRATEGY.
    uint96 slPrice; // stop-loss price. decimals = 18. only valid when flags.POSITION_TPSL_STRATEGY.
    uint8 tpslProfitTokenId; // only valid when flags.POSITION_TPSL_STRATEGY.
    uint32 tpslDeadline; // only valid when flags.POSITION_TPSL_STRATEGY.
}

//                                  160       152       144          96          72    64              8        0
// +------------------------------------------------------------------+-----------+--------------------+--------+
// |                        account 160                               | unused 24 |     orderId 64     | type 8 |
// +----------------------------------+---------+---------+-----------+-----------+-----+--------------+--------+
// |             amount 96            | asset 8 | flags 8 | unused 48 |     time 32     |      enumIndex 64     |
// +----------------------------------+---------+---------+-----------+-----------------+-----------------------+
// |                                                 unused 256                                                 |
// +------------------------------------------------------------------------------------------------------------+
struct LiquidityOrder {
    uint64 id;
    address account;
    uint96 rawAmount; // erc20.decimals
    uint8 assetId;
    bool isAdding;
    uint32 placeOrderTime; // 1e0
}

//                                  160        152       144          96   72       64               8        0
// +------------------------------------------------------------------------+------------------------+--------+
// |              subAccountId 184 (already shifted by 72bits)              |       orderId 64       | type 8 |
// +----------------------------------+----------+---------+-----------+----+--------+---------------+--------+
// |             amount 96            | profit 8 | flags 8 | unused 48 |   time 32   |      enumIndex 64      |
// +----------------------------------+----------+---------+-----------+-------------+------------------------+
// |                                                unused 256                                                |
// +----------------------------------------------------------------------------------------------------------+
struct WithdrawalOrder {
    uint64 id;
    bytes32 subAccountId; // 160 + 8 + 8 + 8 = 184
    uint96 rawAmount; // erc20.decimals
    uint8 profitTokenId;
    bool isProfit;
    uint32 placeOrderTime; // 1e0
}

//                                          160       96      88      80        72    64                 8        0
// +---------------------------------------------------+-------+-------+----------+----------------------+--------+
// |                  rebalancer 160                   | id0 8 | id1 8 | unused 8 |      orderId 64      | type 8 |
// +------------------------------------------+--------+-------+-------+----------+----+-----------------+--------+
// |                amount0 96                |                amount1 96              |       enumIndex 64       |
// +------------------------------------------+----------------------------------------+--------------------------+
// |                                                 userData 256                                                 |
// +--------------------------------------------------------------------------------------------------------------+
struct RebalanceOrder {
    uint64 id;
    address rebalancer;
    uint8 tokenId0;
    uint8 tokenId1;
    uint96 rawAmount0; // erc20.decimals
    uint96 maxRawAmount1; // erc20.decimals
    bytes32 userData;
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/libraries/LibOrderBook.sol": {
      "LibOrderBook": "0x9897a73a606606394fa2324d16f3926f5963a9c3"
    }
  }
}

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newBroker","type":"address"}],"name":"AddBroker","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newRebalancer","type":"address"}],"name":"AddRebalancer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"enum OrderType","name":"orderType","type":"uint8"},{"indexed":false,"internalType":"bytes32[3]","name":"orderData","type":"bytes32[3]"}],"name":"CancelOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"enum OrderType","name":"orderType","type":"uint8"},{"indexed":false,"internalType":"bytes32[3]","name":"orderData","type":"bytes32[3]"}],"name":"FillOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"uint8","name":"assetId","type":"uint8"},{"indexed":false,"internalType":"uint96","name":"rawAmount","type":"uint96"},{"indexed":false,"internalType":"bool","name":"isAdding","type":"bool"}],"name":"NewLiquidityOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"indexed":true,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"uint96","name":"collateral","type":"uint96"},{"indexed":false,"internalType":"uint96","name":"size","type":"uint96"},{"indexed":false,"internalType":"uint96","name":"price","type":"uint96"},{"indexed":false,"internalType":"uint8","name":"profitTokenId","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"flags","type":"uint8"},{"indexed":false,"internalType":"uint32","name":"deadline","type":"uint32"}],"name":"NewPositionOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"indexed":true,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"uint96","name":"collateral","type":"uint96"},{"indexed":false,"internalType":"uint96","name":"size","type":"uint96"},{"indexed":false,"internalType":"uint96","name":"price","type":"uint96"},{"indexed":false,"internalType":"uint8","name":"profitTokenId","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"flags","type":"uint8"},{"indexed":false,"internalType":"uint32","name":"deadline","type":"uint32"},{"components":[{"internalType":"uint96","name":"tpPrice","type":"uint96"},{"internalType":"uint96","name":"slPrice","type":"uint96"},{"internalType":"uint8","name":"tpslProfitTokenId","type":"uint8"},{"internalType":"uint32","name":"tpslDeadline","type":"uint32"}],"indexed":false,"internalType":"struct PositionOrderExtra","name":"extra","type":"tuple"}],"name":"NewPositionOrderExtra","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rebalancer","type":"address"},{"indexed":true,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"uint8","name":"tokenId0","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"tokenId1","type":"uint8"},{"indexed":false,"internalType":"uint96","name":"rawAmount0","type":"uint96"},{"indexed":false,"internalType":"uint96","name":"maxRawAmount1","type":"uint96"},{"indexed":false,"internalType":"bytes32","name":"userData","type":"bytes32"}],"name":"NewRebalanceOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"indexed":true,"internalType":"uint64","name":"orderId","type":"uint64"},{"indexed":false,"internalType":"uint96","name":"rawAmount","type":"uint96"},{"indexed":false,"internalType":"uint8","name":"profitTokenId","type":"uint8"},{"indexed":false,"internalType":"bool","name":"isProfit","type":"bool"}],"name":"NewWithdrawalOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isPaused","type":"bool"}],"name":"PauseLiquidityOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isPaused","type":"bool"}],"name":"PausePositionOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"PrepareToTransferOwnership","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"broker","type":"address"}],"name":"RemoveBroker","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rebalancer","type":"address"}],"name":"RemoveRebalancer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"aggregatorAddress","type":"address"},{"indexed":false,"internalType":"bool","name":"isEnable","type":"bool"}],"name":"SetAggregator","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"oldLockPeriod","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"newLockPeriod","type":"uint32"}],"name":"SetLiquidityLockPeriod","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newMaintainer","type":"address"}],"name":"SetMaintainer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"marketOrderTimeout","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"maxLimitOrderTimeout","type":"uint32"}],"name":"SetOrderTimeout","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newReferralManager","type":"address"}],"name":"SetReferralManager","type":"event"},{"inputs":[{"internalType":"address","name":"newBroker","type":"address"}],"name":"addBroker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newRebalancer","type":"address"}],"name":"addRebalancer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"broker","type":"address"}],"name":"brokers","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"}],"name":"cancelOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimBrokerGasRebate","outputs":[{"internalType":"uint256","name":"rawAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"}],"name":"depositCollateral","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"},{"internalType":"uint96","name":"assetPrice","type":"uint96"},{"internalType":"uint96","name":"mlpPrice","type":"uint96"},{"internalType":"uint96","name":"currentAssetValue","type":"uint96"},{"internalType":"uint96","name":"targetAssetValue","type":"uint96"}],"name":"fillLiquidityOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"},{"internalType":"uint96","name":"collateralPrice","type":"uint96"},{"internalType":"uint96","name":"assetPrice","type":"uint96"},{"internalType":"uint96","name":"profitAssetPrice","type":"uint96"}],"name":"fillPositionOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"},{"internalType":"uint96","name":"price0","type":"uint96"},{"internalType":"uint96","name":"price1","type":"uint96"}],"name":"fillRebalanceOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"},{"internalType":"uint96","name":"collateralPrice","type":"uint96"},{"internalType":"uint96","name":"assetPrice","type":"uint96"},{"internalType":"uint96","name":"profitAssetPrice","type":"uint96"}],"name":"fillWithdrawalOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"}],"name":"getOrder","outputs":[{"internalType":"bytes32[3]","name":"","type":"bytes32[3]"},{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOrderCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"begin","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"}],"name":"getOrders","outputs":[{"internalType":"bytes32[3][]","name":"orderArray","type":"bytes32[3][]"},{"internalType":"uint256","name":"totalCount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"mlp","type":"address"},{"internalType":"address","name":"weth","type":"address"},{"internalType":"address","name":"nativeUnwrapper","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isLiquidityOrderPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isPositionOrderPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"internalType":"uint8","name":"profitAssetId","type":"uint8"},{"internalType":"uint96","name":"collateralPrice","type":"uint96"},{"internalType":"uint96","name":"assetPrice","type":"uint96"},{"internalType":"uint96","name":"profitAssetPrice","type":"uint96"}],"name":"liquidate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"liquidityLockPeriod","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maintainer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"marketOrderTimeout","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLimitOrderTimeout","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextOrderId","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"isPositionOrderPaused_","type":"bool"},{"internalType":"bool","name":"isLiquidityOrderPaused_","type":"bool"}],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"assetId","type":"uint8"},{"internalType":"uint96","name":"rawAmount","type":"uint96"},{"internalType":"bool","name":"isAdding","type":"bool"}],"name":"placeLiquidityOrder","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"internalType":"uint96","name":"collateralAmount","type":"uint96"},{"internalType":"uint96","name":"size","type":"uint96"},{"internalType":"uint96","name":"price","type":"uint96"},{"internalType":"uint8","name":"profitTokenId","type":"uint8"},{"internalType":"uint8","name":"flags","type":"uint8"},{"internalType":"uint32","name":"deadline","type":"uint32"},{"internalType":"bytes32","name":"referralCode","type":"bytes32"},{"components":[{"internalType":"uint96","name":"tpPrice","type":"uint96"},{"internalType":"uint96","name":"slPrice","type":"uint96"},{"internalType":"uint8","name":"tpslProfitTokenId","type":"uint8"},{"internalType":"uint32","name":"tpslDeadline","type":"uint32"}],"internalType":"struct PositionOrderExtra","name":"extra","type":"tuple"}],"name":"placePositionOrder3","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint8","name":"tokenId0","type":"uint8"},{"internalType":"uint8","name":"tokenId1","type":"uint8"},{"internalType":"uint96","name":"rawAmount0","type":"uint96"},{"internalType":"uint96","name":"maxRawAmount1","type":"uint96"},{"internalType":"bytes32","name":"userData","type":"bytes32"}],"name":"placeRebalanceOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"subAccountId","type":"bytes32"},{"internalType":"uint96","name":"rawAmount","type":"uint96"},{"internalType":"uint8","name":"profitTokenId","type":"uint8"},{"internalType":"bool","name":"isProfit","type":"bool"}],"name":"placeWithdrawalOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"orderId","type":"uint64"}],"name":"positionOrderExtras","outputs":[{"components":[{"internalType":"uint96","name":"tpPrice","type":"uint96"},{"internalType":"uint96","name":"slPrice","type":"uint96"},{"internalType":"uint8","name":"tpslProfitTokenId","type":"uint8"},{"internalType":"uint32","name":"tpslDeadline","type":"uint32"}],"internalType":"struct PositionOrderExtra","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"rebalancer","type":"address"}],"name":"rebalancers","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"tokenId","type":"uint8"},{"internalType":"uint96","name":"muxTokenAmount","type":"uint96"}],"name":"redeemMuxToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"referralManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"broker","type":"address"}],"name":"removeBroker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"rebalancer","type":"address"}],"name":"removeRebalancer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceBroker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceRebalancer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bool","name":"isEnable","type":"bool"}],"name":"setAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"gasLimit","type":"uint256"}],"name":"setCallbackGasLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"bool","name":"enable","type":"bool"}],"name":"setCallbackWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"newLiquidityLockPeriod","type":"uint32"}],"name":"setLiquidityLockPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newMaintainer","type":"address"}],"name":"setMaintainer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"marketOrderTimeout_","type":"uint32"},{"internalType":"uint32","name":"maxLimitOrderTimeout_","type":"uint32"}],"name":"setOrderTimeout","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newReferralManager","type":"address"}],"name":"setReferralManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"takeOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"stableUtilization","type":"uint32"},{"internalType":"uint8[]","name":"unstableTokenIds","type":"uint8[]"},{"internalType":"uint32[]","name":"unstableUtilizations","type":"uint32[]"},{"internalType":"uint96[]","name":"unstablePrices","type":"uint96[]"}],"name":"updateFundingState","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"subAccountId","type":"bytes32"}],"name":"withdrawAllCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"}]

608060405234801561001057600080fd5b5061550b806100206000396000f3fe6080604052600436106102935760003560e01c8063715018a61161015a578063c1488069116100c1578063dea9b4641161007a578063dea9b464146108c5578063ee8f99dc146108d8578063f2fde38b146108f5578063f8c8765e14610915578063fbb8d4ce14610935578063fe6facc41461094a57600080fd5b8063c1488069146107f7578063c5f3a4c414610817578063cdf9d07c14610837578063d0ee758c14610865578063d99d6f9a14610885578063ddeb5094146108a557600080fd5b8063942a5e7e11610113578063942a5e7e146106905780639850d32b1461074457806399a349521461076957806399e4ef5914610789578063a44d57a01461079e578063b4b9ef73146107d757600080fd5b8063715018a6146105cc578063836cae65146105e15780638a54942f146106015780638d0a5fbb146106215780638da5cb5b146106445780638f72fc771461066257600080fd5b80633d491e6f116101fe57806358b09b89116101b757806358b09b89146104fc5780635ac05a501461051c578063605361721461053c57806366874cc51461055157806366e10ec61461058a5780636b811a3c146105ac57600080fd5b80633d491e6f14610461578063431e5c9d1461048157806343bc4b9a146104965780634786055f146104b65780634af3e017146104c9578063523eb537146104dc57600080fd5b80632ccd9623116102505780632ccd96231461037b578063315dca6e146103ad578063330a4f9d146103cd578063337c96b4146103ff578063340e2d191461041f5780633d0ebb891461044157600080fd5b80630c9799191461029857806313ea5d29146102ba5780631666bcde146102da57806318a7a405146103035780631ad6a870146103235780632a58b33014610343575b600080fd5b3480156102a457600080fd5b506102b86102b3366004614474565b61096a565b005b3480156102c657600080fd5b506102b86102d5366004614474565b610a22565b3480156102e657600080fd5b50606e5460ff165b60405190151581526020015b60405180910390f35b34801561030f57600080fd5b506102b861031e36600461449f565b610ad7565b34801561032f57600080fd5b506102b861033e3660046144f5565b610b2c565b34801561034f57600080fd5b50606754600160a01b90046001600160401b03166040516001600160401b0390911681526020016102fa565b34801561038757600080fd5b50606f546001600160a01b03165b6040516001600160a01b0390911681526020016102fa565b3480156103b957600080fd5b506102b86103c836600461455a565b610d27565b3480156103d957600080fd5b50606e5462010000900463ffffffff165b60405163ffffffff90911681526020016102fa565b34801561040b57600080fd5b506102b861041a3660046145a3565b610f89565b34801561042b57600080fd5b50606b54600160a01b900463ffffffff166103ea565b34801561044d57600080fd5b506102b861045c366004614604565b611095565b34801561046d57600080fd5b506102b861047c3660046146c1565b61113b565b34801561048d57600080fd5b506102b86111d0565b3480156104a257600080fd5b506102b86104b1366004614474565b6111db565b6102b86104c4366004614703565b611211565b6102b86104d7366004614826565b61139e565b3480156104e857600080fd5b506102b86104f7366004614864565b61146f565b34801561050857600080fd5b506102b861051736600461487f565b61183b565b34801561052857600080fd5b506102b86105373660046148d9565b611bdc565b34801561054857600080fd5b506102b8611d6f565b34801561055d57600080fd5b506102ee61056c366004614474565b6001600160a01b031660009081526066602052604090205460ff1690565b34801561059657600080fd5b50606e54600160301b900463ffffffff166103ea565b3480156105b857600080fd5b506102b86105c7366004614939565b611dc9565b3480156105d857600080fd5b506102b8611e4d565b3480156105ed57600080fd5b506102b86105fc366004614474565b611e91565b34801561060d57600080fd5b506102b861061c366004614939565b611f65565b34801561062d57600080fd5b50610636611f94565b6040519081526020016102fa565b34801561065057600080fd5b506033546001600160a01b0316610395565b34801561066e57600080fd5b5061068261067d366004614952565b611fa4565b6040516102fa929190614974565b34801561069c57600080fd5b506107376106ab366004614864565b604080516080810182526000808252602082018190529181018290526060810191909152506001600160401b0316600090815260706020908152604091829020825160808101845290546001600160601b038082168352600160601b82041692820192909252600160c01b820460ff1692810192909252600160c81b900463ffffffff16606082015290565b6040516102fa91906149e4565b34801561075057600080fd5b50606e54600160501b90046001600160a01b0316610395565b34801561077557600080fd5b506102b861078436600461487f565b61209a565b34801561079557600080fd5b50610636612336565b3480156107aa57600080fd5b506102ee6107b9366004614474565b6001600160a01b03166000908152606d602052604090205460ff1690565b3480156107e357600080fd5b506102b86107f2366004614a29565b6123d3565b34801561080357600080fd5b506102b861081236600461449f565b612542565b34801561082357600080fd5b506102b8610832366004614474565b612607565b34801561084357600080fd5b50610857610852366004614864565b6126c1565b6040516102fa929190614a92565b34801561087157600080fd5b506102b8610880366004614aaf565b6126ea565b34801561089157600080fd5b506102b86108a0366004614474565b612a75565b3480156108b157600080fd5b506102b86108c0366004614b1e565b612acd565b6102b86108d3366004614952565b612bd4565b3480156108e457600080fd5b50606e54610100900460ff166102ee565b34801561090157600080fd5b506102b8610910366004614474565b612d3b565b34801561092157600080fd5b506102b8610930366004614b3c565b612e2f565b34801561094157600080fd5b506102b8612f69565b34801561095657600080fd5b506102b8610965366004614b8d565b612f72565b6033546001600160a01b0316331461099d5760405162461bcd60e51b815260040161099490614bb5565b60405180910390fd5b6001600160a01b0381166000908152606d602052604090205460ff16156109d65760405162461bcd60e51b815260040161099490614bea565b6001600160a01b0381166000818152606d6020526040808220805460ff19166001179055517fc5115f53265d15ca7930718dd520cd314285a7f2f0027e59b441f1f33b87b6919190a250565b6033546001600160a01b03163314610a4c5760405162461bcd60e51b815260040161099490614bb5565b606e546001600160a01b03828116600160501b909204161415610a815760405162461bcd60e51b815260040161099490614bea565b606e8054600160501b600160f01b031916600160501b6001600160a01b038416908102919091179091556040517f20495ad1c3942659031bc9602fe224bb567644c05306fe5656f04f0c5cd09ef590600090a250565b6033546001600160a01b03163314610b015760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b03919091166000908152607460205260409020805460ff1916911515919091179055565b6033546001600160a01b03163314610b565760405162461bcd60e51b815260040161099490614bb5565b63ffffffff8216610b8f5760405162461bcd60e51b81526020600482015260036024820152620543d360ec1b6044820152606401610994565b62ffffff610b9e600a84614c1d565b63ffffffff161115610bd85760405162461bcd60e51b8152602060048201526003602482015262543e4d60e81b6044820152606401610994565b63ffffffff8116610c115760405162461bcd60e51b81526020600482015260036024820152620543d360ec1b6044820152606401610994565b62ffffff610c20600a83614c1d565b63ffffffff161115610c5a5760405162461bcd60e51b8152602060048201526003602482015262543e4d60e81b6044820152606401610994565b606e5463ffffffff8381166201000090920416141580610c8c5750606e5463ffffffff828116600160301b9092041614155b610ca85760405162461bcd60e51b815260040161099490614bea565b606e805469ffffffffffffffff000019166201000063ffffffff85811691820269ffffffff000000000000191692909217600160301b928516928302179092556040805192835260208301919091527f0ac6ed41369d4003621c3216eaf4456c865743f8c396285512c18ac78150aaad91015b60405180910390a15050565b3360009081526066602052604090205460ff16610d565760405162461bcd60e51b815260040161099490614c4e565b606e54610100900460ff1615610d945760405162461bcd60e51b815260206004820152600360248201526204c4f560ec1b6044820152606401610994565b6002609b541415610db75760405162461bcd60e51b815260040161099490614c6b565b6002609b55610dc7606884613190565b610de35760405162461bcd60e51b815260040161099490614ca2565b6000610df06068856131b7565b9050610dfd60688561320c565b6000610e08826133b5565b90506004816004811115610e1e57610e1e614cbf565b14610e3b5760405162461bcd60e51b815260040161099490614cd5565b6040805160e0810182526000808252602080830182815283850183815260608086018581526080870186815260a080890188815260c08a018981528d5190951c968790528c5160581c60ff908116968790528d5160501c1693849052968c01805190911c9182905251891c6001600160601b03908116968790528b8a0151938490526067548a51639eee96df60e01b81526004810197909752602487019590955260448601929092526064850152608484019490945260a483015289831660c483015291881660e4820152935192936001600160a01b0390911692639eee96df926101048084019391929182900301818387803b158015610f3b57600080fd5b505af1158015610f4f573d6000803e3d6000fd5b505050506000805160206154b6833981519152868385604051610f7493929190614cf2565b60405180910390a150506001609b5550505050565b6033546001600160a01b03163314610fb35760405162461bcd60e51b815260040161099490614bb5565b62278d008163ffffffff161115610ff25760405162461bcd60e51b81526020600482015260036024820152624c434b60e81b6044820152606401610994565b606b5463ffffffff828116600160a01b9092041614156110245760405162461bcd60e51b815260040161099490614bea565b606b5460408051600160a01b90920463ffffffff9081168352831660208301527f0c0b8e3bb5e77c750110c5892a4426f766651572fc356dcff0300a53a79771e8910160405180910390a1606b805463ffffffff909216600160a01b0263ffffffff60a01b19909216919091179055565b3360009081526066602052604090205460ff166110c45760405162461bcd60e51b815260040161099490614c4e565b606754604051633d0ebb8960e01b81526001600160a01b0390911690633d0ebb8990611100908a908a908a908a908a908a908a90600401614d7c565b600060405180830381600087803b15801561111a57600080fd5b505af115801561112e573d6000803e3d6000fd5b5050505050505050505050565b60003360405163262d352160e21b8152606660048201526001600160a01b038216602482015260ff851660448201526001600160601b0384166064820152909150739897a73a606606394fa2324d16f3926f5963a9c3906398b4d4849060840160006040518083038186803b1580156111b357600080fd5b505af41580156111c7573d6000803e3d6000fd5b50505050505050565b6111d9336133ce565b565b6033546001600160a01b031633146112055760405162461bcd60e51b815260040161099490614bb5565b61120e8161344f565b50565b6002609b5414156112345760405162461bcd60e51b815260040161099490614c6b565b6002609b553360008181526072602052604090205460608b901c9060ff161561125c5761128d565b816001600160a01b0316816001600160a01b03161461128d5760405162461bcd60e51b815260040161099490614e27565b83158015906112a65750606f546001600160a01b031615155b1561131257606f5460405163bfb7d70d60e01b81526001600160a01b038381166004830152602482018790529091169063bfb7d70d90604401600060405180830381600087803b1580156112f957600080fd5b505af115801561130d573d6000803e3d6000fd5b505050505b739897a73a606606394fa2324d16f3926f5963a9c3630f40ab716066428e8e8e8e8e8e8e8d6040518b63ffffffff1660e01b815260040161135c9a99989796959493929190614e44565b60006040518083038186803b15801561137457600080fd5b505af4158015611388573d6000803e3d6000fd5b50506001609b5550505050505050505050505050565b6002609b5414156113c15760405162461bcd60e51b815260040161099490614c6b565b6002609b5560408051631e8fc0ef60e01b81526066600482015263ffffffff42166024820152336044820181905260ff861660648301526001600160601b038516608483015283151560a48301529151739897a73a606606394fa2324d16f3926f5963a9c391631e8fc0ef9160c4808301926000929190829003018186803b15801561144c57600080fd5b505af4158015611460573d6000803e3d6000fd5b50506001609b55505050505050565b6002609b5414156114925760405162461bcd60e51b815260040161099490614c6b565b6002609b556114a2606882613190565b6114be5760405162461bcd60e51b815260040161099490614ca2565b60006114cb6068836131b7565b90506114d860688361320c565b60006114e5825160601c90565b905060006114f2836133b5565b9050600181600481111561150857611508614cbf565b14156116a0576000611519846134d0565b3360009081526066602052604090205490915060ff161561156c5761153d81613587565b63ffffffff164263ffffffff16116115675760405162461bcd60e51b815260040161099490614eec565b611594565b336001600160a01b038416146115945760405162461bcd60e51b815260040161099490614e27565b60c0810151608016151580156115b75750600081604001516001600160601b0316115b1561165a5760675460208201516000916001600160a01b031690632d46c6c29060581c6040516001600160e01b031960e084901b16815260ff9091166004820152602401602060405180830381865afa158015611618573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061163c9190614f09565b90506116586066828685604001516001600160601b03166135ff565b505b6001600160401b038516600081815260706020908152604080832080546001600160e81b0319169055848201518352607190915290206116999161371c565b50506117ed565b60028160048111156116b4576116b4614cbf565b14156116fe57336001600160a01b038316146116e25760405162461bcd60e51b815260040161099490614e27565b60006116ed8461372f565b90506116f8816137d3565b506117ed565b600381600481111561171257611712614cbf565b14156117c3573360009081526066602052604090205460ff161561178c57600061173b84613935565b606e5460a082015191925060009161175f9162010000900463ffffffff1690614f26565b63ffffffff169050804263ffffffff16116116995760405162461bcd60e51b815260040161099490614eec565b6001600160a01b038216335b6001600160a01b0316146117be5760405162461bcd60e51b815260040161099490614e27565b6117ed565b60048160048111156117d7576117d7614cbf565b1415610293576001600160a01b03821633611798565b7fe5033f0fc6c1035c36f3d7c2b4278c1d0fc20d165ba0873a0ce56a661e8cf86684611818856133b5565b8560405161182893929190614cf2565b60405180910390a150506001609b555050565b3360009081526066602052604090205460ff1661186a5760405162461bcd60e51b815260040161099490614c4e565b606e5460ff16156118a35760405162461bcd60e51b81526020600482015260036024820152620504f560ec1b6044820152606401610994565b6002609b5414156118c65760405162461bcd60e51b815260040161099490614c6b565b6002609b556118d6606885613190565b6118f25760405162461bcd60e51b815260040161099490614ca2565b60006118ff6068866131b7565b905061190c60688661320c565b6000611917826133b5565b9050600181600481111561192d5761192d614cbf565b1461194a5760405162461bcd60e51b815260040161099490614cd5565b6000611955836134d0565b905061196081613587565b63ffffffff164263ffffffff16111561198b5760405162461bcd60e51b815260040161099490614eec565b600061199d8260c00151608016151590565b15611a2c5760405163352de4bb60e11b8152739897a73a606606394fa2324d16f3926f5963a9c390636a5bc976906119e49060669042908d908d908d908a90600401615006565b602060405180830381865af4158015611a01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a25919061504d565b9050611ab4565b604051630580dfb760e11b8152739897a73a606606394fa2324d16f3926f5963a9c390630b01bf6e90611a709060669042908d908d908d908d908b9060040161506a565b602060405180830381865af4158015611a8d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab1919061504d565b90505b60c0820151604016611ba4576000611ad28360c00151608016151590565b60208401519015159060481c60ff1615151515149050611af88360c00151601016151590565b15611aff57155b8015611b565782608001516001600160601b0316826001600160601b03161115611b515760405162461bcd60e51b815260206004820152600360248201526213135560ea1b6044820152606401610994565b611ba2565b82608001516001600160601b0316826001600160601b03161015611ba25760405162461bcd60e51b815260206004820152600360248201526213135560ea1b6044820152606401610994565b505b6000805160206154b6833981519152888486604051611bc593929190614cf2565b60405180910390a150506001609b55505050505050565b336000908152606d602052604090205460ff16611c215760405162461bcd60e51b815260206004820152600360248201526210905360ea1b6044820152606401610994565b6002609b541415611c445760405162461bcd60e51b815260040161099490614c6b565b6002609b556001600160601b038316611c855760405162461bcd60e51b81526020600482015260036024820152620413d360ec1b6044820152606401610994565b606780543391600091600160a01b90046001600160401b0316906014611caa836150c5565b91906101000a8154816001600160401b0302191690836001600160401b0316021790555090506000611ce182848a8a8a8a8a61397d565b9050611cef60688383613a0b565b6040805160ff8a81168252891660208201526001600160601b0388811682840152871660608201526080810186905290516001600160401b038416916001600160a01b038616917f5c1a7ceefa482bcc616dec79c7a8bb748520ec46eb6d550f10ecf97e70f1c96a9181900360a00190a350506001609b55505050505050565b6065546001600160a01b0316336001600160a01b031614611da25760405162461bcd60e51b815260040161099490614e27565b606554611db7906001600160a01b0316613b2f565b606580546001600160a01b0319169055565b606081901c3314611dec5760405162461bcd60e51b815260040161099490614e27565b606754604051631ae0468f60e21b8152600481018390526001600160a01b0390911690636b811a3c90602401600060405180830381600087803b158015611e3257600080fd5b505af1158015611e46573d6000803e3d6000fd5b5050505050565b6033546001600160a01b03163314611e775760405162461bcd60e51b815260040161099490614bb5565b606580546001600160a01b03191690556111d96000613b2f565b606e54600160501b90046001600160a01b0316336001600160a01b03161480611ec457506033546001600160a01b031633145b611ee05760405162461bcd60e51b8152600401610994906150ec565b6001600160a01b03811660009081526066602052604090205460ff1615611f195760405162461bcd60e51b815260040161099490614bea565b6001600160a01b038116600081815260666020526040808220805460ff19166001179055517f2fcbb5eda85b2352f87cce68063c290996e8cbc17c8f7c25a8b9ba1e59de256c9190a250565b6033546001600160a01b03163314611f8f5760405162461bcd60e51b815260040161099490614bb5565b607355565b6000611f9f60685490565b905090565b60606000611fb160685490565b90508284101580611fc25750808410155b15611fcc57612093565b80831115611fda5780611fdc565b825b92506000611fea8585615109565b9050806001600160401b03811115612004576120046146ed565b60405190808252806020026020018201604052801561203d57816020015b61202a6143ee565b8152602001906001900390816120225790505b50925060005b81811015612090576120606120588783615120565b606890613b81565b84828151811061207257612072615138565b602002602001018190525080806120889061514e565b915050612043565b50505b9250929050565b3360009081526066602052604090205460ff166120c95760405162461bcd60e51b815260040161099490614c4e565b6002609b5414156120ec5760405162461bcd60e51b815260040161099490614c6b565b6002609b556120fc606885613190565b6121185760405162461bcd60e51b815260040161099490614ca2565b60006121256068866131b7565b905061213260688661320c565b600061213d826133b5565b9050600381600481111561215357612153614cbf565b146121705760405162461bcd60e51b815260040161099490614cd5565b600061217b83613935565b606e5460a082015191925061219d916201000090910463ffffffff1690614f26565b63ffffffff164263ffffffff1611156121c85760405162461bcd60e51b815260040161099490614eec565b8060800151156122765760675460208201516040808401516060850151915163484289c760e01b815260048101939093526001600160601b03908116602484015260ff909116604483015280891660648301528088166084830152861660a48201526001600160a01b039091169063484289c79060c401600060405180830381600087803b15801561225957600080fd5b505af115801561226d573d6000803e3d6000fd5b505050506122ff565b60675460208201516040808401519051634700832960e11b815260048101929092526001600160601b0390811660248301528089166044830152871660648201526001600160a01b0390911690638e01065290608401600060405180830381600087803b1580156122e657600080fd5b505af11580156122fa573d6000803e3d6000fd5b505050505b6000805160206154b683398151915287838560405161232093929190614cf2565b60405180910390a150506001609b555050505050565b3360009081526066602052604081205460ff166123655760405162461bcd60e51b815260040161099490614c4e565b606754604051636bc72faf60e11b81523360048201526001600160a01b039091169063d78e5f5e906024016020604051808303816000875af11580156123af573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f9f9190615169565b6002609b5414156123f65760405162461bcd60e51b815260040161099490614c6b565b6002609b5560006124078560601c90565b90506001600160a01b03811633146124315760405162461bcd60e51b815260040161099490614e27565b6001600160601b03841661246d5760405162461bcd60e51b81526020600482015260036024820152620413d360ec1b6044820152606401610994565b60678054600091600160a01b9091046001600160401b0316906014612491836150c5565b91906101000a8154816001600160401b0302191690836001600160401b03160217905550905060006124cd82888888886124c84290565b613c43565b90506124db60688383613a0b565b604080516001600160601b038816815260ff871660208201528515158183015290516001600160401b0384169189917f201d03547a8fd1f2eaa0fda90af89681a6c4dc6a8e495565e5ca6a62b3579cf09181900360600190a350506001609b555050505050565b6033546001600160a01b0316331461256c5760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b0382166125a85760405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606401610994565b6001600160a01b038216600081815260726020908152604091829020805460ff191685151590811790915591519182527f9aaad5d73fc4de1befd3e790b855dfdc6363f068e93abfdf01ad70681d31d0ce910160405180910390a25050565b6033546001600160a01b031633146126315760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b03811661266d5760405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606401610994565b606f80546001600160a01b0319166001600160a01b0383169081179091556040519081527f57202bce87a87010e83825477a341d777f701216d3e2a3b4642c72d9e8a931989060200160405180910390a150565b6126c96143ee565b60006126d66068846131b7565b6126e1606885613190565b91509150915091565b3360009081526066602052604090205460ff166127195760405162461bcd60e51b815260040161099490614c4e565b606e54610100900460ff16156127575760405162461bcd60e51b815260206004820152600360248201526204c4f560ec1b6044820152606401610994565b6002609b54141561277a5760405162461bcd60e51b815260040161099490614c6b565b6002609b5561278a606886613190565b6127a65760405162461bcd60e51b815260040161099490614ca2565b60006127b36068876131b7565b90506127c060688761320c565b60006127cb8261372f565b6020808201516001600160a01b031660009081526074909152604090205490915060ff16156128dc57600081602001516001600160a01b031663be49f64a612811613d08565b848a8a8a8a6040518763ffffffff1660e01b81526004016128369594939291906151df565b60206040518083038160008887f193505050508015612872575060408051601f3d908101601f1916820190925261286f91810190615221565b60015b61287e57506000612881565b90505b806128da5761288f826137d3565b7fe5033f0fc6c1035c36f3d7c2b4278c1d0fc20d165ba0873a0ce56a661e8cf866886128ba856133b5565b856040516128ca93929190614cf2565b60405180910390a1505050612a69565b505b60006128e7836133b5565b905060028160048111156128fd576128fd614cbf565b1461291a5760405162461bcd60e51b815260040161099490614cd5565b604051636cc4fd9560e11b8152600090739897a73a606606394fa2324d16f3926f5963a9c39063d989fb2a906129619060669042908d908d908d908d908d9060040161523e565b602060405180830381865af415801561297e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129a29190615169565b6020808501516001600160a01b031660009081526074909152604090205490915060ff1615612a3b5782602001516001600160a01b0316639c69c2e16129e6613d08565b85848c8c8c8c6040518863ffffffff1660e01b8152600401612a0d969594939291906152b3565b600060405180830381600088803b158015612a2757600080fd5b5087f193505050508015612a39575060015b505b6000805160206154b6833981519152898386604051612a5c93929190614cf2565b60405180910390a1505050505b50506001609b55505050565b606e54600160501b90046001600160a01b0316336001600160a01b03161480612aa857506033546001600160a01b031633145b612ac45760405162461bcd60e51b8152600401610994906150ec565b61120e816133ce565b606e54600160501b90046001600160a01b0316336001600160a01b03161480612b0057506033546001600160a01b031633145b612b1c5760405162461bcd60e51b8152600401610994906150ec565b606e5460ff16151582151514612b7157606e805460ff19168315159081179091556040519081527ff08d1ca9cf739c5ed2fcedf748abbfa8f14006e47f4a0a3805e6ce8ace2411229060200160405180910390a15b606e5460ff61010090910416151581151514612bd057606e80548215156101000261ff00199091161790556040517f1dd885054d26280b4f25ebb658ef23327620ee20f5ad56b33902e87f8ad65bba90610d1b90831515815260200190565b5050565b6000612bdf83613d20565b80519091506001600160a01b03163314612c0b5760405162461bcd60e51b815260040161099490614e27565b81612c3e5760405162461bcd60e51b81526020600482015260036024820152620433d360ec1b6044820152606401610994565b60675460208201516040516316a3636160e11b815260ff90911660048201526000916001600160a01b031690632d46c6c290602401602060405180830381865afa158015612c90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cb49190614f09565b9050612cd060663360675484906001600160a01b031687613db9565b6067546040516337aa6d1960e21b815260048101869052602481018590526001600160a01b039091169063dea9b46490604401600060405180830381600087803b158015612d1d57600080fd5b505af1158015612d31573d6000803e3d6000fd5b5050505050505050565b6033546001600160a01b03163314612d655760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b038116612da15760405162461bcd60e51b815260206004820152600360248201526204f3d360ec1b6044820152606401610994565b6033546001600160a01b0382811691161415612de55760405162461bcd60e51b81526020600482015260036024820152624f3d4f60e81b6044820152606401610994565b606580546001600160a01b0319166001600160a01b0383169081179091556040517fb501f5dc3610d10a179d924f686fc89ddcdd3abb05afd7a1baeead166b2f122c90600090a250565b600054610100900460ff16612e4a5760005460ff1615612e4e565b303b155b612eb15760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610994565b600054610100900460ff16158015612ed3576000805461ffff19166101011790555b612edb613f57565b606780546001600160a01b03199081166001600160a01b0388811691909117909255606a80548216878416179055606b80548216868416179055606c805490911684831617905560335416606e80546001600160a01b0392909216600160501b02600160501b600160f01b03199092169190911790558015611e46576000805461ff00191690555050505050565b6111d93361344f565b3360009081526066602052604090205460ff16612fa15760405162461bcd60e51b815260040161099490614c4e565b606754604051633f9beb3160e21b81526004810187905260ff861660248201526001600160601b0380861660448301528085166064830152831660848201526001600160a01b039091169063fe6facc49060a4016020604051808303816000875af1158015613014573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613038919061504d565b506067546040516303e9375760e01b8152600481018790526000916001600160a01b0316906303e937579060240160a060405180830381865afa158015613083573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130a791906152fb565b5050505090506000816001600160601b0316111561311e57606754604051631ae0468f60e21b8152600481018890526001600160a01b0390911690636b811a3c90602401600060405180830381600087803b15801561310557600080fd5b505af1158015613119573d6000803e3d6000fd5b505050505b6040516342f4ff7160e11b81526066600482015260248101879052739897a73a606606394fa2324d16f3926f5963a9c3906385e9fee29060440160006040518083038186803b15801561317057600080fd5b505af4158015613184573d6000803e3d6000fd5b50505050505050505050565b6001600160401b038116600090815260018381016020526040909120015415155b92915050565b6131bf6143ee565b6001600160401b038216600090815260018401602052604090819020815160608101928390529160039082845b8154815260200190600101908083116131ec575050505050905092915050565b6001600160401b0381166000908152600180840160205260408220919082015490506001600160401b0381166132545760405162461bcd60e51b815260040161099490614ca2565b6000613261600183615377565b85546001600160401b0391909116915060009061328090600190615109565b90508181146133475760008660000182815481106132a0576132a0615138565b90600052602060002090600491828204019190066008029054906101000a90046001600160401b03169050808760000184815481106132e1576132e1615138565b600091825260208083206004830401805460039093166008026101000a6001600160401b03818102199094169584160294909417909355838116825260018a81019093526040909120919086169067ffffffffffffffff19908301541617816001015550505b85548690806133585761335861539f565b600082815260208082206004600019949094019384040180546001600160401b03600860038716026101000a8102199091169091559290935596168652600196870190525050604083208381559384018390555050600290910155565b805160009060ff1660048111156131b1576131b1614cbf565b6001600160a01b03811660009081526066602052604090205460ff166134065760405162461bcd60e51b815260040161099490614bea565b6001600160a01b038116600081815260666020526040808220805460ff19169055517fcdf53ae488d66a98f509e3342bdc0a13dee821f05bfb372351346a7a991df7a29190a250565b6001600160a01b0381166000908152606d602052604090205460ff166134875760405162461bcd60e51b815260040161099490614bea565b6001600160a01b0381166000818152606d6020526040808220805460ff19169055517f963257db523ad7beed5ed8d412d9efcfa2ec8b73e3c20c3aaf5b6161f9ec48119190a250565b60408051610120810182526000808252602080830182815283850183815260608086018581526080870186815260a080890188815260c08a0189815260e08b018a81526101008c019a8b528d5168ffffffffffffffffff19169098528c8c0180518d1c6001600160601b03169097529b9097018051821c909352825160901c60ff908116909b52935190931c909252815160981c909716909252815190951c62ffffff169091525190911c63ffffffff1690915290565b60006135998260c00151604016151590565b156135bc57606e5460e08301516131b19162010000900463ffffffff1690614f26565b6135eb82610100015162ffffff16600a6135d691906153b5565b606e54600160301b900463ffffffff16613f86565b8260e001516131b19190614f26565b919050565b60058401546001600160a01b0384811691161415613702576005840154600685015460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303816000875af1158015613670573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136949190615221565b5060068401546040516339f4769360e01b81526001600160a01b03848116600483015260248201849052909116906339f4769390604401600060405180830381600087803b1580156136e557600080fd5b505af11580156136f9573d6000803e3d6000fd5b50505050613716565b6137166001600160a01b0384168383613fa9565b50505050565b60006137288383614011565b9392505050565b6040805160c08101825260008082526020820181815292820181905260608083018290526080830182905260a0830191909152835160081c6001600160401b031682528351901c9091528160015b602002015160a01c604082015260608260016020020151901b60f81c6060820152600060688360016020020151901b60f81c8015156080840152905060a08360016020020151901b60e01c60a083015250919050565b8060800151156138795760675460608201516040516316a3636160e11b815260ff90911660048201526000916001600160a01b031690632d46c6c290602401602060405180830381865afa15801561382f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138539190614f09565b9050613873606682846020015185604001516001600160601b03166135ff565b506138a4565b60208101516040820151606a546138a4926001600160a01b03909116916001600160601b0316613fa9565b6020808201516001600160a01b031660009081526074909152604090205460ff161561120e5780602001516001600160a01b031663463cde3a6138e5613d08565b836040518363ffffffff1660e01b815260040161390291906153e1565b600060405180830381600088803b15801561391c57600080fd5b5087f19350505050801561392e575060015b61120e5750565b6040805160c081018252600080825260208201818152928201819052606082018190526080820181905260a0820152825168ffffffffffffffffff191690915281600161377d565b6139856143ee565b60089790971b68ffffffffffffffff001660509490941b60ff60501b1660589590951b60ff60581b1660609690961b6bffffffffffffffffffffffff19169590951793909317919091176004178452604091821b73ffffffffffffffffffffffff00000000000000001660a09190911b6001600160a01b03191617602084015282015290565b613a158383613190565b15613a485760405162461bcd60e51b815260206004820152600360248201526204455560ec1b6044820152606401610994565b82546001810184556000848152602090206004820401805460039092166008026101000a6001600160401b038181021990931685841691909102179055835490811115613abd5760405162461bcd60e51b815260206004820152600360248201526213cd8d60ea1b6044820152606401610994565b60208201516001600160401b031615613afe5760405162461bcd60e51b81526020600482015260036024820152622798a360e91b6044820152606401610994565b60208083018051831790526001600160401b03841660009081526001860190915260409020611e469083600361440c565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b613b896143ee565b82548210613bbf5760405162461bcd60e51b815260206004820152600360248201526209288b60eb1b6044820152606401610994565b6000836000018381548110613bd657613bd6615138565b6000918252602080832060048304015460039283166008026101000a90046001600160401b03168084526001880190915260409283902083516060810194859052919450909290919082845b815481526020019060010190808311613c2257505050505091505092915050565b613c4b6143ee565b68ffffffffffffffffff861615613c8a5760405162461bcd60e51b815260206004820152600360248201526210525160ea1b6044820152606401610994565b600083613c98576000613c9b565b60015b9050600368ffffffffffffffff0060088a901b1688171782600060200201526001600160a01b031960a087901b1660ff60981b609887901b161760ff60901b609083901b16176bffffffff0000000000000000604085901b16178260016020020152509695505050505050565b60735460009015613d1a575060735490565b5a905090565b60408051608081018252600080825260208201819052918101829052606081019190915268ffffffffffffffffff821615613d835760405162461bcd60e51b815260206004820152600360248201526210525160ea1b6044820152606401610994565b606082811c825260ff605884901c81166020840152605084901c8116604084015260489390931c90921615159181019190915290565b60058501546001600160a01b0384811691161415613f0e57600034118015613de057508034145b613e125760405162461bcd60e51b815260206004820152600360248201526215905360ea1b6044820152606401610994565b8460050160009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b158015613e6457600080fd5b505af1158015613e78573d6000803e3d6000fd5b505050506001600160a01b03831630149050613f0957600585015460405163a9059cbb60e01b81526001600160a01b038481166004830152602482018490529091169063a9059cbb906044016020604051808303816000875af1158015613ee3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f079190615221565b505b611e46565b3415613f425760405162461bcd60e51b815260206004820152600360248201526215905360ea1b6044820152606401610994565b611e466001600160a01b038416858484614104565b600054610100900460ff16613f7e5760405162461bcd60e51b8152600401610994906153ef565b6111d961413c565b60008163ffffffff168363ffffffff161115613fa25781613728565b5090919050565b6040516001600160a01b03831660248201526044810182905261400c90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261416b565b505050565b600081815260018301602052604081205480156140fa576000614035600183615109565b855490915060009061404990600190615109565b90508181146140ae57600086600001828154811061406957614069615138565b906000526020600020015490508087600001848154811061408c5761408c615138565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806140bf576140bf61539f565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506131b1565b60009150506131b1565b6040516001600160a01b03808516602483015283166044820152606481018290526137169085906323b872dd60e01b90608401613fd5565b600054610100900460ff166141635760405162461bcd60e51b8152600401610994906153ef565b6111d961423d565b60006141c0826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661426d9092919063ffffffff16565b80519091501561400c57808060200190518101906141de9190615221565b61400c5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610994565b600054610100900460ff166142645760405162461bcd60e51b8152600401610994906153ef565b6111d933613b2f565b606061427c8484600085614284565b949350505050565b6060824710156142e55760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610994565b6001600160a01b0385163b61433c5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610994565b600080866001600160a01b031685876040516143589190615466565b60006040518083038185875af1925050503d8060008114614395576040519150601f19603f3d011682016040523d82523d6000602084013e61439a565b606091505b50915091506143aa8282866143b5565b979650505050505050565b606083156143c4575081613728565b8251156143d45782518084602001fd5b8160405162461bcd60e51b81526004016109949190615482565b60405180606001604052806003906020820280368337509192915050565b826003810192821561443a579160200282015b8281111561443a57825182559160200191906001019061441f565b5061444692915061444a565b5090565b5b80821115614446576000815560010161444b565b6001600160a01b038116811461120e57600080fd5b60006020828403121561448657600080fd5b81356137288161445f565b801515811461120e57600080fd5b600080604083850312156144b257600080fd5b82356144bd8161445f565b915060208301356144cd81614491565b809150509250929050565b63ffffffff8116811461120e57600080fd5b80356135fa816144d8565b6000806040838503121561450857600080fd5b8235614513816144d8565b915060208301356144cd816144d8565b80356001600160401b03811681146135fa57600080fd5b6001600160601b038116811461120e57600080fd5b80356135fa8161453a565b60008060006060848603121561456f57600080fd5b61457884614523565b925060208401356145888161453a565b915060408401356145988161453a565b809150509250925092565b6000602082840312156145b557600080fd5b8135613728816144d8565b60008083601f8401126145d257600080fd5b5081356001600160401b038111156145e957600080fd5b6020830191508360208260051b850101111561209357600080fd5b60008060008060008060006080888a03121561461f57600080fd5b873561462a816144d8565b965060208801356001600160401b038082111561464657600080fd5b6146528b838c016145c0565b909850965060408a013591508082111561466b57600080fd5b6146778b838c016145c0565b909650945060608a013591508082111561469057600080fd5b5061469d8a828b016145c0565b989b979a50959850939692959293505050565b803560ff811681146135fa57600080fd5b600080604083850312156146d457600080fd5b6146dd836146b0565b915060208301356144cd8161453a565b634e487b7160e01b600052604160045260246000fd5b6000806000806000806000806000898b0361018081121561472357600080fd5b8a35995060208b01356147358161453a565b985060408b01356147458161453a565b975060608b01356147558161453a565b965061476360808c016146b0565b955061477160a08c016146b0565b945060c08b0135614781816144d8565b935060e08b01359250608060ff198201121561479c57600080fd5b50604051608081018181106001600160401b03821117156147cd57634e487b7160e01b600052604160045260246000fd5b6040526147dd6101008c0161454f565b81526147ec6101208c0161454f565b60208201526147fe6101408c016146b0565b60408201526148106101608c016144ea565b6060820152809150509295985092959850929598565b60008060006060848603121561483b57600080fd5b614844846146b0565b925060208401356148548161453a565b9150604084013561459881614491565b60006020828403121561487657600080fd5b61372882614523565b6000806000806080858703121561489557600080fd5b61489e85614523565b935060208501356148ae8161453a565b925060408501356148be8161453a565b915060608501356148ce8161453a565b939692955090935050565b600080600080600060a086880312156148f157600080fd5b6148fa866146b0565b9450614908602087016146b0565b935060408601356149188161453a565b925060608601356149288161453a565b949793965091946080013592915050565b60006020828403121561494b57600080fd5b5035919050565b6000806040838503121561496557600080fd5b50508035926020909101359150565b6040808252835190820181905260009060609081840190602080880185805b848110156149d057825186835b60038110156149bd578251825291860191908601906001016149a0565b5050509486019491830191600101614993565b505050949094019490945250919392505050565b608081016131b182846001600160601b038082511683528060208301511660208401525060ff604082015116604083015263ffffffff60608201511660608301525050565b60008060008060808587031215614a3f57600080fd5b843593506020850135614a518161453a565b9250614a5f604086016146b0565b915060608501356148ce81614491565b8060005b6003811015613716578151845260209384019390910190600101614a73565b60808101614aa08285614a6f565b82151560608301529392505050565b600080600080600060a08688031215614ac757600080fd5b614ad086614523565b94506020860135614ae08161453a565b93506040860135614af08161453a565b92506060860135614b008161453a565b91506080860135614b108161453a565b809150509295509295909350565b60008060408385031215614b3157600080fd5b82356144bd81614491565b60008060008060808587031215614b5257600080fd5b8435614b5d8161445f565b93506020850135614b6d8161445f565b92506040850135614b7d8161445f565b915060608501356148ce8161445f565b600080600080600060a08688031215614ba557600080fd5b85359450614ae0602087016146b0565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b60208082526003908201526243484760e81b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff80841680614c4257634e487b7160e01b600052601260045260246000fd5b92169190910492915050565b6020808252600390820152622125a960e91b604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526003908201526213d25160ea1b604082015260600190565b634e487b7160e01b600052602160045260246000fd5b60208082526003908201526205459560ec1b604082015260600190565b6001600160401b038416815260a0810160058410614d2057634e487b7160e01b600052602160045260246000fd5b83602083015261427c6040830184614a6f565b8183526000602080850194508260005b85811015614d71578135614d568161453a565b6001600160601b031687529582019590820190600101614d43565b509495945050505050565b63ffffffff888116825260806020808401829052908301889052600091899160a08501845b8b811015614dc75760ff614db4866146b0565b1682529382019390820190600101614da1565b508581036040870152888152810192508860005b89811015614e02578135614dee816144d8565b841685529382019390820190600101614ddb565b505050508281036060840152614e19818587614d33565b9a9950505050505050505050565b60208082526003908201526214d39160ea1b604082015260600190565b8a815263ffffffff8a81166020830152604082018a90526001600160601b0389811660608401528881166080840152871660a083015260ff86811660c0840152851660e083015283166101008201526101a08101614edd6101208301846001600160601b038082511683528060208301511660208401525060ff604082015116604083015263ffffffff60608201511660608301525050565b9b9a5050505050505050505050565b60208082526003908201526204558560ec1b604082015260600190565b600060208284031215614f1b57600080fd5b81516137288161445f565b600063ffffffff808316818516808303821115614f4557614f45614c07565b01949350505050565b6001600160401b038151168252602081015160208301526001600160601b0360408201511660408301526060810151614f9260608401826001600160601b03169052565b506080810151614fad60808401826001600160601b03169052565b5060a0810151614fc260a084018260ff169052565b5060c0810151614fd760c084018260ff169052565b5060e0810151614fef60e084018263ffffffff169052565b506101008181015162ffffff811684830152613716565b86815263ffffffff861660208201526001600160401b03851660408201526001600160601b038481166060830152831660808201526101c081016143aa60a0830184614f4e565b60006020828403121561505f57600080fd5b81516137288161453a565b87815263ffffffff871660208201526001600160401b03861660408201526001600160601b0385811660608301528481166080830152831660a08201526101e081016150b960c0830184614f4e565b98975050505050505050565b60006001600160401b03808316818114156150e2576150e2614c07565b6001019392505050565b60208082526003908201526253214d60e81b604082015260600190565b60008282101561511b5761511b614c07565b500390565b6000821982111561513357615133614c07565b500190565b634e487b7160e01b600052603260045260246000fd5b600060001982141561516257615162614c07565b5060010190565b60006020828403121561517b57600080fd5b5051919050565b80516001600160401b031682526020808201516001600160a01b0316908301526040808201516001600160601b03169083015260608082015160ff169083015260808082015115159083015260a09081015163ffffffff16910152565b61014081016151ee8288615182565b6001600160601b0395861660c083015293851660e082015291841661010083015290921661012090920191909152919050565b60006020828403121561523357600080fd5b815161372881614491565b87815263ffffffff87166020808301919091526001600160601b03878116604084015286811660608401528581166080840152841660a083015261012082019060c083018460005b60038110156152a357815183529183019190830190600101615286565b5050505098975050505050505050565b61016081016152c28289615182565b60c08201969096526001600160601b0394851660e082015292841661010084015290831661012083015290911661014090910152919050565b600080600080600060a0868803121561531357600080fd5b855161531e8161453a565b602087015190955061532f8161453a565b6040870151909450615340816144d8565b60608701519093506153518161453a565b60808701519092506fffffffffffffffffffffffffffffffff81168114614b1057600080fd5b60006001600160401b038381169083168181101561539757615397614c07565b039392505050565b634e487b7160e01b600052603160045260246000fd5b600063ffffffff808316818516818304811182151516156153d8576153d8614c07565b02949350505050565b60c081016131b18284615182565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b60005b8381101561545557818101518382015260200161543d565b838111156137165750506000910152565b6000825161547881846020870161543a565b9190910192915050565b60208152600082518060208401526154a181604085016020870161543a565b601f01601f1916919091016040019291505056fe6204728db10730656ada9f8ce5b258b0d97dc6ac8e8a101ff4b905c3c9cc7dc5a26469706673582212200650f8dfd5e86abc5b690115a26b6357e3485afda7ad5dda2d8730d9cca3fe0964736f6c634300080a0033

Deployed Bytecode

0x6080604052600436106102935760003560e01c8063715018a61161015a578063c1488069116100c1578063dea9b4641161007a578063dea9b464146108c5578063ee8f99dc146108d8578063f2fde38b146108f5578063f8c8765e14610915578063fbb8d4ce14610935578063fe6facc41461094a57600080fd5b8063c1488069146107f7578063c5f3a4c414610817578063cdf9d07c14610837578063d0ee758c14610865578063d99d6f9a14610885578063ddeb5094146108a557600080fd5b8063942a5e7e11610113578063942a5e7e146106905780639850d32b1461074457806399a349521461076957806399e4ef5914610789578063a44d57a01461079e578063b4b9ef73146107d757600080fd5b8063715018a6146105cc578063836cae65146105e15780638a54942f146106015780638d0a5fbb146106215780638da5cb5b146106445780638f72fc771461066257600080fd5b80633d491e6f116101fe57806358b09b89116101b757806358b09b89146104fc5780635ac05a501461051c578063605361721461053c57806366874cc51461055157806366e10ec61461058a5780636b811a3c146105ac57600080fd5b80633d491e6f14610461578063431e5c9d1461048157806343bc4b9a146104965780634786055f146104b65780634af3e017146104c9578063523eb537146104dc57600080fd5b80632ccd9623116102505780632ccd96231461037b578063315dca6e146103ad578063330a4f9d146103cd578063337c96b4146103ff578063340e2d191461041f5780633d0ebb891461044157600080fd5b80630c9799191461029857806313ea5d29146102ba5780631666bcde146102da57806318a7a405146103035780631ad6a870146103235780632a58b33014610343575b600080fd5b3480156102a457600080fd5b506102b86102b3366004614474565b61096a565b005b3480156102c657600080fd5b506102b86102d5366004614474565b610a22565b3480156102e657600080fd5b50606e5460ff165b60405190151581526020015b60405180910390f35b34801561030f57600080fd5b506102b861031e36600461449f565b610ad7565b34801561032f57600080fd5b506102b861033e3660046144f5565b610b2c565b34801561034f57600080fd5b50606754600160a01b90046001600160401b03166040516001600160401b0390911681526020016102fa565b34801561038757600080fd5b50606f546001600160a01b03165b6040516001600160a01b0390911681526020016102fa565b3480156103b957600080fd5b506102b86103c836600461455a565b610d27565b3480156103d957600080fd5b50606e5462010000900463ffffffff165b60405163ffffffff90911681526020016102fa565b34801561040b57600080fd5b506102b861041a3660046145a3565b610f89565b34801561042b57600080fd5b50606b54600160a01b900463ffffffff166103ea565b34801561044d57600080fd5b506102b861045c366004614604565b611095565b34801561046d57600080fd5b506102b861047c3660046146c1565b61113b565b34801561048d57600080fd5b506102b86111d0565b3480156104a257600080fd5b506102b86104b1366004614474565b6111db565b6102b86104c4366004614703565b611211565b6102b86104d7366004614826565b61139e565b3480156104e857600080fd5b506102b86104f7366004614864565b61146f565b34801561050857600080fd5b506102b861051736600461487f565b61183b565b34801561052857600080fd5b506102b86105373660046148d9565b611bdc565b34801561054857600080fd5b506102b8611d6f565b34801561055d57600080fd5b506102ee61056c366004614474565b6001600160a01b031660009081526066602052604090205460ff1690565b34801561059657600080fd5b50606e54600160301b900463ffffffff166103ea565b3480156105b857600080fd5b506102b86105c7366004614939565b611dc9565b3480156105d857600080fd5b506102b8611e4d565b3480156105ed57600080fd5b506102b86105fc366004614474565b611e91565b34801561060d57600080fd5b506102b861061c366004614939565b611f65565b34801561062d57600080fd5b50610636611f94565b6040519081526020016102fa565b34801561065057600080fd5b506033546001600160a01b0316610395565b34801561066e57600080fd5b5061068261067d366004614952565b611fa4565b6040516102fa929190614974565b34801561069c57600080fd5b506107376106ab366004614864565b604080516080810182526000808252602082018190529181018290526060810191909152506001600160401b0316600090815260706020908152604091829020825160808101845290546001600160601b038082168352600160601b82041692820192909252600160c01b820460ff1692810192909252600160c81b900463ffffffff16606082015290565b6040516102fa91906149e4565b34801561075057600080fd5b50606e54600160501b90046001600160a01b0316610395565b34801561077557600080fd5b506102b861078436600461487f565b61209a565b34801561079557600080fd5b50610636612336565b3480156107aa57600080fd5b506102ee6107b9366004614474565b6001600160a01b03166000908152606d602052604090205460ff1690565b3480156107e357600080fd5b506102b86107f2366004614a29565b6123d3565b34801561080357600080fd5b506102b861081236600461449f565b612542565b34801561082357600080fd5b506102b8610832366004614474565b612607565b34801561084357600080fd5b50610857610852366004614864565b6126c1565b6040516102fa929190614a92565b34801561087157600080fd5b506102b8610880366004614aaf565b6126ea565b34801561089157600080fd5b506102b86108a0366004614474565b612a75565b3480156108b157600080fd5b506102b86108c0366004614b1e565b612acd565b6102b86108d3366004614952565b612bd4565b3480156108e457600080fd5b50606e54610100900460ff166102ee565b34801561090157600080fd5b506102b8610910366004614474565b612d3b565b34801561092157600080fd5b506102b8610930366004614b3c565b612e2f565b34801561094157600080fd5b506102b8612f69565b34801561095657600080fd5b506102b8610965366004614b8d565b612f72565b6033546001600160a01b0316331461099d5760405162461bcd60e51b815260040161099490614bb5565b60405180910390fd5b6001600160a01b0381166000908152606d602052604090205460ff16156109d65760405162461bcd60e51b815260040161099490614bea565b6001600160a01b0381166000818152606d6020526040808220805460ff19166001179055517fc5115f53265d15ca7930718dd520cd314285a7f2f0027e59b441f1f33b87b6919190a250565b6033546001600160a01b03163314610a4c5760405162461bcd60e51b815260040161099490614bb5565b606e546001600160a01b03828116600160501b909204161415610a815760405162461bcd60e51b815260040161099490614bea565b606e8054600160501b600160f01b031916600160501b6001600160a01b038416908102919091179091556040517f20495ad1c3942659031bc9602fe224bb567644c05306fe5656f04f0c5cd09ef590600090a250565b6033546001600160a01b03163314610b015760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b03919091166000908152607460205260409020805460ff1916911515919091179055565b6033546001600160a01b03163314610b565760405162461bcd60e51b815260040161099490614bb5565b63ffffffff8216610b8f5760405162461bcd60e51b81526020600482015260036024820152620543d360ec1b6044820152606401610994565b62ffffff610b9e600a84614c1d565b63ffffffff161115610bd85760405162461bcd60e51b8152602060048201526003602482015262543e4d60e81b6044820152606401610994565b63ffffffff8116610c115760405162461bcd60e51b81526020600482015260036024820152620543d360ec1b6044820152606401610994565b62ffffff610c20600a83614c1d565b63ffffffff161115610c5a5760405162461bcd60e51b8152602060048201526003602482015262543e4d60e81b6044820152606401610994565b606e5463ffffffff8381166201000090920416141580610c8c5750606e5463ffffffff828116600160301b9092041614155b610ca85760405162461bcd60e51b815260040161099490614bea565b606e805469ffffffffffffffff000019166201000063ffffffff85811691820269ffffffff000000000000191692909217600160301b928516928302179092556040805192835260208301919091527f0ac6ed41369d4003621c3216eaf4456c865743f8c396285512c18ac78150aaad91015b60405180910390a15050565b3360009081526066602052604090205460ff16610d565760405162461bcd60e51b815260040161099490614c4e565b606e54610100900460ff1615610d945760405162461bcd60e51b815260206004820152600360248201526204c4f560ec1b6044820152606401610994565b6002609b541415610db75760405162461bcd60e51b815260040161099490614c6b565b6002609b55610dc7606884613190565b610de35760405162461bcd60e51b815260040161099490614ca2565b6000610df06068856131b7565b9050610dfd60688561320c565b6000610e08826133b5565b90506004816004811115610e1e57610e1e614cbf565b14610e3b5760405162461bcd60e51b815260040161099490614cd5565b6040805160e0810182526000808252602080830182815283850183815260608086018581526080870186815260a080890188815260c08a018981528d5190951c968790528c5160581c60ff908116968790528d5160501c1693849052968c01805190911c9182905251891c6001600160601b03908116968790528b8a0151938490526067548a51639eee96df60e01b81526004810197909752602487019590955260448601929092526064850152608484019490945260a483015289831660c483015291881660e4820152935192936001600160a01b0390911692639eee96df926101048084019391929182900301818387803b158015610f3b57600080fd5b505af1158015610f4f573d6000803e3d6000fd5b505050506000805160206154b6833981519152868385604051610f7493929190614cf2565b60405180910390a150506001609b5550505050565b6033546001600160a01b03163314610fb35760405162461bcd60e51b815260040161099490614bb5565b62278d008163ffffffff161115610ff25760405162461bcd60e51b81526020600482015260036024820152624c434b60e81b6044820152606401610994565b606b5463ffffffff828116600160a01b9092041614156110245760405162461bcd60e51b815260040161099490614bea565b606b5460408051600160a01b90920463ffffffff9081168352831660208301527f0c0b8e3bb5e77c750110c5892a4426f766651572fc356dcff0300a53a79771e8910160405180910390a1606b805463ffffffff909216600160a01b0263ffffffff60a01b19909216919091179055565b3360009081526066602052604090205460ff166110c45760405162461bcd60e51b815260040161099490614c4e565b606754604051633d0ebb8960e01b81526001600160a01b0390911690633d0ebb8990611100908a908a908a908a908a908a908a90600401614d7c565b600060405180830381600087803b15801561111a57600080fd5b505af115801561112e573d6000803e3d6000fd5b5050505050505050505050565b60003360405163262d352160e21b8152606660048201526001600160a01b038216602482015260ff851660448201526001600160601b0384166064820152909150739897a73a606606394fa2324d16f3926f5963a9c3906398b4d4849060840160006040518083038186803b1580156111b357600080fd5b505af41580156111c7573d6000803e3d6000fd5b50505050505050565b6111d9336133ce565b565b6033546001600160a01b031633146112055760405162461bcd60e51b815260040161099490614bb5565b61120e8161344f565b50565b6002609b5414156112345760405162461bcd60e51b815260040161099490614c6b565b6002609b553360008181526072602052604090205460608b901c9060ff161561125c5761128d565b816001600160a01b0316816001600160a01b03161461128d5760405162461bcd60e51b815260040161099490614e27565b83158015906112a65750606f546001600160a01b031615155b1561131257606f5460405163bfb7d70d60e01b81526001600160a01b038381166004830152602482018790529091169063bfb7d70d90604401600060405180830381600087803b1580156112f957600080fd5b505af115801561130d573d6000803e3d6000fd5b505050505b739897a73a606606394fa2324d16f3926f5963a9c3630f40ab716066428e8e8e8e8e8e8e8d6040518b63ffffffff1660e01b815260040161135c9a99989796959493929190614e44565b60006040518083038186803b15801561137457600080fd5b505af4158015611388573d6000803e3d6000fd5b50506001609b5550505050505050505050505050565b6002609b5414156113c15760405162461bcd60e51b815260040161099490614c6b565b6002609b5560408051631e8fc0ef60e01b81526066600482015263ffffffff42166024820152336044820181905260ff861660648301526001600160601b038516608483015283151560a48301529151739897a73a606606394fa2324d16f3926f5963a9c391631e8fc0ef9160c4808301926000929190829003018186803b15801561144c57600080fd5b505af4158015611460573d6000803e3d6000fd5b50506001609b55505050505050565b6002609b5414156114925760405162461bcd60e51b815260040161099490614c6b565b6002609b556114a2606882613190565b6114be5760405162461bcd60e51b815260040161099490614ca2565b60006114cb6068836131b7565b90506114d860688361320c565b60006114e5825160601c90565b905060006114f2836133b5565b9050600181600481111561150857611508614cbf565b14156116a0576000611519846134d0565b3360009081526066602052604090205490915060ff161561156c5761153d81613587565b63ffffffff164263ffffffff16116115675760405162461bcd60e51b815260040161099490614eec565b611594565b336001600160a01b038416146115945760405162461bcd60e51b815260040161099490614e27565b60c0810151608016151580156115b75750600081604001516001600160601b0316115b1561165a5760675460208201516000916001600160a01b031690632d46c6c29060581c6040516001600160e01b031960e084901b16815260ff9091166004820152602401602060405180830381865afa158015611618573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061163c9190614f09565b90506116586066828685604001516001600160601b03166135ff565b505b6001600160401b038516600081815260706020908152604080832080546001600160e81b0319169055848201518352607190915290206116999161371c565b50506117ed565b60028160048111156116b4576116b4614cbf565b14156116fe57336001600160a01b038316146116e25760405162461bcd60e51b815260040161099490614e27565b60006116ed8461372f565b90506116f8816137d3565b506117ed565b600381600481111561171257611712614cbf565b14156117c3573360009081526066602052604090205460ff161561178c57600061173b84613935565b606e5460a082015191925060009161175f9162010000900463ffffffff1690614f26565b63ffffffff169050804263ffffffff16116116995760405162461bcd60e51b815260040161099490614eec565b6001600160a01b038216335b6001600160a01b0316146117be5760405162461bcd60e51b815260040161099490614e27565b6117ed565b60048160048111156117d7576117d7614cbf565b1415610293576001600160a01b03821633611798565b7fe5033f0fc6c1035c36f3d7c2b4278c1d0fc20d165ba0873a0ce56a661e8cf86684611818856133b5565b8560405161182893929190614cf2565b60405180910390a150506001609b555050565b3360009081526066602052604090205460ff1661186a5760405162461bcd60e51b815260040161099490614c4e565b606e5460ff16156118a35760405162461bcd60e51b81526020600482015260036024820152620504f560ec1b6044820152606401610994565b6002609b5414156118c65760405162461bcd60e51b815260040161099490614c6b565b6002609b556118d6606885613190565b6118f25760405162461bcd60e51b815260040161099490614ca2565b60006118ff6068866131b7565b905061190c60688661320c565b6000611917826133b5565b9050600181600481111561192d5761192d614cbf565b1461194a5760405162461bcd60e51b815260040161099490614cd5565b6000611955836134d0565b905061196081613587565b63ffffffff164263ffffffff16111561198b5760405162461bcd60e51b815260040161099490614eec565b600061199d8260c00151608016151590565b15611a2c5760405163352de4bb60e11b8152739897a73a606606394fa2324d16f3926f5963a9c390636a5bc976906119e49060669042908d908d908d908a90600401615006565b602060405180830381865af4158015611a01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a25919061504d565b9050611ab4565b604051630580dfb760e11b8152739897a73a606606394fa2324d16f3926f5963a9c390630b01bf6e90611a709060669042908d908d908d908d908b9060040161506a565b602060405180830381865af4158015611a8d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab1919061504d565b90505b60c0820151604016611ba4576000611ad28360c00151608016151590565b60208401519015159060481c60ff1615151515149050611af88360c00151601016151590565b15611aff57155b8015611b565782608001516001600160601b0316826001600160601b03161115611b515760405162461bcd60e51b815260206004820152600360248201526213135560ea1b6044820152606401610994565b611ba2565b82608001516001600160601b0316826001600160601b03161015611ba25760405162461bcd60e51b815260206004820152600360248201526213135560ea1b6044820152606401610994565b505b6000805160206154b6833981519152888486604051611bc593929190614cf2565b60405180910390a150506001609b55505050505050565b336000908152606d602052604090205460ff16611c215760405162461bcd60e51b815260206004820152600360248201526210905360ea1b6044820152606401610994565b6002609b541415611c445760405162461bcd60e51b815260040161099490614c6b565b6002609b556001600160601b038316611c855760405162461bcd60e51b81526020600482015260036024820152620413d360ec1b6044820152606401610994565b606780543391600091600160a01b90046001600160401b0316906014611caa836150c5565b91906101000a8154816001600160401b0302191690836001600160401b0316021790555090506000611ce182848a8a8a8a8a61397d565b9050611cef60688383613a0b565b6040805160ff8a81168252891660208201526001600160601b0388811682840152871660608201526080810186905290516001600160401b038416916001600160a01b038616917f5c1a7ceefa482bcc616dec79c7a8bb748520ec46eb6d550f10ecf97e70f1c96a9181900360a00190a350506001609b55505050505050565b6065546001600160a01b0316336001600160a01b031614611da25760405162461bcd60e51b815260040161099490614e27565b606554611db7906001600160a01b0316613b2f565b606580546001600160a01b0319169055565b606081901c3314611dec5760405162461bcd60e51b815260040161099490614e27565b606754604051631ae0468f60e21b8152600481018390526001600160a01b0390911690636b811a3c90602401600060405180830381600087803b158015611e3257600080fd5b505af1158015611e46573d6000803e3d6000fd5b5050505050565b6033546001600160a01b03163314611e775760405162461bcd60e51b815260040161099490614bb5565b606580546001600160a01b03191690556111d96000613b2f565b606e54600160501b90046001600160a01b0316336001600160a01b03161480611ec457506033546001600160a01b031633145b611ee05760405162461bcd60e51b8152600401610994906150ec565b6001600160a01b03811660009081526066602052604090205460ff1615611f195760405162461bcd60e51b815260040161099490614bea565b6001600160a01b038116600081815260666020526040808220805460ff19166001179055517f2fcbb5eda85b2352f87cce68063c290996e8cbc17c8f7c25a8b9ba1e59de256c9190a250565b6033546001600160a01b03163314611f8f5760405162461bcd60e51b815260040161099490614bb5565b607355565b6000611f9f60685490565b905090565b60606000611fb160685490565b90508284101580611fc25750808410155b15611fcc57612093565b80831115611fda5780611fdc565b825b92506000611fea8585615109565b9050806001600160401b03811115612004576120046146ed565b60405190808252806020026020018201604052801561203d57816020015b61202a6143ee565b8152602001906001900390816120225790505b50925060005b81811015612090576120606120588783615120565b606890613b81565b84828151811061207257612072615138565b602002602001018190525080806120889061514e565b915050612043565b50505b9250929050565b3360009081526066602052604090205460ff166120c95760405162461bcd60e51b815260040161099490614c4e565b6002609b5414156120ec5760405162461bcd60e51b815260040161099490614c6b565b6002609b556120fc606885613190565b6121185760405162461bcd60e51b815260040161099490614ca2565b60006121256068866131b7565b905061213260688661320c565b600061213d826133b5565b9050600381600481111561215357612153614cbf565b146121705760405162461bcd60e51b815260040161099490614cd5565b600061217b83613935565b606e5460a082015191925061219d916201000090910463ffffffff1690614f26565b63ffffffff164263ffffffff1611156121c85760405162461bcd60e51b815260040161099490614eec565b8060800151156122765760675460208201516040808401516060850151915163484289c760e01b815260048101939093526001600160601b03908116602484015260ff909116604483015280891660648301528088166084830152861660a48201526001600160a01b039091169063484289c79060c401600060405180830381600087803b15801561225957600080fd5b505af115801561226d573d6000803e3d6000fd5b505050506122ff565b60675460208201516040808401519051634700832960e11b815260048101929092526001600160601b0390811660248301528089166044830152871660648201526001600160a01b0390911690638e01065290608401600060405180830381600087803b1580156122e657600080fd5b505af11580156122fa573d6000803e3d6000fd5b505050505b6000805160206154b683398151915287838560405161232093929190614cf2565b60405180910390a150506001609b555050505050565b3360009081526066602052604081205460ff166123655760405162461bcd60e51b815260040161099490614c4e565b606754604051636bc72faf60e11b81523360048201526001600160a01b039091169063d78e5f5e906024016020604051808303816000875af11580156123af573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f9f9190615169565b6002609b5414156123f65760405162461bcd60e51b815260040161099490614c6b565b6002609b5560006124078560601c90565b90506001600160a01b03811633146124315760405162461bcd60e51b815260040161099490614e27565b6001600160601b03841661246d5760405162461bcd60e51b81526020600482015260036024820152620413d360ec1b6044820152606401610994565b60678054600091600160a01b9091046001600160401b0316906014612491836150c5565b91906101000a8154816001600160401b0302191690836001600160401b03160217905550905060006124cd82888888886124c84290565b613c43565b90506124db60688383613a0b565b604080516001600160601b038816815260ff871660208201528515158183015290516001600160401b0384169189917f201d03547a8fd1f2eaa0fda90af89681a6c4dc6a8e495565e5ca6a62b3579cf09181900360600190a350506001609b555050505050565b6033546001600160a01b0316331461256c5760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b0382166125a85760405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606401610994565b6001600160a01b038216600081815260726020908152604091829020805460ff191685151590811790915591519182527f9aaad5d73fc4de1befd3e790b855dfdc6363f068e93abfdf01ad70681d31d0ce910160405180910390a25050565b6033546001600160a01b031633146126315760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b03811661266d5760405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606401610994565b606f80546001600160a01b0319166001600160a01b0383169081179091556040519081527f57202bce87a87010e83825477a341d777f701216d3e2a3b4642c72d9e8a931989060200160405180910390a150565b6126c96143ee565b60006126d66068846131b7565b6126e1606885613190565b91509150915091565b3360009081526066602052604090205460ff166127195760405162461bcd60e51b815260040161099490614c4e565b606e54610100900460ff16156127575760405162461bcd60e51b815260206004820152600360248201526204c4f560ec1b6044820152606401610994565b6002609b54141561277a5760405162461bcd60e51b815260040161099490614c6b565b6002609b5561278a606886613190565b6127a65760405162461bcd60e51b815260040161099490614ca2565b60006127b36068876131b7565b90506127c060688761320c565b60006127cb8261372f565b6020808201516001600160a01b031660009081526074909152604090205490915060ff16156128dc57600081602001516001600160a01b031663be49f64a612811613d08565b848a8a8a8a6040518763ffffffff1660e01b81526004016128369594939291906151df565b60206040518083038160008887f193505050508015612872575060408051601f3d908101601f1916820190925261286f91810190615221565b60015b61287e57506000612881565b90505b806128da5761288f826137d3565b7fe5033f0fc6c1035c36f3d7c2b4278c1d0fc20d165ba0873a0ce56a661e8cf866886128ba856133b5565b856040516128ca93929190614cf2565b60405180910390a1505050612a69565b505b60006128e7836133b5565b905060028160048111156128fd576128fd614cbf565b1461291a5760405162461bcd60e51b815260040161099490614cd5565b604051636cc4fd9560e11b8152600090739897a73a606606394fa2324d16f3926f5963a9c39063d989fb2a906129619060669042908d908d908d908d908d9060040161523e565b602060405180830381865af415801561297e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129a29190615169565b6020808501516001600160a01b031660009081526074909152604090205490915060ff1615612a3b5782602001516001600160a01b0316639c69c2e16129e6613d08565b85848c8c8c8c6040518863ffffffff1660e01b8152600401612a0d969594939291906152b3565b600060405180830381600088803b158015612a2757600080fd5b5087f193505050508015612a39575060015b505b6000805160206154b6833981519152898386604051612a5c93929190614cf2565b60405180910390a1505050505b50506001609b55505050565b606e54600160501b90046001600160a01b0316336001600160a01b03161480612aa857506033546001600160a01b031633145b612ac45760405162461bcd60e51b8152600401610994906150ec565b61120e816133ce565b606e54600160501b90046001600160a01b0316336001600160a01b03161480612b0057506033546001600160a01b031633145b612b1c5760405162461bcd60e51b8152600401610994906150ec565b606e5460ff16151582151514612b7157606e805460ff19168315159081179091556040519081527ff08d1ca9cf739c5ed2fcedf748abbfa8f14006e47f4a0a3805e6ce8ace2411229060200160405180910390a15b606e5460ff61010090910416151581151514612bd057606e80548215156101000261ff00199091161790556040517f1dd885054d26280b4f25ebb658ef23327620ee20f5ad56b33902e87f8ad65bba90610d1b90831515815260200190565b5050565b6000612bdf83613d20565b80519091506001600160a01b03163314612c0b5760405162461bcd60e51b815260040161099490614e27565b81612c3e5760405162461bcd60e51b81526020600482015260036024820152620433d360ec1b6044820152606401610994565b60675460208201516040516316a3636160e11b815260ff90911660048201526000916001600160a01b031690632d46c6c290602401602060405180830381865afa158015612c90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cb49190614f09565b9050612cd060663360675484906001600160a01b031687613db9565b6067546040516337aa6d1960e21b815260048101869052602481018590526001600160a01b039091169063dea9b46490604401600060405180830381600087803b158015612d1d57600080fd5b505af1158015612d31573d6000803e3d6000fd5b5050505050505050565b6033546001600160a01b03163314612d655760405162461bcd60e51b815260040161099490614bb5565b6001600160a01b038116612da15760405162461bcd60e51b815260206004820152600360248201526204f3d360ec1b6044820152606401610994565b6033546001600160a01b0382811691161415612de55760405162461bcd60e51b81526020600482015260036024820152624f3d4f60e81b6044820152606401610994565b606580546001600160a01b0319166001600160a01b0383169081179091556040517fb501f5dc3610d10a179d924f686fc89ddcdd3abb05afd7a1baeead166b2f122c90600090a250565b600054610100900460ff16612e4a5760005460ff1615612e4e565b303b155b612eb15760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610994565b600054610100900460ff16158015612ed3576000805461ffff19166101011790555b612edb613f57565b606780546001600160a01b03199081166001600160a01b0388811691909117909255606a80548216878416179055606b80548216868416179055606c805490911684831617905560335416606e80546001600160a01b0392909216600160501b02600160501b600160f01b03199092169190911790558015611e46576000805461ff00191690555050505050565b6111d93361344f565b3360009081526066602052604090205460ff16612fa15760405162461bcd60e51b815260040161099490614c4e565b606754604051633f9beb3160e21b81526004810187905260ff861660248201526001600160601b0380861660448301528085166064830152831660848201526001600160a01b039091169063fe6facc49060a4016020604051808303816000875af1158015613014573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613038919061504d565b506067546040516303e9375760e01b8152600481018790526000916001600160a01b0316906303e937579060240160a060405180830381865afa158015613083573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130a791906152fb565b5050505090506000816001600160601b0316111561311e57606754604051631ae0468f60e21b8152600481018890526001600160a01b0390911690636b811a3c90602401600060405180830381600087803b15801561310557600080fd5b505af1158015613119573d6000803e3d6000fd5b505050505b6040516342f4ff7160e11b81526066600482015260248101879052739897a73a606606394fa2324d16f3926f5963a9c3906385e9fee29060440160006040518083038186803b15801561317057600080fd5b505af4158015613184573d6000803e3d6000fd5b50505050505050505050565b6001600160401b038116600090815260018381016020526040909120015415155b92915050565b6131bf6143ee565b6001600160401b038216600090815260018401602052604090819020815160608101928390529160039082845b8154815260200190600101908083116131ec575050505050905092915050565b6001600160401b0381166000908152600180840160205260408220919082015490506001600160401b0381166132545760405162461bcd60e51b815260040161099490614ca2565b6000613261600183615377565b85546001600160401b0391909116915060009061328090600190615109565b90508181146133475760008660000182815481106132a0576132a0615138565b90600052602060002090600491828204019190066008029054906101000a90046001600160401b03169050808760000184815481106132e1576132e1615138565b600091825260208083206004830401805460039093166008026101000a6001600160401b03818102199094169584160294909417909355838116825260018a81019093526040909120919086169067ffffffffffffffff19908301541617816001015550505b85548690806133585761335861539f565b600082815260208082206004600019949094019384040180546001600160401b03600860038716026101000a8102199091169091559290935596168652600196870190525050604083208381559384018390555050600290910155565b805160009060ff1660048111156131b1576131b1614cbf565b6001600160a01b03811660009081526066602052604090205460ff166134065760405162461bcd60e51b815260040161099490614bea565b6001600160a01b038116600081815260666020526040808220805460ff19169055517fcdf53ae488d66a98f509e3342bdc0a13dee821f05bfb372351346a7a991df7a29190a250565b6001600160a01b0381166000908152606d602052604090205460ff166134875760405162461bcd60e51b815260040161099490614bea565b6001600160a01b0381166000818152606d6020526040808220805460ff19169055517f963257db523ad7beed5ed8d412d9efcfa2ec8b73e3c20c3aaf5b6161f9ec48119190a250565b60408051610120810182526000808252602080830182815283850183815260608086018581526080870186815260a080890188815260c08a0189815260e08b018a81526101008c019a8b528d5168ffffffffffffffffff19169098528c8c0180518d1c6001600160601b03169097529b9097018051821c909352825160901c60ff908116909b52935190931c909252815160981c909716909252815190951c62ffffff169091525190911c63ffffffff1690915290565b60006135998260c00151604016151590565b156135bc57606e5460e08301516131b19162010000900463ffffffff1690614f26565b6135eb82610100015162ffffff16600a6135d691906153b5565b606e54600160301b900463ffffffff16613f86565b8260e001516131b19190614f26565b919050565b60058401546001600160a01b0384811691161415613702576005840154600685015460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303816000875af1158015613670573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136949190615221565b5060068401546040516339f4769360e01b81526001600160a01b03848116600483015260248201849052909116906339f4769390604401600060405180830381600087803b1580156136e557600080fd5b505af11580156136f9573d6000803e3d6000fd5b50505050613716565b6137166001600160a01b0384168383613fa9565b50505050565b60006137288383614011565b9392505050565b6040805160c08101825260008082526020820181815292820181905260608083018290526080830182905260a0830191909152835160081c6001600160401b031682528351901c9091528160015b602002015160a01c604082015260608260016020020151901b60f81c6060820152600060688360016020020151901b60f81c8015156080840152905060a08360016020020151901b60e01c60a083015250919050565b8060800151156138795760675460608201516040516316a3636160e11b815260ff90911660048201526000916001600160a01b031690632d46c6c290602401602060405180830381865afa15801561382f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138539190614f09565b9050613873606682846020015185604001516001600160601b03166135ff565b506138a4565b60208101516040820151606a546138a4926001600160a01b03909116916001600160601b0316613fa9565b6020808201516001600160a01b031660009081526074909152604090205460ff161561120e5780602001516001600160a01b031663463cde3a6138e5613d08565b836040518363ffffffff1660e01b815260040161390291906153e1565b600060405180830381600088803b15801561391c57600080fd5b5087f19350505050801561392e575060015b61120e5750565b6040805160c081018252600080825260208201818152928201819052606082018190526080820181905260a0820152825168ffffffffffffffffff191690915281600161377d565b6139856143ee565b60089790971b68ffffffffffffffff001660509490941b60ff60501b1660589590951b60ff60581b1660609690961b6bffffffffffffffffffffffff19169590951793909317919091176004178452604091821b73ffffffffffffffffffffffff00000000000000001660a09190911b6001600160a01b03191617602084015282015290565b613a158383613190565b15613a485760405162461bcd60e51b815260206004820152600360248201526204455560ec1b6044820152606401610994565b82546001810184556000848152602090206004820401805460039092166008026101000a6001600160401b038181021990931685841691909102179055835490811115613abd5760405162461bcd60e51b815260206004820152600360248201526213cd8d60ea1b6044820152606401610994565b60208201516001600160401b031615613afe5760405162461bcd60e51b81526020600482015260036024820152622798a360e91b6044820152606401610994565b60208083018051831790526001600160401b03841660009081526001860190915260409020611e469083600361440c565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b613b896143ee565b82548210613bbf5760405162461bcd60e51b815260206004820152600360248201526209288b60eb1b6044820152606401610994565b6000836000018381548110613bd657613bd6615138565b6000918252602080832060048304015460039283166008026101000a90046001600160401b03168084526001880190915260409283902083516060810194859052919450909290919082845b815481526020019060010190808311613c2257505050505091505092915050565b613c4b6143ee565b68ffffffffffffffffff861615613c8a5760405162461bcd60e51b815260206004820152600360248201526210525160ea1b6044820152606401610994565b600083613c98576000613c9b565b60015b9050600368ffffffffffffffff0060088a901b1688171782600060200201526001600160a01b031960a087901b1660ff60981b609887901b161760ff60901b609083901b16176bffffffff0000000000000000604085901b16178260016020020152509695505050505050565b60735460009015613d1a575060735490565b5a905090565b60408051608081018252600080825260208201819052918101829052606081019190915268ffffffffffffffffff821615613d835760405162461bcd60e51b815260206004820152600360248201526210525160ea1b6044820152606401610994565b606082811c825260ff605884901c81166020840152605084901c8116604084015260489390931c90921615159181019190915290565b60058501546001600160a01b0384811691161415613f0e57600034118015613de057508034145b613e125760405162461bcd60e51b815260206004820152600360248201526215905360ea1b6044820152606401610994565b8460050160009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b158015613e6457600080fd5b505af1158015613e78573d6000803e3d6000fd5b505050506001600160a01b03831630149050613f0957600585015460405163a9059cbb60e01b81526001600160a01b038481166004830152602482018490529091169063a9059cbb906044016020604051808303816000875af1158015613ee3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f079190615221565b505b611e46565b3415613f425760405162461bcd60e51b815260206004820152600360248201526215905360ea1b6044820152606401610994565b611e466001600160a01b038416858484614104565b600054610100900460ff16613f7e5760405162461bcd60e51b8152600401610994906153ef565b6111d961413c565b60008163ffffffff168363ffffffff161115613fa25781613728565b5090919050565b6040516001600160a01b03831660248201526044810182905261400c90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261416b565b505050565b600081815260018301602052604081205480156140fa576000614035600183615109565b855490915060009061404990600190615109565b90508181146140ae57600086600001828154811061406957614069615138565b906000526020600020015490508087600001848154811061408c5761408c615138565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806140bf576140bf61539f565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506131b1565b60009150506131b1565b6040516001600160a01b03808516602483015283166044820152606481018290526137169085906323b872dd60e01b90608401613fd5565b600054610100900460ff166141635760405162461bcd60e51b8152600401610994906153ef565b6111d961423d565b60006141c0826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661426d9092919063ffffffff16565b80519091501561400c57808060200190518101906141de9190615221565b61400c5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610994565b600054610100900460ff166142645760405162461bcd60e51b8152600401610994906153ef565b6111d933613b2f565b606061427c8484600085614284565b949350505050565b6060824710156142e55760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610994565b6001600160a01b0385163b61433c5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610994565b600080866001600160a01b031685876040516143589190615466565b60006040518083038185875af1925050503d8060008114614395576040519150601f19603f3d011682016040523d82523d6000602084013e61439a565b606091505b50915091506143aa8282866143b5565b979650505050505050565b606083156143c4575081613728565b8251156143d45782518084602001fd5b8160405162461bcd60e51b81526004016109949190615482565b60405180606001604052806003906020820280368337509192915050565b826003810192821561443a579160200282015b8281111561443a57825182559160200191906001019061441f565b5061444692915061444a565b5090565b5b80821115614446576000815560010161444b565b6001600160a01b038116811461120e57600080fd5b60006020828403121561448657600080fd5b81356137288161445f565b801515811461120e57600080fd5b600080604083850312156144b257600080fd5b82356144bd8161445f565b915060208301356144cd81614491565b809150509250929050565b63ffffffff8116811461120e57600080fd5b80356135fa816144d8565b6000806040838503121561450857600080fd5b8235614513816144d8565b915060208301356144cd816144d8565b80356001600160401b03811681146135fa57600080fd5b6001600160601b038116811461120e57600080fd5b80356135fa8161453a565b60008060006060848603121561456f57600080fd5b61457884614523565b925060208401356145888161453a565b915060408401356145988161453a565b809150509250925092565b6000602082840312156145b557600080fd5b8135613728816144d8565b60008083601f8401126145d257600080fd5b5081356001600160401b038111156145e957600080fd5b6020830191508360208260051b850101111561209357600080fd5b60008060008060008060006080888a03121561461f57600080fd5b873561462a816144d8565b965060208801356001600160401b038082111561464657600080fd5b6146528b838c016145c0565b909850965060408a013591508082111561466b57600080fd5b6146778b838c016145c0565b909650945060608a013591508082111561469057600080fd5b5061469d8a828b016145c0565b989b979a50959850939692959293505050565b803560ff811681146135fa57600080fd5b600080604083850312156146d457600080fd5b6146dd836146b0565b915060208301356144cd8161453a565b634e487b7160e01b600052604160045260246000fd5b6000806000806000806000806000898b0361018081121561472357600080fd5b8a35995060208b01356147358161453a565b985060408b01356147458161453a565b975060608b01356147558161453a565b965061476360808c016146b0565b955061477160a08c016146b0565b945060c08b0135614781816144d8565b935060e08b01359250608060ff198201121561479c57600080fd5b50604051608081018181106001600160401b03821117156147cd57634e487b7160e01b600052604160045260246000fd5b6040526147dd6101008c0161454f565b81526147ec6101208c0161454f565b60208201526147fe6101408c016146b0565b60408201526148106101608c016144ea565b6060820152809150509295985092959850929598565b60008060006060848603121561483b57600080fd5b614844846146b0565b925060208401356148548161453a565b9150604084013561459881614491565b60006020828403121561487657600080fd5b61372882614523565b6000806000806080858703121561489557600080fd5b61489e85614523565b935060208501356148ae8161453a565b925060408501356148be8161453a565b915060608501356148ce8161453a565b939692955090935050565b600080600080600060a086880312156148f157600080fd5b6148fa866146b0565b9450614908602087016146b0565b935060408601356149188161453a565b925060608601356149288161453a565b949793965091946080013592915050565b60006020828403121561494b57600080fd5b5035919050565b6000806040838503121561496557600080fd5b50508035926020909101359150565b6040808252835190820181905260009060609081840190602080880185805b848110156149d057825186835b60038110156149bd578251825291860191908601906001016149a0565b5050509486019491830191600101614993565b505050949094019490945250919392505050565b608081016131b182846001600160601b038082511683528060208301511660208401525060ff604082015116604083015263ffffffff60608201511660608301525050565b60008060008060808587031215614a3f57600080fd5b843593506020850135614a518161453a565b9250614a5f604086016146b0565b915060608501356148ce81614491565b8060005b6003811015613716578151845260209384019390910190600101614a73565b60808101614aa08285614a6f565b82151560608301529392505050565b600080600080600060a08688031215614ac757600080fd5b614ad086614523565b94506020860135614ae08161453a565b93506040860135614af08161453a565b92506060860135614b008161453a565b91506080860135614b108161453a565b809150509295509295909350565b60008060408385031215614b3157600080fd5b82356144bd81614491565b60008060008060808587031215614b5257600080fd5b8435614b5d8161445f565b93506020850135614b6d8161445f565b92506040850135614b7d8161445f565b915060608501356148ce8161445f565b600080600080600060a08688031215614ba557600080fd5b85359450614ae0602087016146b0565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b60208082526003908201526243484760e81b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff80841680614c4257634e487b7160e01b600052601260045260246000fd5b92169190910492915050565b6020808252600390820152622125a960e91b604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526003908201526213d25160ea1b604082015260600190565b634e487b7160e01b600052602160045260246000fd5b60208082526003908201526205459560ec1b604082015260600190565b6001600160401b038416815260a0810160058410614d2057634e487b7160e01b600052602160045260246000fd5b83602083015261427c6040830184614a6f565b8183526000602080850194508260005b85811015614d71578135614d568161453a565b6001600160601b031687529582019590820190600101614d43565b509495945050505050565b63ffffffff888116825260806020808401829052908301889052600091899160a08501845b8b811015614dc75760ff614db4866146b0565b1682529382019390820190600101614da1565b508581036040870152888152810192508860005b89811015614e02578135614dee816144d8565b841685529382019390820190600101614ddb565b505050508281036060840152614e19818587614d33565b9a9950505050505050505050565b60208082526003908201526214d39160ea1b604082015260600190565b8a815263ffffffff8a81166020830152604082018a90526001600160601b0389811660608401528881166080840152871660a083015260ff86811660c0840152851660e083015283166101008201526101a08101614edd6101208301846001600160601b038082511683528060208301511660208401525060ff604082015116604083015263ffffffff60608201511660608301525050565b9b9a5050505050505050505050565b60208082526003908201526204558560ec1b604082015260600190565b600060208284031215614f1b57600080fd5b81516137288161445f565b600063ffffffff808316818516808303821115614f4557614f45614c07565b01949350505050565b6001600160401b038151168252602081015160208301526001600160601b0360408201511660408301526060810151614f9260608401826001600160601b03169052565b506080810151614fad60808401826001600160601b03169052565b5060a0810151614fc260a084018260ff169052565b5060c0810151614fd760c084018260ff169052565b5060e0810151614fef60e084018263ffffffff169052565b506101008181015162ffffff811684830152613716565b86815263ffffffff861660208201526001600160401b03851660408201526001600160601b038481166060830152831660808201526101c081016143aa60a0830184614f4e565b60006020828403121561505f57600080fd5b81516137288161453a565b87815263ffffffff871660208201526001600160401b03861660408201526001600160601b0385811660608301528481166080830152831660a08201526101e081016150b960c0830184614f4e565b98975050505050505050565b60006001600160401b03808316818114156150e2576150e2614c07565b6001019392505050565b60208082526003908201526253214d60e81b604082015260600190565b60008282101561511b5761511b614c07565b500390565b6000821982111561513357615133614c07565b500190565b634e487b7160e01b600052603260045260246000fd5b600060001982141561516257615162614c07565b5060010190565b60006020828403121561517b57600080fd5b5051919050565b80516001600160401b031682526020808201516001600160a01b0316908301526040808201516001600160601b03169083015260608082015160ff169083015260808082015115159083015260a09081015163ffffffff16910152565b61014081016151ee8288615182565b6001600160601b0395861660c083015293851660e082015291841661010083015290921661012090920191909152919050565b60006020828403121561523357600080fd5b815161372881614491565b87815263ffffffff87166020808301919091526001600160601b03878116604084015286811660608401528581166080840152841660a083015261012082019060c083018460005b60038110156152a357815183529183019190830190600101615286565b5050505098975050505050505050565b61016081016152c28289615182565b60c08201969096526001600160601b0394851660e082015292841661010084015290831661012083015290911661014090910152919050565b600080600080600060a0868803121561531357600080fd5b855161531e8161453a565b602087015190955061532f8161453a565b6040870151909450615340816144d8565b60608701519093506153518161453a565b60808701519092506fffffffffffffffffffffffffffffffff81168114614b1057600080fd5b60006001600160401b038381169083168181101561539757615397614c07565b039392505050565b634e487b7160e01b600052603160045260246000fd5b600063ffffffff808316818516818304811182151516156153d8576153d8614c07565b02949350505050565b60c081016131b18284615182565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b60005b8381101561545557818101518382015260200161543d565b838111156137165750506000910152565b6000825161547881846020870161543a565b9190910192915050565b60208152600082518060208401526154a181604085016020870161543a565b601f01601f1916919091016040019291505056fe6204728db10730656ada9f8ce5b258b0d97dc6ac8e8a101ff4b905c3c9cc7dc5a26469706673582212200650f8dfd5e86abc5b690115a26b6357e3485afda7ad5dda2d8730d9cca3fe0964736f6c634300080a0033

Block Transaction Difficulty 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

Txn Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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