MON Price: $0.018793 (+2.58%)

Contract

0x1366E093b5334A6Ca2fAADd61fC4AB60AFD61557

Overview

MON Balance

Monad Chain LogoMonad Chain LogoMonad Chain Logo0 MON

MON Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
Positions

Compiler Version
v0.8.17+commit.8df45f5f

Optimization Enabled:
Yes with 200 runs

Other Settings:
london EvmVersion
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./IERC20Metadata.sol";
import "pyth-sdk-solidity/IPyth.sol";
import "pyth-sdk-solidity/PythStructs.sol";

import {AssetStore} from "./AssetStore.sol";
import {DataStore} from "./DataStore.sol";
import {FundStore} from "./FundStore.sol";
import {FundingStore} from "./FundingStore.sol";
import {MarketStore} from "./MarketStore.sol";
import {OrderStore} from "./OrderStore.sol";
import {PoolStore} from "./PoolStore.sol";
import {PositionStore} from "./PositionStore.sol";
import {RiskStore} from "./RiskStore.sol";

import {Funding} from "./Funding.sol";
import {Orders} from "./Orders.sol";
import {Pool} from "./Pool.sol";

import "./Roles.sol";

import {PythUpdater} from "./PythUpdater.sol";
import {ReferralStore} from "./ReferralStore.sol";
import {RebateStore} from "./RebateStore.sol";
import {PythPriceUtils} from "./PythPriceUtils.sol";

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

/**
 * @title  Positions
 * @notice Implementation of position related logic, i.e. increase positions,
 *         decrease positions, close positions, add/remove margin
 */
contract Positions is Roles {
    // Constants
    uint256 public constant UNIT = 10 ** 18;
    uint256 public constant BPS_DIVIDER = 10000;

    // Events
    event PositionIncreased(
        uint256 indexed orderId,
        address indexed user,
        address indexed asset,
        string market,
        bool isLong,
        uint256 size,
        uint256 margin,
        uint256 price,
        uint256 positionMargin,
        uint256 positionSize,
        uint256 positionPrice,
        int256 fundingTracker,
        uint256 fee
    );

    event PositionDecreased(
        uint256 indexed orderId,
        address indexed user,
        address indexed asset,
        string market,
        bool isLong,
        uint256 size,
        uint256 margin,
        uint256 price,
        uint256 positionMargin,
        uint256 positionSize,
        uint256 positionPrice,
        int256 fundingTracker,
        uint256 fee,
        int256 pnl,
        int256 pnlUsd,
        int256 fundingFee
    );

    event MarginIncreased(
        address indexed user,
        address indexed asset,
        string market,
        uint256 marginDiff,
        uint256 positionMargin
    );

    event MarginDecreased(
        address indexed user,
        address indexed asset,
        string market,
        uint256 marginDiff,
        uint256 positionMargin
    );

    event FeePaid(
        uint256 indexed orderId,
        address indexed user,
        address indexed asset,
        string market,
        uint256 fee,
        uint256 poolFee,
        uint256 buyBackFee,
        uint256 treasuryFee,
        uint256 keeperFee,
        bool isLiquidation,
        uint256 referrerRebate
    );

    // Contracts
    DataStore public DS;

    AssetStore public assetStore;
    FundStore public fundStore;
    FundingStore public fundingStore;
    MarketStore public marketStore;
    OrderStore public orderStore;
    PoolStore public poolStore;
    PositionStore public positionStore;
    RiskStore public riskStore;
    BuyBackStore public buyBackStore;

    Funding public funding;
    Pool public pool;

    IPyth public pyth;

    PythUpdater public pythUpdater;
    ReferralStore public referralStore;
    RebateStore public rebateStore;

    /// @dev Initializes DataStore address
    function initialize(address rs, address ds) external initializer {
        DS = DataStore(ds);
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @dev Reverts if new orders are paused
    modifier ifNotPaused() {
        require(!orderStore.areNewOrdersPaused(), "!paused");
        _;
    }

    /// @notice Initializes protocol contracts
    /// @dev Only callable by governance
    function link() external onlyGov {
        assetStore = AssetStore(DS.getAddress("AssetStore"));
        fundStore = FundStore(payable(DS.getAddress("FundStore")));
        fundingStore = FundingStore(DS.getAddress("FundingStore"));
        marketStore = MarketStore(DS.getAddress("MarketStore"));
        orderStore = OrderStore(DS.getAddress("OrderStore"));
        poolStore = PoolStore(DS.getAddress("PoolStore"));
        positionStore = PositionStore(DS.getAddress("PositionStore"));
        riskStore = RiskStore(DS.getAddress("RiskStore"));
        buyBackStore = BuyBackStore(DS.getAddress("BuyBackStore"));
        funding = Funding(DS.getAddress("Funding"));
        pool = Pool(DS.getAddress("Pool"));
        pyth = IPyth(DS.getAddress("Pyth"));
        pythUpdater = PythUpdater(payable(DS.getAddress("PythUpdater")));
        referralStore = ReferralStore(DS.getAddress("ReferralStore"));
        rebateStore = RebateStore(DS.getAddress("RebateStore"));
    }

    /// @notice Opens a new position or increases existing one
    /// @dev Only callable by other protocol contracts
    function increasePosition(
        uint256 orderId,
        uint256 price,
        address keeper
    ) public onlyContract {
        OrderStore.Order memory order = orderStore.get(orderId);

        // Check if maximum open interest is reached
        riskStore.checkMaxDelta(
            order.asset,
            order.market,
            order.size,
            order.isLong
        );
        positionStore.incrementOI(
            order.asset,
            order.market,
            order.size,
            order.isLong
        );
        funding.updateFundingTracker(order.asset, order.market);

        PositionStore.Position memory position = positionStore.getPosition(
            order.user,
            order.asset,
            order.market
        );
        uint256 averagePrice = (position.size *
            position.price +
            order.size *
            price) / (position.size + order.size);

        riskStore.checkMaxPositionSize(
            order.asset,
            order.market,
            order.size,
            position.size,
            order.isLong,
            position.isLong
        );

        // Populate position fields if new position
        if (position.size == 0) {
            position.user = order.user;
            position.asset = order.asset;
            position.market = order.market;
            position.timestamp = block.timestamp;
            position.isLong = order.isLong;
            position.fundingTracker = funding.getRealTimeFundingTracker(
                order.asset,
                order.market
            );
        } else {
            (, int256 fundingFee) = getPnL(
                position.asset,
                position.market,
                position.isLong,
                price,
                position.price,
                position.size,
                position.fundingTracker
            );

            if (fundingFee != 0) {
                uint256 absFundingFee = fundingFee > 0
                    ? uint256(fundingFee)
                    : uint256(-fundingFee);
                uint256 oldMargin = position.margin;

                if (
                    (position.isLong && fundingFee > 0) ||
                    (!position.isLong && fundingFee < 0)
                ) {
                    if (absFundingFee < position.margin) {
                        position.margin -= absFundingFee;
                        pool.creditTraderLoss(
                            position.user,
                            position.asset,
                            position.market,
                            absFundingFee
                        );
                        uint256 newSize = (position.size * position.margin) /
                            oldMargin;
                        uint256 sizeDiff = position.size - newSize;
                        position.size = newSize;
                        positionStore.decrementOI(
                            position.asset,
                            position.market,
                            sizeDiff,
                            position.isLong
                        );
                    }
                } else {
                    position.margin += absFundingFee;
                    pool.debitTraderProfitWithoutTransfer(
                        position.user,
                        position.asset,
                        position.market,
                        absFundingFee
                    );
                    uint256 newSize = (position.size * position.margin) /
                        oldMargin;
                    uint256 sizeDiff = newSize - position.size;
                    position.size = newSize;
                    positionStore.incrementOI(
                        position.asset,
                        position.market,
                        sizeDiff,
                        position.isLong
                    );
                }
            }
            position.fundingTracker = funding.getRealTimeFundingTracker(
                position.asset,
                position.market
            );
        }

        // Add or update position
        position.size += order.size;
        position.margin += order.margin;
        position.price = averagePrice;

        positionStore.addOrUpdate(position);

        // Remove order
        orderStore.remove(orderId);

        // Credit fee to keeper, pool, stakers, treasury
        creditFee(
            orderId,
            order.user,
            order.asset,
            order.market,
            order.fee,
            false,
            keeper
        );

        emit PositionIncreased(
            orderId,
            order.user,
            order.asset,
            order.market,
            order.isLong,
            order.size,
            order.margin,
            price,
            position.margin,
            position.size,
            position.price,
            position.fundingTracker,
            order.fee
        );
    }

    /// @notice Decreases or closes an existing position
    /// @dev Only callable by other protocol contracts
    function decreasePosition(
        uint256 orderId,
        uint256 price,
        address keeper
    ) external onlyContract {
        OrderStore.Order memory order = orderStore.get(orderId);
        PositionStore.Position memory position = positionStore.getPosition(
            order.user,
            order.asset,
            order.market
        );

        // If position size is less than order size, not all will be executed
        uint256 executedOrderSize = position.size > order.size
            ? order.size
            : position.size;
        uint256 remainingOrderSize = order.size - executedOrderSize;

        uint256 remainingOrderMargin;
        uint256 amountToReturnToUser;

        if (!order.isReduceOnly) {
            // User submitted order.margin when sending the order. Refund the portion of order.margin
            // that executes against the position
            uint256 executedOrderMargin = (order.margin * executedOrderSize) /
                order.size;
            amountToReturnToUser += executedOrderMargin;
            remainingOrderMargin = order.margin - executedOrderMargin;
        }

        // Calculate fee based on executed order size
        uint256 fee = (order.fee * executedOrderSize) / order.size;

        creditFee(
            orderId,
            order.user,
            order.asset,
            order.market,
            fee,
            false,
            keeper
        );

        // If an order is reduce-only, fee is taken from the position's margin.
        uint256 feeToPay = order.isReduceOnly ? fee : 0;

        // Funding update
        positionStore.decrementOI(
            order.asset,
            order.market,
            executedOrderSize,
            position.isLong
        );
        funding.updateFundingTracker(order.asset, order.market);

        // Get PNL of position
        (int256 pnl, int256 fundingFee) = getPnL(
            order.asset,
            order.market,
            position.isLong,
            price,
            position.price,
            executedOrderSize,
            position.fundingTracker
        );

        uint256 executedPositionMargin = (position.margin * executedOrderSize) /
            position.size;

        // If PNL is less than position margin, close position, else update position
        if (pnl <= -1 * int256(position.margin)) {
            pnl = -1 * int256(position.margin);
            executedPositionMargin = position.margin;
            executedOrderSize = position.size;
            position.size = 0;
        } else {
            position.margin -= executedPositionMargin;
            position.size -= executedOrderSize;
            // position.fundingTracker = fundingStore.getFundingTracker(order.asset, order.market);
        }

        // Check for maximum pool drawdown
        riskStore.checkPoolDrawdown(order.asset, pnl);

        if (position.size == 0) {
            // Remove position if size == 0
            positionStore.remove(order.user, order.asset, order.market);
        } else {
            positionStore.addOrUpdate(position);
        }

        // Credit trader loss or debit trader profit based on pnl
        if (pnl < 0) {
            uint256 absPnl = uint256(-1 * pnl);
            pool.creditTraderLoss(
                order.user,
                order.asset,
                order.market,
                absPnl
            );

            uint256 totalPnl = absPnl + feeToPay;

            // If an order is reduce-only, fee is taken from the position's margin as the order's margin is zero.
            if (totalPnl < executedPositionMargin) {
                amountToReturnToUser += executedPositionMargin - totalPnl;
            }
        } else {
            pool.debitTraderProfit(
                order.user,
                order.asset,
                order.market,
                uint256(pnl)
            );

            // If an order is reduce-only, fee is taken from the position's margin as the order's margin is zero.
            amountToReturnToUser += executedPositionMargin - feeToPay;
        }

        // Remove order and transfer funds out
        orderStore.remove(orderId);
        fundStore.transferOut(order.asset, order.user, amountToReturnToUser);

        emit PositionDecreased(
            orderId,
            order.user,
            order.asset,
            order.market,
            order.isLong,
            executedOrderSize,
            executedPositionMargin,
            price,
            position.margin,
            position.size,
            position.price,
            position.fundingTracker,
            feeToPay,
            pnl,
            0,
            fundingFee
        );

        // Open position in opposite direction if size remains
        if (!order.isReduceOnly && remainingOrderSize > 0) {
            OrderStore.Order memory nextOrder = OrderStore.Order({
                orderId: 0,
                user: order.user,
                market: order.market,
                asset: order.asset,
                margin: remainingOrderMargin,
                size: remainingOrderSize,
                price: 0,
                isLong: order.isLong,
                fee: (order.fee * remainingOrderSize) / order.size,
                orderType: 0,
                isReduceOnly: false,
                timestamp: block.timestamp,
                expiry: 0,
                cancelOrderId: 0
            });

            uint256 nextOrderId = orderStore.add(nextOrder);

            increasePosition(nextOrderId, price, keeper);
        }
    }

    /// @notice Close position without taking profits to retrieve margin in black swan scenarios
    function closePositionWithoutProfit(
        address _asset,
        string calldata _market,
        bytes[] calldata priceUpdateData
    ) external {
        address user = msg.sender;

        // check if positions exists
        PositionStore.Position memory position = positionStore.getPosition(
            user,
            _asset,
            _market
        );
        require(position.size > 0, "!position");

        // update funding tracker
        positionStore.decrementOI(
            _asset,
            _market,
            position.size,
            position.isLong
        );
        funding.updateFundingTracker(_asset, _market);

        pythUpdater.updatePriceFeed(priceUpdateData);

        MarketStore.Market memory market = marketStore.get(_market);
        (uint256 price, uint256 publishTime) = _getPythPrice(market.pythFeed);

        require(price > 0, "!price");

        require(block.timestamp - publishTime < market.pythMaxAge, "!max-age");

        (int256 pnl, ) = getPnL(
            _asset,
            _market,
            position.isLong,
            price,
            position.price,
            position.size,
            position.fundingTracker
        );

        // Only profitable positions can be closed this way
        require(pnl >= 0, "!pnl-positive");

        // Remove position and transfer margin out
        positionStore.remove(user, _asset, _market);
        fundStore.transferOut(_asset, user, position.margin);

        emit PositionDecreased(
            0,
            user,
            _asset,
            _market,
            !position.isLong,
            position.size,
            position.margin,
            price,
            position.margin,
            position.size,
            position.price,
            position.fundingTracker,
            0,
            0,
            0,
            0
        );
    }

    /// @notice Add margin to a position to decrease its leverage and push away its liquidation price
    function addMargin(
        address asset,
        string calldata market,
        uint256 margin
    ) external payable ifNotPaused {
        address user = msg.sender;

        PositionStore.Position memory position = positionStore.getPosition(
            user,
            asset,
            market
        );
        require(position.size > 0, "!position");

        // Transfer additional margin in
        if (asset == address(0)) {
            margin = msg.value;
            fundStore.transferIn{value: margin}(asset, user, margin);
        } else {
            fundStore.transferIn(asset, user, margin);
        }

        require(margin > 0, "!margin");

        // update position margin
        position.margin += margin;

        // Check if leverage is above minimum leverage
        uint256 leverage = (UNIT * position.size) / position.margin;
        require(leverage >= UNIT, "!min-leverage");

        // update position
        positionStore.addOrUpdate(position);

        emit MarginIncreased(user, asset, market, margin, position.margin);
    }

    /// @notice Remove margin from a position to increase its leverage
    function removeMargin(
        address asset,
        string calldata market,
        uint256 margin,
        bytes[] calldata priceUpdateData
    ) external ifNotPaused {
        address user = msg.sender;

        MarketStore.Market memory marketInfo = marketStore.get(market);

        PositionStore.Position memory position = positionStore.getPosition(
            user,
            asset,
            market
        );
        require(position.size > 0, "!position");
        require(position.margin > margin, "!margin");

        uint256 remainingMargin = position.margin - margin;

        // Leverage
        uint256 leverageAfterRemoval = (UNIT * position.size) / remainingMargin;
        require(
            leverageAfterRemoval <= marketInfo.maxLeverage * UNIT,
            "!max-leverage"
        );

        pythUpdater.updatePriceFeed(priceUpdateData);

        (uint256 price, uint256 publishTime) = _getPythPrice(
            marketInfo.pythFeed
        );

        require(price > 0, "!price");

        require(
            block.timestamp - publishTime < marketInfo.pythMaxAge,
            "!max-age"
        );

        (int256 upl, ) = getPnL(
            asset,
            market,
            position.isLong,
            price,
            position.price,
            position.size,
            position.fundingTracker
        );

        if (upl < 0) {
            uint256 absUpl = uint256(-1 * upl);
            require(
                absUpl <
                    (remainingMargin *
                        (BPS_DIVIDER - positionStore.removeMarginBuffer())) /
                        BPS_DIVIDER,
                "!upl"
            );
        }

        // Update position and transfer margin out
        position.margin = remainingMargin;
        positionStore.addOrUpdate(position);

        fundStore.transferOut(asset, user, margin);

        emit MarginDecreased(user, asset, market, margin, position.margin);
    }

    /// @notice Credit fee to Keeper, Pool, Stakers, and Treasury
    /// @dev Only callable by other protocol contracts
    function creditFee(
        uint256 orderId,
        address user,
        address asset,
        string memory market,
        uint256 fee,
        bool isLiquidation,
        address keeper
    ) public onlyContract {
        if (fee == 0) return;

        uint256 keeperShare = positionStore.keeperFeeShare();
        uint256 buyBackShare = buyBackStore.feeShare();
        uint256 poolShare = poolStore.feeShare();
        // multiply fee by UNIT (10^18) to increase position
        fee = fee * UNIT;

        uint256 keeperFee;
        if (keeper != address(0) && keeperShare > 0) {
            keeperFee = (fee * keeperShare) / BPS_DIVIDER;
        }

        // Calculate fees
        address referrer = referralStore.getReferrer(user);
        uint256 referrerRebate = 0;
        if (referrer != address(0)) {
            referrerRebate =
                (fee * referralStore.getRebateFeeShare(referrer)) /
                BPS_DIVIDER;
        }
        uint256 netFee = fee - keeperFee - referrerRebate;
        uint256 feeToBuyBack = buyBackShare == 0
            ? 0
            : (netFee * buyBackShare) / BPS_DIVIDER;
        uint256 feeToPool = poolShare == 0
            ? 0
            : (netFee * poolShare) / BPS_DIVIDER;
        uint256 feeToTreasury = netFee - feeToBuyBack - feeToPool;

        // Increment balances, transfer fees out
        // Divide fee by UNIT to get original fee value back
        poolStore.incrementBufferBalance(asset, feeToPool / UNIT);
        buyBackStore.incrementAssetBalance(asset, feeToBuyBack / UNIT);
        if (referrer != address(0)) {
            rebateStore.incrementRebate(referrer, asset, referrerRebate / UNIT);
        }
        fundStore.transferOut(
            asset,
            DS.getAddress("treasury"),
            feeToTreasury / UNIT
        );
        fundStore.transferOut(asset, keeper, keeperFee / UNIT);

        emit FeePaid(
            orderId,
            user,
            asset,
            market,
            fee / UNIT, // paid by user
            feeToPool / UNIT,
            feeToBuyBack / UNIT,
            feeToTreasury / UNIT,
            keeperFee / UNIT,
            isLiquidation,
            referrerRebate / UNIT
        );
    }

    /// @notice Get pnl of a position
    /// @param asset Base asset of position
    /// @param market Market position was submitted on
    /// @param isLong Wether position is long or short
    /// @param price Current price of market
    /// @param positionPrice Average execution price of position
    /// @param size Positions size (margin * leverage) in wei
    /// @param fundingTracker Market funding rate tracker
    /// @return pnl Profit and loss of position
    /// @return fundingFee Funding fee of position
    function getPnL(
        address asset,
        string memory market,
        bool isLong,
        uint256 price,
        uint256 positionPrice,
        uint256 size,
        int256 fundingTracker
    ) public view returns (int256 pnl, int256 fundingFee) {
        if (price == 0 || positionPrice == 0 || size == 0) return (0, 0);

        if (isLong) {
            pnl =
                (int256(size) * (int256(price) - int256(positionPrice))) /
                int256(positionPrice);
        } else {
            pnl =
                (int256(size) * (int256(positionPrice) - int256(price))) /
                int256(positionPrice);
        }

        int256 currentFundingTracker = funding.getRealTimeFundingTracker(
            asset,
            market
        );
        fundingFee =
            (int256(size) * (currentFundingTracker - fundingTracker)) /
            (int256(BPS_DIVIDER) * int256(UNIT)); // funding tracker is in UNIT * bps

        if (isLong) {
            pnl -= fundingFee; // positive = longs pay, negative = longs receive
        } else {
            pnl += fundingFee; // positive = shorts receive, negative = shorts pay
        }

        return (pnl, fundingFee);
    }

    /// @dev Returns pyth price converted to 18 decimals
    function _getPythPrice(
        bytes32 priceFeedId
    ) internal view returns (uint256, uint256) {
        // It will revert if the price is older than maxAge
        PythStructs.Price memory retrievedPrice = pyth.getPriceUnsafe(
            priceFeedId
        );

        // Convert price to 18 decimals
        uint256 price = PythPriceUtils.toUint256(retrievedPrice);
        uint256 publishTime = retrievedPrice.publishTime;

        return (price, publishTime);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

import "./IERC20.sol";

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

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

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

// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;

import "./PythStructs.sol";
import "./IPythEvents.sol";

/// @title Consume prices from the Pyth Network (https://pyth.network/).
/// @dev Please refer to the guidance at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how to consume prices safely.
/// @author Pyth Data Association
interface IPyth is IPythEvents {
    /// @notice Returns the price of a price feed without any sanity checks.
    /// @dev This function returns the most recent price update in this contract without any recency checks.
    /// This function is unsafe as the returned price update may be arbitrarily far in the past.
    ///
    /// Users of this function should check the `publishTime` in the price to ensure that the returned price is
    /// sufficiently recent for their application. If you are considering using this function, it may be
    /// safer / easier to use `getPriceNoOlderThan`.
    /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
    function getPriceUnsafe(
        bytes32 id
    ) external view returns (PythStructs.Price memory price);

    /// @notice Returns the price that is no older than `age` seconds of the current time.
    /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in
    /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
    /// recently.
    /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
    function getPriceNoOlderThan(
        bytes32 id,
        uint age
    ) external view returns (PythStructs.Price memory price);

    /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.
    /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.
    /// However, if the price is not recent this function returns the latest available price.
    ///
    /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that
    /// the returned price is recent or useful for any particular application.
    ///
    /// Users of this function should check the `publishTime` in the price to ensure that the returned price is
    /// sufficiently recent for their application. If you are considering using this function, it may be
    /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.
    /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
    function getEmaPriceUnsafe(
        bytes32 id
    ) external view returns (PythStructs.Price memory price);

    /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds
    /// of the current time.
    /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in
    /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
    /// recently.
    /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
    function getEmaPriceNoOlderThan(
        bytes32 id,
        uint age
    ) external view returns (PythStructs.Price memory price);

    /// @notice Update price feeds with given update messages.
    /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
    /// `getUpdateFee` with the length of the `updateData` array.
    /// Prices will be updated if they are more recent than the current stored prices.
    /// The call will succeed even if the update is not the most recent.
    /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.
    /// @param updateData Array of price update data.
    function updatePriceFeeds(bytes[] calldata updateData) external payable;

    /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is
    /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the
    /// given `publishTimes` for the price feeds and does not read the actual price update publish time within `updateData`.
    ///
    /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
    /// `getUpdateFee` with the length of the `updateData` array.
    ///
    /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime
    /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have
    /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.
    /// Otherwise, it calls updatePriceFeeds method to update the prices.
    ///
    /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.
    /// @param updateData Array of price update data.
    /// @param priceIds Array of price ids.
    /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`
    function updatePriceFeedsIfNecessary(
        bytes[] calldata updateData,
        bytes32[] calldata priceIds,
        uint64[] calldata publishTimes
    ) external payable;

    /// @notice Returns the required fee to update an array of price updates.
    /// @param updateData Array of price update data.
    /// @return feeAmount The required fee in Wei.
    function getUpdateFee(
        bytes[] calldata updateData
    ) external view returns (uint feeAmount);

    /// @notice Parse `updateData` and return price feeds of the given `priceIds` if they are all published
    /// within `minPublishTime` and `maxPublishTime`.
    ///
    /// You can use this method if you want to use a Pyth price at a fixed time and not the most recent price;
    /// otherwise, please consider using `updatePriceFeeds`. This method may store the price updates on-chain, if they
    /// are more recent than the current stored prices.
    ///
    /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
    /// `getUpdateFee` with the length of the `updateData` array.
    ///
    ///
    /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is
    /// no update for any of the given `priceIds` within the given time range.
    /// @param updateData Array of price update data.
    /// @param priceIds Array of price ids.
    /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.
    /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.
    /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).
    function parsePriceFeedUpdates(
        bytes[] calldata updateData,
        bytes32[] calldata priceIds,
        uint64 minPublishTime,
        uint64 maxPublishTime
    ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);

    /// @notice Similar to `parsePriceFeedUpdates` but ensures the updates returned are
    /// the first updates published in minPublishTime. That is, if there are multiple updates for a given timestamp,
    /// this method will return the first update. This method may store the price updates on-chain, if they
    /// are more recent than the current stored prices.
    ///
    ///
    /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is
    /// no update for any of the given `priceIds` within the given time range and uniqueness condition.
    /// @param updateData Array of price update data.
    /// @param priceIds Array of price ids.
    /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.
    /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.
    /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).
    function parsePriceFeedUpdatesUnique(
        bytes[] calldata updateData,
        bytes32[] calldata priceIds,
        uint64 minPublishTime,
        uint64 maxPublishTime
    ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);
}

File 4 of 33 : PythStructs.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;

contract PythStructs {
    // A price with a degree of uncertainty, represented as a price +- a confidence interval.
    //
    // The confidence interval roughly corresponds to the standard error of a normal distribution.
    // Both the price and confidence are stored in a fixed-point numeric representation,
    // `x * (10^expo)`, where `expo` is the exponent.
    //
    // Please refer to the documentation at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how
    // to how this price safely.
    struct Price {
        // Price
        int64 price;
        // Confidence interval around the price
        uint64 conf;
        // Price exponent
        int32 expo;
        // Unix timestamp describing when the price was published
        uint publishTime;
    }

    // PriceFeed represents a current aggregate price from pyth publisher feeds.
    struct PriceFeed {
        // The price ID.
        bytes32 id;
        // Latest available price
        Price price;
        // Latest available exponentially-weighted moving average price
        Price emaPrice;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";

/// @title AssetStore
/// @notice Persistent storage of supported assets
contract AssetStore is Roles {
    // Asset info struct
    struct Asset {
        uint256 minSize;
        address chainlinkFeed;
    }

    // Asset list
    address[] public assetList;
    mapping(address => Asset) private assets;

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @notice Set or update an asset
    /// @dev Only callable by governance
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param assetInfo Struct containing minSize and chainlinkFeed
    function set(address asset, Asset memory assetInfo) external onlyGov {
        assets[asset] = assetInfo;
        for (uint256 i = 0; i < assetList.length; i++) {
            if (assetList[i] == asset) return;
        }
        assetList.push(asset);
    }

    /// @notice Returns asset struct of `asset`
    /// @param asset Asset address, e.g. address(0) for ETH
    function get(address asset) external view returns (Asset memory) {
        return assets[asset];
    }

    /// @notice Get a list of all supported assets
    function getAssetList() external view returns (address[] memory) {
        return assetList;
    }

    /// @notice Get number of supported assets
    function getAssetCount() external view returns (uint256) {
        return assetList.length;
    }

    /// @notice Returns asset address at `index`
    /// @param index index of asset
    function getAssetByIndex(uint256 index) external view returns (address) {
        return assetList[index];
    }

    /// @notice Returns true if `asset` is supported
    /// @param asset Asset address, e.g. address(0) for ETH
    function isSupported(address asset) external view returns (bool) {
        return assets[asset].minSize > 0;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

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

/// @title DataStore
/// @notice General purpose storage contract
/// @dev Access is restricted to governance
contract DataStore is Governable {
    // Key-value stores
    mapping(bytes32 => uint256) public uintValues;
    mapping(bytes32 => int256) public intValues;
    mapping(bytes32 => address) public addressValues;
    mapping(bytes32 => bytes32) public dataValues;
    mapping(bytes32 => bool) public boolValues;
    mapping(bytes32 => string) public stringValues;

    function initialize() external initializer {
        _setGov(msg.sender);
    }

    /// @param key The key for the record
    /// @param value value to store
    /// @param overwrite Overwrites existing value if set to true
    function setUint(
        string calldata key,
        uint256 value,
        bool overwrite
    ) external onlyGov returns (bool) {
        bytes32 hash = getHash(key);
        if (overwrite || uintValues[hash] == 0) {
            uintValues[hash] = value;
            return true;
        }
        return false;
    }

    /// @param key The key for the record
    function getUint(string calldata key) external view returns (uint256) {
        return uintValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value value to store
    /// @param overwrite Overwrites existing value if set to true
    function setInt(
        string calldata key,
        int256 value,
        bool overwrite
    ) external onlyGov returns (bool) {
        bytes32 hash = getHash(key);
        if (overwrite || intValues[hash] == 0) {
            intValues[hash] = value;
            return true;
        }
        return false;
    }

    /// @param key The key for the record
    function getInt(string calldata key) external view returns (int256) {
        return intValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value address to store
    /// @param overwrite Overwrites existing value if set to true
    function setAddress(
        string calldata key,
        address value,
        bool overwrite
    ) external onlyGov returns (bool) {
        bytes32 hash = getHash(key);
        if (overwrite || addressValues[hash] == address(0)) {
            addressValues[hash] = value;
            return true;
        }
        return false;
    }

    /// @param key The key for the record
    function getAddress(string calldata key) external view returns (address) {
        return addressValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value byte value to store
    function setData(
        string calldata key,
        bytes32 value
    ) external onlyGov returns (bool) {
        dataValues[getHash(key)] = value;
        return true;
    }

    /// @param key The key for the record
    function getData(string calldata key) external view returns (bytes32) {
        return dataValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value value to store (true / false)
    function setBool(
        string calldata key,
        bool value
    ) external onlyGov returns (bool) {
        boolValues[getHash(key)] = value;
        return true;
    }

    /// @param key The key for the record
    function getBool(string calldata key) external view returns (bool) {
        return boolValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value string to store
    function setString(
        string calldata key,
        string calldata value
    ) external onlyGov returns (bool) {
        stringValues[getHash(key)] = value;
        return true;
    }

    /// @param key The key for the record
    function getString(
        string calldata key
    ) external view returns (string memory) {
        return stringValues[getHash(key)];
    }

    /// @param key string to hash
    function getHash(string memory key) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(key));
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import "./Roles.sol";

/// @title FundStore
/// @notice Storage of protocol funds
contract FundStore is Roles, ReentrancyGuard {
    // Libraries
    using SafeERC20 for IERC20;
    using Address for address payable;

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @notice Transfers `amount` of `asset` in
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param from Address where asset is transferred from
    function transferIn(
        address asset,
        address from,
        uint256 amount
    ) external payable onlyContract {
        if (asset == address(0)) {
            require(amount > 0, "ETH:bad-amount");
            require(msg.value == amount, "ETH:bad-amount");
            return;
        }

        require(msg.value == 0, "ERC20:bad-value");
        if (amount == 0) return;
        IERC20(asset).safeTransferFrom(from, address(this), amount);
    }

    /// @notice Transfers `amount` of `asset` out
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param to Address where asset is transferred to
    function transferOut(
        address asset,
        address to,
        uint256 amount
    ) external nonReentrant onlyContract {
        if (amount == 0 || to == address(0)) return;
        if (asset == address(0)) {
            (bool success, ) = payable(to).call{value: amount}("");
            require(success, "Transfer failed");
        } else {
            IERC20(asset).safeTransfer(to, amount);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";

/// @title FundingStore
/// @notice Storage of funding trackers for all supported markets
contract FundingStore is Roles {
    // interval used to calculate accrued funding
    uint256 public fundingInterval;

    // asset => market => funding tracker (long) (short is opposite)
    mapping(address => mapping(string => int256)) private fundingTrackers;

    // asset => market => last time fundingTracker was updated. In seconds.
    mapping(address => mapping(string => uint256)) private lastUpdated;

    // asset => market => last ema funding rate
    mapping(address => mapping(string => int256)) private lastEmaFundingRate;

    // asset => market => capped ema funding rate
    mapping(address => mapping(string => int256))
        private lastCappedEmaFundingRate;

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        fundingInterval = 8 hours;
    }

    /// @notice updates `fundingInterval`
    /// @dev Only callable by governance
    /// @param interval new funding interval, in seconds
    function setFundingInterval(uint256 interval) external onlyGov {
        require(interval > 0, "!interval");
        fundingInterval = interval;
    }

    /// @notice updates `lastEmaFundingRate` mapping
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param emaFundingRate Last ema funding rate
    function setLastEmaFundingRate(
        address asset,
        string calldata market,
        int256 emaFundingRate
    ) external onlyContract {
        lastEmaFundingRate[asset][market] = emaFundingRate;
    }

    /// @notice updates `lastCappedEmaFundingRate` mapping
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param cappedEmaFundingRate Last capped ema funding rate
    function setLastCappedEmaFundingRate(
        address asset,
        string calldata market,
        int256 cappedEmaFundingRate
    ) external onlyContract {
        lastCappedEmaFundingRate[asset][market] = cappedEmaFundingRate;
    }

    /// @notice returns `lastEmaFundingRate` mapping
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    function getLastEmaFundingRate(
        address asset,
        string calldata market
    ) external view returns (int256) {
        return lastEmaFundingRate[asset][market];
    }

    /// @notice returns `lastCappedEmaFundingRate` mapping
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    function getLastCappedEmaFundingRate(
        address asset,
        string calldata market
    ) external view returns (int256) {
        return lastCappedEmaFundingRate[asset][market];
    }

    /// @notice Updates `lastUpdated` mapping
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked by Funding.updateFundingTracker
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param timestamp Timestamp in seconds
    function setLastUpdated(
        address asset,
        string calldata market,
        uint256 timestamp
    ) external onlyContract {
        lastUpdated[asset][market] = timestamp;
    }

    /// @notice updates `fundingTracker` mapping
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked by Funding.updateFundingTracker
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param fundingIncrement Accrued funding of given asset and market
    function updateFundingTracker(
        address asset,
        string calldata market,
        int256 fundingIncrement
    ) external onlyContract {
        fundingTrackers[asset][market] += fundingIncrement;
    }

    /// @notice Returns last update timestamp of `asset` and `market`
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    function getLastUpdated(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return lastUpdated[asset][market];
    }

    /// @notice Returns funding tracker of `asset` and `market`
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    function getFundingTracker(
        address asset,
        string calldata market
    ) external view returns (int256) {
        return fundingTrackers[asset][market];
    }

    /// @notice Returns funding trackers of `assets` and `markets`
    /// @param assets Array of asset addresses
    /// @param markets Array of market strings
    function getFundingTrackers(
        address[] calldata assets,
        string[] calldata markets
    ) external view returns (int256[] memory fts) {
        uint256 length = assets.length;
        fts = new int256[](length);
        for (uint256 i = 0; i < length; i++) {
            fts[i] = fundingTrackers[assets[i]][markets[i]];
        }
        return fts;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";

/// @title MarketStore
/// @notice Persistent storage of supported markets
contract MarketStore is Roles {
    // Market struct
    struct Market {
        string name; // Market's full name, e.g. Bitcoin / U.S. Dollar
        string category; // crypto, fx, commodities, or indices
        address chainlinkFeed; // Price feed contract address
        uint256 maxLeverage; // No decimals
        uint256 maxDeviation; // In bps, max price difference from oracle to chainlink price
        uint256 fee; // In bps. 10 = 0.1%
        uint256 liqThreshold; // In bps
        uint256 fundingFactor; // Yearly funding rate if OI is completely skewed to one side. In bps.
        uint256 minOrderAge; // Min order age before is can be executed. In seconds
        uint256 pythMaxAge; // Max Pyth submitted price age, in seconds
        bytes32 pythFeed; // Pyth price feed id
        bool allowChainlinkExecution; // Allow anyone to execute orders with chainlink
        bool isReduceOnly; // accepts only reduce only orders
        uint256 minFactor; // funding rate min factor
        uint256 sampleSize; // funding rate sample size
    }

    // Constants to limit gov power
    uint256 public constant BPS_DIVIDER = 10000; // 100%
    uint256 public constant MAX_FEE = 1000; // 10%
    uint256 public constant MAX_DEVIATION = 1000; // 10%
    uint256 public constant MAX_LIQTHRESHOLD = 10000; // 100%
    uint256 public constant MAX_MIN_ORDER_AGE = 30;
    uint256 public constant MIN_PYTH_MAX_AGE = 3;

    // list of supported markets
    string[] public marketList; // "ETH-USD", "BTC-USD", etc
    mapping(string => Market) private markets;

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @notice Set or update a market
    /// @dev Only callable by governance
    /// @param market String identifier, e.g. "ETH-USD"
    /// @param marketInfo Market struct containing required market data
    function set(
        string calldata market,
        Market memory marketInfo
    ) external onlyGov {
        require(marketInfo.fee <= MAX_FEE, "!max-fee");
        require(marketInfo.maxLeverage >= 1, "!max-leverage");
        require(marketInfo.maxDeviation <= MAX_DEVIATION, "!max-deviation");
        require(
            marketInfo.liqThreshold <= MAX_LIQTHRESHOLD,
            "!max-liqthreshold"
        );
        require(
            marketInfo.minOrderAge <= MAX_MIN_ORDER_AGE,
            "!max-minorderage"
        );
        require(marketInfo.pythMaxAge >= MIN_PYTH_MAX_AGE, "!min-pythmaxage");
        require(
            marketInfo.maxLeverage * marketInfo.fee <= BPS_DIVIDER,
            "!max-leverage-fee"
        );

        markets[market] = marketInfo;
        for (uint256 i = 0; i < marketList.length; i++) {
            // check if market already exists, if yes return
            if (
                keccak256(abi.encodePacked(marketList[i])) ==
                keccak256(abi.encodePacked(market))
            ) return;
        }
        marketList.push(market);
    }

    /// @notice Returns market struct of `market`
    /// @param market String identifier, e.g. "ETH-USD"
    function get(string calldata market) external view returns (Market memory) {
        return markets[market];
    }

    /// @notice Returns market struct array of specified markets
    /// @param _markets Array of market strings, e.g. ["ETH-USD", "BTC-USD"]
    function getMany(
        string[] calldata _markets
    ) external view returns (Market[] memory) {
        uint256 length = _markets.length;
        Market[] memory _marketInfos = new Market[](length);
        for (uint256 i = 0; i < length; i++) {
            _marketInfos[i] = markets[_markets[i]];
        }
        return _marketInfos;
    }

    /// @notice Returns market identifier at `index`
    /// @param index index of marketList
    function getMarketByIndex(
        uint256 index
    ) external view returns (string memory) {
        return marketList[index];
    }

    /// @notice Get a list of all supported markets
    function getMarketList() external view returns (string[] memory) {
        return marketList;
    }

    /// @notice Get number of supported markets
    function getMarketCount() external view returns (uint256) {
        return marketList.length;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./EnumerableSet.sol";

import "./Roles.sol";

/// @title OrderStore
/// @notice Persistent storage for Orders.sol
contract OrderStore is Roles {
    // Libraries
    using EnumerableSet for EnumerableSet.UintSet;

    // Order struct
    struct Order {
        uint256 orderId; // incremental order id
        address user; // user that usubmitted the order
        address asset; // Asset address, e.g. address(0) for ETH
        string market; // Market this order was submitted on
        uint256 margin; // Collateral tied to this order. In wei
        uint256 size; // Order size (margin * leverage). In wei
        uint256 price; // The order's price if its a trigger or protected order
        uint256 fee; // Fee amount paid. In wei
        bool isLong; // Wether the order is a buy or sell order
        uint8 orderType; // 0 = market, 1 = limit, 2 = stop
        bool isReduceOnly; // Wether the order is reduce-only
        uint256 timestamp; // block.timestamp at which the order was submitted
        uint256 expiry; // block.timestamp at which the order expires
        uint256 cancelOrderId; // orderId to cancel when this order executes
    }

    uint256 public oid; // incremental order id
    mapping(uint256 => Order) private orders; // order id => Order
    mapping(address => EnumerableSet.UintSet) private userOrderIds; // user => [order ids..]
    EnumerableSet.UintSet private marketOrderIds; // [order ids..]
    EnumerableSet.UintSet private triggerOrderIds; // [order ids..]

    uint256 public maxMarketOrderTTL;
    uint256 public maxTriggerOrderTTL;
    uint256 public chainlinkCooldown;

    bool public areNewOrdersPaused;
    bool public isProcessingPaused;

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        maxMarketOrderTTL = 5 minutes;
        maxTriggerOrderTTL = 180 days;
        chainlinkCooldown = 5 minutes;
    }

    // Setters

    /// @notice Disable submitting new orders
    /// @dev Only callable by governance
    function setAreNewOrdersPaused(bool b) external onlyGov {
        areNewOrdersPaused = b;
    }

    /// @notice Disable processing new orders
    /// @dev Only callable by governance
    function setIsProcessingPaused(bool b) external onlyGov {
        isProcessingPaused = b;
    }

    /// @notice Set duration until market orders expire
    /// @dev Only callable by governance
    /// @param amount Duration in seconds
    function setMaxMarketOrderTTL(uint256 amount) external onlyGov {
        require(amount > 0, "!amount");
        require(amount < maxTriggerOrderTTL, "amount > maxTriggerOrderTTL");
        maxMarketOrderTTL = amount;
    }

    /// @notice Set duration until trigger orders expire
    /// @dev Only callable by governance
    /// @param amount Duration in seconds
    function setMaxTriggerOrderTTL(uint256 amount) external onlyGov {
        require(amount > 0, "!amount");
        require(amount > maxMarketOrderTTL, "amount < maxMarketOrderTTL");
        maxTriggerOrderTTL = amount;
    }

    /// @notice Set duration after orders can be executed with chainlink
    /// @dev Only callable by governance
    /// @param amount Duration in seconds
    function setChainlinkCooldown(uint256 amount) external onlyGov {
        require(amount > 0, "!amount");
        chainlinkCooldown = amount;
    }

    /// @notice Adds order to storage
    /// @dev Only callable by other protocol contracts
    function add(Order memory order) external onlyContract returns (uint256) {
        uint256 nextOrderId = ++oid;
        order.orderId = nextOrderId;
        orders[nextOrderId] = order;
        userOrderIds[order.user].add(nextOrderId);
        if (order.orderType == 0) {
            marketOrderIds.add(order.orderId);
        } else {
            triggerOrderIds.add(order.orderId);
        }
        return nextOrderId;
    }

    /// @notice Removes order from store
    /// @dev Only callable by other protocol contracts
    /// @param orderId Order to remove
    function remove(uint256 orderId) external onlyContract {
        Order memory order = orders[orderId];
        if (order.size == 0) return;
        userOrderIds[order.user].remove(orderId);
        marketOrderIds.remove(orderId);
        triggerOrderIds.remove(orderId);
        delete orders[orderId];
    }

    /// @notice Removes order from store
    /// @dev Only callable by other protocol contracts
    /// @param orderId Order to remove
    function unsafeRemove(uint256 orderId) external onlyGov {
        Order memory order = orders[orderId];
        userOrderIds[order.user].remove(orderId);
        marketOrderIds.remove(orderId);
        triggerOrderIds.remove(orderId);
        delete orders[orderId];
    }

    /// @notice Removes many orders from store
    /// @dev Only callable by governance
    /// @param orderIds Orders to remove
    function unsafeRemoveMany(uint256[] calldata orderIds) external onlyGov {
        for (uint256 i = 0; i < orderIds.length; i++) {
            uint256 orderId = orderIds[i];
            Order memory order = orders[orderId];
            userOrderIds[order.user].remove(orderId);
            marketOrderIds.remove(orderId);
            triggerOrderIds.remove(orderId);
            delete orders[orderId];
        }
    }

    /// @notice Updates `cancelOrderId` of `orderId`, e.g. TP order cancels a SL order and vice versa
    /// @dev Only callable by other protocol contracts
    /// @param orderId Order which cancels `cancelOrderId` on execution
    /// @param cancelOrderId Order to cancel when `orderId` executes
    function updateCancelOrderId(
        uint256 orderId,
        uint256 cancelOrderId
    ) external onlyContract {
        Order storage order = orders[orderId];
        order.cancelOrderId = cancelOrderId;
    }

    /// @notice Returns a single order
    /// @param orderId Order to get
    function get(uint256 orderId) external view returns (Order memory) {
        return orders[orderId];
    }

    /// @notice Returns many orders
    /// @param orderIds Orders to get, e.g. [1, 2, 5]
    function getMany(
        uint256[] calldata orderIds
    ) external view returns (Order[] memory) {
        uint256 length = orderIds.length;
        Order[] memory _orders = new Order[](length);

        for (uint256 i = 0; i < length; i++) {
            _orders[i] = orders[orderIds[i]];
        }

        return _orders;
    }

    /// @notice Returns market orders
    /// @param length Amount of market orders to return
    function getMarketOrders(
        uint256 length
    ) external view returns (Order[] memory) {
        uint256 _length = marketOrderIds.length();
        if (length > _length) length = _length;

        Order[] memory _orders = new Order[](length);

        for (uint256 i = 0; i < length; i++) {
            _orders[i] = orders[marketOrderIds.at(i)];
        }

        return _orders;
    }

    /// @notice Returns trigger orders
    /// @param length Amount of trigger orders to return
    /// @param offset Offset to start
    function getTriggerOrders(
        uint256 length,
        uint256 offset
    ) external view returns (Order[] memory) {
        uint256 _length = triggerOrderIds.length();
        require(offset <= _length, "Offset out of bounds");

        uint256 availableLength = _length - offset;
        uint256 resultLength = length > availableLength
            ? availableLength
            : length;
        Order[] memory _orders = new Order[](resultLength);

        for (uint256 i = 0; i < resultLength; i++) {
            _orders[i] = orders[triggerOrderIds.at(i + offset)];
        }

        return _orders;
    }

    /// @notice Returns orders of `user`
    function getUserOrders(
        address user
    ) external view returns (Order[] memory) {
        uint256 length = userOrderIds[user].length();
        Order[] memory _orders = new Order[](length);

        for (uint256 i = 0; i < length; i++) {
            _orders[i] = orders[userOrderIds[user].at(i)];
        }

        return _orders;
    }

    /// @notice Returns amount of market orders
    function getMarketOrderCount() external view returns (uint256) {
        return marketOrderIds.length();
    }

    /// @notice Returns amount of trigger orders
    function getTriggerOrderCount() external view returns (uint256) {
        return triggerOrderIds.length();
    }

    /// @notice Returns order amount of `user`
    function getUserOrderCount(address user) external view returns (uint256) {
        return userOrderIds[user].length();
    }

    /// @notice Returns true if order is from `user`
    /// @param orderId order to check
    /// @param user user to check
    function isUserOrder(
        uint256 orderId,
        address user
    ) external view returns (bool) {
        return userOrderIds[user].contains(orderId);
    }
}

File 11 of 33 : PoolStore.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";

/// @title PoolStore
/// @notice Persistent storage for Pool.sol
contract PoolStore is Roles {
    // Constants
    uint256 public constant BPS_DIVIDER = 10000;

    // State variables
    uint256 public feeShare;
    uint256 public depositId;
    uint256[] public lockupPeriods;

    mapping(address => uint256) private clpSupply; // asset => clp supply

    mapping(address => uint256) private balances; // asset => balance
    mapping(address => mapping(address => uint256)) private userClpBalances; // asset => account => clp amount

    mapping(address => mapping(address => uint256[]))
        private depositIdsForAccount; // account => asset => [depositIds..]
    mapping(uint256 => uint256) private depositClpBalances; // depositId => clp balance
    mapping(uint256 => uint256) private depositTimestamps; // depositId => timestamp

    mapping(address => uint256) private bufferBalances; // asset => balance
    mapping(address => uint256) private lastPaid; // asset => timestamp

    mapping(address => uint256) private bufferPayoutPeriods; // asset => period

    // Custom fees (deposit/withdraw) configuration
    mapping(address => bool) private customWithdrawalTaxesActive; // asset => is custom withdrawal tax active
    mapping(address => uint256) private withdrawalTaxes; // asset => custom withdrawal tax bps

    mapping(address => bool) private customDepositTaxesUnlocked; // asset => is custom deposit tax unlocked
    mapping(address => bool) private customDepositTaxesLocked; // asset => is custom deposit tax locked
    mapping(address => uint256) private depositTaxesUnlocked; // asset => custom deposit tax bps for unlocked deposits
    mapping(address => uint256) private depositTaxLocked; // asset => custom deposit tax bps for locked deposits

    function initialize(
        address rs,
        uint256[] calldata periods
    ) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        feeShare = 5000;
        depositId = 0;
        for (uint256 i = 0; i < periods.length; i++) {
            lockupPeriods.push(periods[i]);
        }
    }

    /// @notice Set pool fee
    /// @dev Only callable by governance
    /// @param bps fee share in bps
    function setFeeShare(uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        feeShare = bps;
    }

    /// @notice Set lockup periods
    /// @dev Only callable by governance
    /// @param periods Lockup periods in seconds (can include 0 for no lockup)
    function setLockupPeriods(uint256[] calldata periods) external onlyGov {
        require(periods.length > 0, "!length");

        delete lockupPeriods;
        for (uint256 i = 0; i < periods.length; i++) {
            lockupPeriods.push(periods[i]);
        }
    }

    /// @notice Set buffer payout periods
    /// @dev Only callable by governance
    /// @param assets Assets
    /// @param periods Buffer payout periods in seconds
    function setBufferPayoutPeriods(
        address[] calldata assets,
        uint256[] calldata periods
    ) external onlyGov {
        require(periods.length == assets.length, "!length");
        for (uint256 i = 0; i < assets.length; i++) {
            require(periods[i] > 0, "!period");
            bufferPayoutPeriods[assets[i]] = periods[i];
        }
    }

    /// @notice Returns buffer payout period for an asset
    /// @param asset Asset
    /// @return Buffer payout period in seconds
    function getBufferPayoutPeriod(
        address asset
    ) external view returns (uint256) {
        return bufferPayoutPeriods[asset];
    }

    /// @notice Enable/disable custom deposit tax for an asset
    /// @param _isActive Whether custom deposit tax is active
    /// @param asset Asset address
    function setCustomDepositTaxesLocked(
        bool _isActive,
        address asset
    ) external onlyGov {
        customDepositTaxesLocked[asset] = _isActive;
    }

    /// @notice Set custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    /// @param tax Custom deposit tax in bps
    function setDepositTaxLocked(address asset, uint256 tax) external onlyGov {
        require(tax < BPS_DIVIDER, "!tax");
        depositTaxLocked[asset] = tax;
    }

    /// @notice Enable/disable custom deposit tax for an asset
    /// @param _isActive Whether custom deposit tax is active
    /// @param asset Asset address
    function setCustomDepositTaxesUnlocked(
        bool _isActive,
        address asset
    ) external onlyGov {
        customDepositTaxesUnlocked[asset] = _isActive;
    }

    /// @notice Set custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    /// @param tax Custom deposit tax in bps
    function setDepositTaxUnlocked(
        address asset,
        uint256 tax
    ) external onlyGov {
        require(tax < BPS_DIVIDER, "!tax");
        depositTaxesUnlocked[asset] = tax;
    }

    /// @notice Returns whether custom deposit tax (locked) is active for an asset
    /// @param asset Asset address
    function isCustomDepositTaxesLockedActive(
        address asset
    ) external view returns (bool) {
        return customDepositTaxesLocked[asset];
    }

    /// @notice Returns whether custom deposit tax (unlocked) is active for an asset
    /// @param asset Asset address
    function isCustomDepositTaxesUnlockedActive(
        address asset
    ) external view returns (bool) {
        return customDepositTaxesUnlocked[asset];
    }

    /// @notice Returns custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    function getDepositTaxLocked(
        address asset
    ) external view returns (uint256) {
        return depositTaxLocked[asset];
    }

    /// @notice Returns custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    function getDepositTaxUnlocked(
        address asset
    ) external view returns (uint256) {
        return depositTaxesUnlocked[asset];
    }

    /// @notice Enable/disable custom withdrawal tax for an asset
    /// @param _isActive Whether custom withdrawal tax is active
    /// @param asset Asset address
    function setCustomWithdrawalTaxes(
        bool _isActive,
        address asset
    ) external onlyGov {
        customWithdrawalTaxesActive[asset] = _isActive;
    }

    /// @notice Set custom withdrawal tax (in bps) for an asset
    /// @param asset Asset address
    /// @param tax Custom withdrawal tax in bps
    function setWithdrawalTax(address asset, uint256 tax) external onlyGov {
        withdrawalTaxes[asset] = tax;
    }

    /// @notice Returns whether custom withdrawal tax is active for an asset
    /// @param asset Asset address
    function isCustomWithdrawalTaxesActive(
        address asset
    ) external view returns (bool) {
        return customWithdrawalTaxesActive[asset];
    }

    /// @notice Returns custom withdrawal tax (bps) for an asset
    /// @param asset Asset address
    function getWithdrawalTax(address asset) external view returns (uint256) {
        return withdrawalTaxes[asset];
    }

    /// @notice Increments pool balance
    /// @dev Only callable by other protocol contracts
    function incrementBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        balances[asset] += amount;
    }

    /// @notice Decrements pool balance
    /// @dev Only callable by other protocol contracts
    function decrementBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        balances[asset] = balances[asset] <= amount
            ? 0
            : balances[asset] - amount;
    }

    /// @notice Increments buffer balance
    /// @dev Only callable by other protocol contracts
    function incrementBufferBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        bufferBalances[asset] += amount;
    }

    /// @notice Decrements buffer balance
    /// @dev Only callable by other protocol contracts
    function decrementBufferBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        bufferBalances[asset] = bufferBalances[asset] <= amount
            ? 0
            : bufferBalances[asset] - amount;
    }

    /// @notice Updates `lastPaid`
    /// @dev Only callable by other protocol contracts
    function setLastPaid(
        address asset,
        uint256 timestamp
    ) external onlyContract {
        lastPaid[asset] = timestamp;
    }

    /// @notice Increments `clpSupply`, `userClpBalances` and `depositIdsForAccount`
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset
    /// @param user User
    /// @param amount Amount
    /// @param lockupPeriodIndex Lockup period index
    /// @return depositId Deposit ID
    /// @return lockupPeriod Lockup period
    function incrementUserClpBalance(
        address asset,
        address user,
        uint256 amount,
        uint256 lockupPeriodIndex
    ) external onlyContract returns (uint256, uint256) {
        require(amount > 0, "!amount");
        require(
            lockupPeriodIndex < lockupPeriods.length,
            "!lockup-period-index"
        );
        clpSupply[asset] += amount;
        userClpBalances[asset][user] += amount;

        uint256 lockupPeriod = lockupPeriods[lockupPeriodIndex];
        uint256 currentDepositId = depositId;
        depositIdsForAccount[user][asset].push(currentDepositId);
        depositClpBalances[currentDepositId] = amount;
        if (lockupPeriod > 0) {
            depositTimestamps[currentDepositId] =
                block.timestamp +
                lockupPeriod;
        } else {
            depositTimestamps[currentDepositId] = 0;
        }

        unchecked {
            depositId++;
        }

        return (currentDepositId, lockupPeriod);
    }

    /// @notice Decrements `clpSupply` and `userClpBalances`
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset
    /// @param user User
    /// @param amount Amount
    /// @return depositIds Array of deposit IDs
    /// @return amounts Array of deposit amounts
    function decrementUserClpBalance(
        address asset,
        address user,
        uint256 amount
    ) external onlyContract returns (uint256[] memory, uint256[] memory) {
        require(amount > 0, "!amount");
        clpSupply[asset] = clpSupply[asset] <= amount
            ? 0
            : clpSupply[asset] - amount;

        userClpBalances[asset][user] = userClpBalances[asset][user] <= amount
            ? 0
            : userClpBalances[asset][user] - amount;

        uint256[] storage userDeposits = depositIdsForAccount[user][asset];
        uint256 len = userDeposits.length;
        uint256[] memory depositIds = new uint256[](len);
        uint256[] memory amounts = new uint256[](len);
        uint256 remainingAmount = amount;
        uint256 writeIndex = 0;
        uint256 upd = 0;

        for (uint256 i = 0; i < len; i++) {
            uint256 dId = userDeposits[i];
            uint256 depositBalance = depositClpBalances[dId];
            uint256 depositTimestamp = depositTimestamps[dId];

            if (depositBalance > 0) {
                bool isUnlocked = block.timestamp >= depositTimestamp;

                if (isUnlocked && remainingAmount > 0) {
                    if (depositBalance > remainingAmount) {
                        uint256 newBal = depositBalance - remainingAmount;
                        depositClpBalances[dId] = newBal;
                        remainingAmount = 0;
                        if (writeIndex != i) {
                            userDeposits[writeIndex] = dId;
                        }
                        writeIndex++;
                        depositIds[upd] = dId;
                        amounts[upd] = newBal;
                        upd++;
                    } else {
                        remainingAmount -= depositBalance;
                        depositIds[upd] = dId;
                        amounts[upd] = 0;
                        delete depositClpBalances[dId];
                        delete depositTimestamps[dId];
                        upd++;
                    }
                } else {
                    if (writeIndex != i) {
                        userDeposits[writeIndex] = dId;
                    }
                    writeIndex++;
                }
            }
        }

        while (userDeposits.length > writeIndex) {
            userDeposits.pop();
        }

        require(remainingAmount == 0, "!locked-amount");

        assembly {
            mstore(depositIds, upd)
            mstore(amounts, upd)
        }

        return (depositIds, amounts);
    }

    /// @notice Reset lockup timestamp for a deposit
    /// @dev Only callable by governance
    /// @param _depositId Deposit ID
    function resetLockupTimestamp(uint256 _depositId) external onlyGov {
        depositTimestamps[_depositId] = 0;
    }

    /// @notice Returns the sum of buffer and pool balance of `asset`
    /// @param asset Asset address
    /// @return Available balance
    function getAvailable(address asset) external view returns (uint256) {
        return balances[asset] + bufferBalances[asset];
    }

    /// @notice Returns amount of `asset` in pool
    /// @param asset Asset address
    /// @return Balance
    function getBalance(address asset) external view returns (uint256) {
        return balances[asset];
    }

    /// @notice Returns amount of `asset` in buffer
    /// @param asset Asset address
    /// @return Buffer balance
    function getBufferBalance(address asset) external view returns (uint256) {
        return bufferBalances[asset];
    }

    /// @notice Returns pool balances of `_assets`
    /// @param _assets Assets
    /// @return Balances
    function getBalances(
        address[] calldata _assets
    ) external view returns (uint256[] memory) {
        uint256 length = _assets.length;
        uint256[] memory _balances = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            _balances[i] = balances[_assets[i]];
        }

        return _balances;
    }

    /// @notice Returns buffer balances of `_assets`
    /// @param _assets Assets
    /// @return Balances
    function getBufferBalances(
        address[] calldata _assets
    ) external view returns (uint256[] memory) {
        uint256 length = _assets.length;
        uint256[] memory _balances = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            _balances[i] = bufferBalances[_assets[i]];
        }

        return _balances;
    }

    /// @notice Returns last time pool was paid
    /// @param asset Asset address
    /// @return Last paid timestamp
    function getLastPaid(address asset) external view returns (uint256) {
        return lastPaid[asset];
    }

    /// @notice Returns `asset` balance of `account`
    /// @param asset Asset address
    /// @param account User address
    /// @return Balance
    function getUserBalance(
        address asset,
        address account
    ) public view returns (uint256) {
        if (clpSupply[asset] == 0) return 0;
        return
            (userClpBalances[asset][account] * balances[asset]) /
            clpSupply[asset];
    }

    /// @notice Returns `_assets` balance of `account`
    /// @param _assets Assets
    /// @param account User address
    /// @return Balances
    function getUserBalances(
        address[] calldata _assets,
        address account
    ) external view returns (uint256[] memory) {
        uint256 length = _assets.length;
        uint256[] memory _balances = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            _balances[i] = getUserBalance(_assets[i], account);
        }

        return _balances;
    }

    /// @notice Returns `asset` balances of multiple `accounts`
    /// @param asset Asset address
    /// @param accounts User addresses
    /// @return Balances
    function getUsersBalances(
        address asset,
        address[] calldata accounts
    ) external view returns (uint256[] memory) {
        uint256[] memory _balances = new uint256[](accounts.length);
        for (uint256 i = 0; i < accounts.length; i++) {
            _balances[i] = getUserBalance(asset, accounts[i]);
        }
        return _balances;
    }

    /// @notice Returns total amount of CLP for `asset`
    /// @param asset Asset address
    /// @return CLP supply
    function getClpSupply(address asset) public view returns (uint256) {
        return clpSupply[asset];
    }

    /// @notice Returns amount of CLP of `account` for `asset`
    /// @param asset Asset address
    /// @param account User address
    /// @return CLP amount
    function getUserClpBalance(
        address asset,
        address account
    ) public view returns (uint256) {
        return userClpBalances[asset][account];
    }

    /// @notice Returns CLP balances of `accounts` for `asset`
    /// @param asset Asset address
    /// @param accounts User addresses
    /// @return clpAmounts CLP amounts
    function getUsersClpBalances(
        address asset,
        address[] calldata accounts
    ) external view returns (uint256[] memory clpAmounts) {
        uint256 len = accounts.length;
        clpAmounts = new uint256[](len);
        for (uint256 i = 0; i < len; i++) {
            clpAmounts[i] = userClpBalances[asset][accounts[i]];
        }

        return clpAmounts;
    }

    /// @notice Returns deposit IDs for a user and asset
    /// @param user User address
    /// @param asset Asset address
    /// @return Deposit IDs
    function getDepositIdsForAccount(
        address user,
        address asset
    ) external view returns (uint256[] memory) {
        return depositIdsForAccount[user][asset];
    }

    /// @notice Returns deposit info for a specific deposit ID
    /// @param dId Deposit ID
    /// @return balance Deposit balance
    /// @return timestamp Deposit timestamp
    function getDepositInfo(
        uint256 dId
    ) external view returns (uint256 balance, uint256 timestamp) {
        return (depositClpBalances[dId], depositTimestamps[dId]);
    }

    /// @notice Returns the amount of unlocked CLP for a user
    /// @param asset Asset address
    /// @param account User address
    /// @return Unlocked CLP amount
    function getUnlockedClpBalance(
        address asset,
        address account
    ) external view returns (uint256) {
        uint256[] memory userDeposits = depositIdsForAccount[account][asset];
        uint256 unlockedAmount = 0;

        for (uint256 i = 0; i < userDeposits.length; i++) {
            uint256 dId = userDeposits[i];
            uint256 depositBalance = depositClpBalances[dId];
            uint256 unlockTimestamp = depositTimestamps[dId];

            if (depositBalance > 0 && block.timestamp >= unlockTimestamp) {
                unlockedAmount += depositBalance;
            }
        }

        return unlockedAmount;
    }

    /// @notice Returns the amount of locked CLP for a user
    /// @param asset Asset address
    /// @param account User address
    /// @return Locked CLP amount
    function getLockedClpBalance(
        address asset,
        address account
    ) external view returns (uint256) {
        uint256[] memory userDeposits = depositIdsForAccount[account][asset];
        uint256 lockedAmount = 0;

        for (uint256 i = 0; i < userDeposits.length; i++) {
            uint256 dId = userDeposits[i];
            uint256 depositBalance = depositClpBalances[dId];
            uint256 unlockTimestamp = depositTimestamps[dId];

            if (depositBalance > 0 && block.timestamp < unlockTimestamp) {
                lockedAmount += depositBalance;
            }
        }

        return lockedAmount;
    }

    // @notice Returns lockup period for a given index
    /// @param index Lockup period index
    /// @return Lockup period in seconds
    function getLockupPeriod(uint256 index) external view returns (uint256) {
        return lockupPeriods[index];
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./EnumerableSet.sol";

import "./Roles.sol";

/// @title PositionStore
/// @notice Persistent storage for Positions.sol
contract PositionStore is Roles {
    // Libraries
    using EnumerableSet for EnumerableSet.Bytes32Set;

    // Position struct
    struct Position {
        address user; // User that submitted the position
        address asset; // Asset address, e.g. address(0) for ETH
        string market; // Market this position was submitted on
        bool isLong; // Wether the position is long or short
        uint256 size; // The position's size (margin * leverage)
        uint256 margin; // Collateral tied to this position. In wei
        int256 fundingTracker; // Market funding rate tracker
        uint256 price; // The position's average execution price
        uint256 timestamp; // Time at which the position was created
    }

    // Constants
    uint256 public constant BPS_DIVIDER = 10000;
    uint256 public constant MAX_KEEPER_FEE_SHARE = 2000; // 20%

    // State variables
    uint256 public removeMarginBuffer;
    uint256 public keeperFeeShare;

    // Mappings
    mapping(address => mapping(string => uint256)) private OI; // open interest. market => asset => amount
    mapping(address => mapping(string => uint256)) private OILong; // open interest. market => asset => amount
    mapping(address => mapping(string => uint256)) private OIShort; // open interest. market => asset => amount]

    mapping(bytes32 => Position) private positions; // key = asset,user,market
    EnumerableSet.Bytes32Set private positionKeys; // [position keys..]
    mapping(address => EnumerableSet.Bytes32Set) private positionKeysForUser; // user => [position keys..]

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        removeMarginBuffer = 1000;
        keeperFeeShare = 500;
    }

    /// @notice Updates `removeMarginBuffer`
    /// @dev Only callable by governance
    /// @param bps new `removeMarginBuffer` in bps
    function setRemoveMarginBuffer(uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        removeMarginBuffer = bps;
    }

    /// @notice Sets keeper fee share
    /// @dev Only callable by governance
    /// @param bps new `keeperFeeShare` in bps
    function setKeeperFeeShare(uint256 bps) external onlyGov {
        require(bps <= MAX_KEEPER_FEE_SHARE, "!keeper-fee-share");
        keeperFeeShare = bps;
    }

    /// @notice Adds new position or updates exisiting one
    /// @dev Only callable by other protocol contracts
    /// @param position Position to add/update
    function addOrUpdate(Position memory position) external onlyContract {
        bytes32 key = _getPositionKey(
            position.user,
            position.asset,
            position.market
        );
        positions[key] = position;
        positionKeysForUser[position.user].add(key);
        positionKeys.add(key);
    }

    /// @notice Removes position
    /// @dev Only callable by other protocol contracts
    function remove(
        address user,
        address asset,
        string calldata market
    ) external onlyContract {
        bytes32 key = _getPositionKey(user, asset, market);
        positionKeysForUser[user].remove(key);
        positionKeys.remove(key);
        delete positions[key];
    }

    /// @notice Increments open interest
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked by Positions.increasePosition
    function incrementOI(
        address asset,
        string calldata market,
        uint256 amount,
        bool isLong
    ) external onlyContract {
        OI[asset][market] += amount;
        if (isLong) {
            OILong[asset][market] += amount;
        } else {
            OIShort[asset][market] += amount;
        }
    }

    /// @notice Decrements open interest
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked whenever a position is closed or decreased
    function decrementOI(
        address asset,
        string calldata market,
        uint256 amount,
        bool isLong
    ) external onlyContract {
        OI[asset][market] = OI[asset][market] <= amount
            ? 0
            : OI[asset][market] - amount;
        if (isLong) {
            OILong[asset][market] = OILong[asset][market] <= amount
                ? 0
                : OILong[asset][market] - amount;
        } else {
            OIShort[asset][market] = OIShort[asset][market] <= amount
                ? 0
                : OIShort[asset][market] - amount;
        }
    }

    /// @notice Returns open interest of `asset` and `market`
    function getOI(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return OILong[asset][market] + OIShort[asset][market];
    }

    /// @notice Sets open interest of long positions
    function setOILong(
        address asset,
        string calldata market,
        uint256 amount
    ) external onlyGov {
        OILong[asset][market] = amount;
    }

    /// @notice Sets open interest of short positions
    function setOIShort(
        address asset,
        string calldata market,
        uint256 amount
    ) external onlyGov {
        OIShort[asset][market] = amount;
    }

    /// @notice Returns open interest of long positions
    function getOILong(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return OILong[asset][market];
    }

    /// @notice Returns open interest of short positions
    function getOIShort(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return OIShort[asset][market];
    }

    /// @notice Returns position of `user`
    /// @param asset Base asset of position
    /// @param market Market this position was submitted on
    function getPosition(
        address user,
        address asset,
        string memory market
    ) public view returns (Position memory) {
        bytes32 key = _getPositionKey(user, asset, market);
        return positions[key];
    }

    /// @notice Returns positions of `users`
    /// @param assets Base assets of positions
    /// @param markets Markets of positions
    function getPositions(
        address[] calldata users,
        address[] calldata assets,
        string[] calldata markets
    ) external view returns (Position[] memory) {
        uint256 length = users.length;
        Position[] memory _positions = new Position[](length);

        for (uint256 i = 0; i < length; i++) {
            _positions[i] = getPosition(users[i], assets[i], markets[i]);
        }

        return _positions;
    }

    /// @notice Returns positions
    /// @param keys Position keys
    function getPositions(
        bytes32[] calldata keys
    ) external view returns (Position[] memory) {
        uint256 length = keys.length;
        Position[] memory _positions = new Position[](length);

        for (uint256 i = 0; i < length; i++) {
            _positions[i] = positions[keys[i]];
        }

        return _positions;
    }

    /// @notice Returns number of positions
    function getPositionCount() external view returns (uint256) {
        return positionKeys.length();
    }

    /// @notice Returns `length` amount of positions starting from `offset`
    function getPositions(
        uint256 length,
        uint256 offset
    ) external view returns (Position[] memory) {
        uint256 _length = positionKeys.length();
        require(offset <= _length, "Offset out of bounds");

        uint256 availableLength = _length - offset;
        uint256 resultLength = length > availableLength
            ? availableLength
            : length;
        Position[] memory _positions = new Position[](resultLength);

        for (uint256 i = 0; i < resultLength; i++) {
            _positions[i] = positions[positionKeys.at(i + offset)];
        }

        return _positions;
    }

    /// @notice Returns all positions of `user`
    function getUserPositions(
        address user
    ) external view returns (Position[] memory) {
        uint256 length = positionKeysForUser[user].length();
        Position[] memory _positions = new Position[](length);

        for (uint256 i = 0; i < length; i++) {
            _positions[i] = positions[positionKeysForUser[user].at(i)];
        }

        return _positions;
    }

    /// @dev Returns position key by hashing (user, asset, market)
    function _getPositionKey(
        address user,
        address asset,
        string memory market
    ) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(user, asset, market));
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import {DataStore} from "./DataStore.sol";
import {PoolStore} from "./PoolStore.sol";
import {PositionStore} from "./PositionStore.sol";

import "./Roles.sol";

/// @title RiskStore
/// @notice Implementation of risk mitigation measures such as maximum open interest and maximum pool drawdown
contract RiskStore is Roles {
    // Constants
    uint256 public constant BPS_DIVIDER = 10000;

    mapping(string => mapping(address => uint256)) private maxOI; // market => asset => amount

    // Pool Risk Measures
    uint256 public poolHourlyDecay; // bps = 4.16% hourly, disappears after 24 hours
    mapping(address => int256) private poolProfitTracker; // asset => amount (amortized)
    mapping(address => uint256) private poolProfitLimit; // asset => bps
    mapping(address => uint256) private poolLastChecked; // asset => timestamp

    // Contracts
    DataStore public DS;

    /// @dev Initialize DataStore address
    function initialize(address rs, address ds) external initializer {
        DS = DataStore(ds);
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        poolHourlyDecay = 416;
    }

    // V2 Delta Long-Short
    mapping(string => mapping(address => uint256)) private maxDelta; // market => asset => amount

    // V3 Max Position Size
    uint256 private maxPositionSizeFactor; // 10000 = 100%

    // V4 ADL
    mapping(address => uint256) private adlThreshold; // asset => threshold (bps)

    /// @notice Set maximum delta between longs and shorts
    /// @dev Only callable by governance
    /// @param market Market to set, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param amount Max delta to set
    function setMaxDelta(
        string calldata market,
        address asset,
        uint256 amount
    ) external onlyGov {
        require(amount > 0, "!amount");
        maxDelta[market][asset] = amount;
    }

    /// @notice Set maximum open interest
    /// @notice Once current open interest exceeds this value, orders are no longer accepted
    /// @dev Only callable by governance
    /// @param market Market to set, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param amount Max open interest to set
    function setMaxOI(
        string calldata market,
        address asset,
        uint256 amount
    ) external onlyGov {
        require(amount > 0, "!amount");
        maxOI[market][asset] = amount;
    }

    /// @notice Set maximum position size factor
    /// @dev Only callable by governance
    /// @param factor Max position size factor
    function setMaxPositionSizeFactor(uint256 factor) external onlyGov {
        maxPositionSizeFactor = factor;
    }

    /// @notice Set hourly pool decay
    /// @dev Only callable by governance
    /// @param bps Hourly pool decay in bps
    function setPoolHourlyDecay(uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        poolHourlyDecay = bps;
    }

    /// @notice Set pool profit limit of `asset`
    /// @dev Only callable by governance
    /// @param asset Address of asset, e.g. address(0) for ETH
    /// @param bps Pool profit limit in bps
    function setPoolProfitLimit(address asset, uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        poolProfitLimit[asset] = bps;
    }

    /// @notice Set ADL threshold of `asset`
    /// @dev Only callable by governance
    /// @param asset Address of asset, e.g. address(0) for ETH
    /// @param bps ADL threshold in bps
    function setADLThreshold(address asset, uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        adlThreshold[asset] = bps;
    }

    /// @notice Measures the net loss of a pool over time
    /// @notice Reverts if time-weighted drawdown is higher than the allowed profit limit
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked by Positions.decreasePosition
    function checkPoolDrawdown(
        address asset,
        int256 pnl
    ) external onlyContract {
        // Get available amount of `asset` in the pool (pool balance + buffer balance)
        uint256 poolAvailable = PoolStore(DS.getAddress("PoolStore"))
            .getAvailable(asset);

        // Get profit tracker, pnl > 0 means trader win
        int256 profitTracker = getPoolProfitTracker(asset) + pnl;
        // get profit limit of pool
        uint256 profitLimit = poolProfitLimit[asset];

        // update storage vars
        poolProfitTracker[asset] = profitTracker;
        poolLastChecked[asset] = block.timestamp;

        // return if profit limit or profit tracker is zero / less than zero
        if (profitLimit == 0 || profitTracker <= 0) return;

        // revert if profitTracker > profitLimit * available funds
        require(
            uint256(profitTracker) <
                (profitLimit * poolAvailable) / BPS_DIVIDER,
            "!pool-risk"
        );
    }

    /// @notice Checks if maximum delta and maximum open interest are reached
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param size Size of the position
    /// @param isLong Whether position is long (true) or short (false)
    function checkMaxDelta(
        address asset,
        string calldata market,
        uint256 size,
        bool isLong
    ) external view {
        // Get current OI values
        uint256 oiLong = PositionStore(DS.getAddress("PositionStore"))
            .getOILong(asset, market);
        uint256 oiShort = PositionStore(DS.getAddress("PositionStore"))
            .getOIShort(asset, market);
        uint256 _maxDelta = maxDelta[market][asset];

        if (_maxDelta > 0) {
            if (isLong) {
                // available long = maxDelta - oiLong + oiShort
                int256 availableLong = int256(_maxDelta) -
                    int256(oiLong) +
                    int256(oiShort);
                if (availableLong < 0) {
                    availableLong = 0;
                }
                require(size <= uint256(availableLong), "!max-delta");
            } else {
                // available short = maxDelta + oiLong - oiShort
                int256 availableShort = int256(_maxDelta) +
                    int256(oiLong) -
                    int256(oiShort);
                if (availableShort < 0) {
                    availableShort = 0;
                }
                require(size <= uint256(availableShort), "!max-delta");
            }
        }

        // Check max OI
        // uint256 openInterest = PositionStore(DS.getAddress('PositionStore')).getOI(asset, market);
        uint256 openInterest = oiLong + oiShort;
        uint256 _maxOI = maxOI[market][asset];
        if (_maxOI > 0 && openInterest + size > _maxOI) revert("!max-oi");
    }

    /// @notice Checks if maximum open interest is reached
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function checkMaxOI(
        address asset,
        string calldata market,
        uint256 size
    ) external view {
        uint256 openInterest = PositionStore(DS.getAddress("PositionStore"))
            .getOI(asset, market);
        uint256 _maxOI = maxOI[market][asset];
        if (_maxOI > 0 && openInterest + size > _maxOI) revert("!max-oi");
    }

    /// @notice Get maximum position size of `market`
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function getMaxPositionSize(
        string calldata market,
        address asset
    ) external view returns (uint256) {
        return (maxOI[market][asset] * maxPositionSizeFactor) / 10000;
    }

    /// @notice Checks if maximum position size is reached
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param sizeToAdd Size of the position to add
    /// @param currentSize Current size of the position
    /// @param isLongOrder Whether the order is long or short
    /// @param isLongPosition Whether the position is long or short
    function checkMaxPositionSize(
        address asset,
        string calldata market,
        uint256 sizeToAdd,
        uint256 currentSize,
        bool isLongOrder,
        bool isLongPosition
    ) external view {
        if (maxPositionSizeFactor == 0) return;
        uint256 maxPositionSize = (maxOI[market][asset] *
            maxPositionSizeFactor) / 10000;
        uint256 newSize;
        if (currentSize == 0) {
            newSize = sizeToAdd;
        } else if (isLongOrder == isLongPosition) {
            newSize = currentSize + sizeToAdd;
        } else {
            newSize = currentSize > sizeToAdd
                ? currentSize - sizeToAdd
                : sizeToAdd - currentSize;
        }
        require(newSize <= maxPositionSize, "!max-position-size");
    }

    /// @notice Get maximum delta of `market`
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function getMaxDelta(
        string calldata market,
        address asset
    ) external view returns (uint256) {
        return maxDelta[market][asset];
    }

    /// @notice Get maximum open interest of `market`
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function getMaxOI(
        string calldata market,
        address asset
    ) external view returns (uint256) {
        return maxOI[market][asset];
    }

    /// @notice Returns pool profit tracker of `asset`
    /// @dev Amortized every hour by 4.16% unless otherwise set
    function getPoolProfitTracker(address asset) public view returns (int256) {
        int256 profitTracker = poolProfitTracker[asset];
        uint256 lastCheckedHourId = poolLastChecked[asset] / (1 hours);
        uint256 currentHourId = block.timestamp / (1 hours);

        if (currentHourId > lastCheckedHourId) {
            // hours passed since last check
            uint256 hoursPassed = currentHourId - lastCheckedHourId;
            if (hoursPassed >= BPS_DIVIDER / poolHourlyDecay) {
                profitTracker = 0;
            } else {
                // reduce profit tracker by `poolHourlyDecay` for every hour that passed since last check
                for (uint256 i = 0; i < hoursPassed; i++) {
                    profitTracker *=
                        (int256(BPS_DIVIDER) - int256(poolHourlyDecay)) /
                        int256(BPS_DIVIDER);
                }
            }
        }

        return profitTracker;
    }

    /// @notice Returns pool profit limit of `asset`
    function getPoolProfitLimit(address asset) external view returns (uint256) {
        return poolProfitLimit[asset];
    }

    /// @notice Get ADL threshold of `asset`
    /// @param asset Address of asset, e.g. address(0) for ETH
    function getADLThreshold(address asset) external view returns (uint256) {
        return adlThreshold[asset];
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import {DataStore} from "./DataStore.sol";
import {FundingStore} from "./FundingStore.sol";
import {MarketStore} from "./MarketStore.sol";
import {PositionStore} from "./PositionStore.sol";

import "./Roles.sol";

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

/**
 * @title  Funding
 * @notice Funding rates are calculated hourly for each market and collateral
 *         asset based on the real-time open interest imbalance
 */
contract Funding is Roles {
    // Events
    event FundingUpdated(
        address indexed asset,
        string market,
        uint256 OILong,
        uint256 OIShort,
        int256 accruedFundingV1,
        int256 accruedFundingV2,
        int256 onePeriodFundingIncrement,
        int256 fundingTracker
    );

    // Constants
    uint256 public constant UNIT = 10 ** 18;

    // Contracts
    DataStore public DS;
    FundingStore public fundingStore;
    MarketStore public marketStore;
    PositionStore public positionStore;
    RiskStore public riskStore;

    /// @dev Initializes DataStore address
    function initialize(address rs, address ds) external initializer {
        DS = DataStore(ds);
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @notice Initializes protocol contracts
    /// @dev Only callable by governance
    function link() external onlyGov {
        fundingStore = FundingStore(DS.getAddress("FundingStore"));
        marketStore = MarketStore(DS.getAddress("MarketStore"));
        positionStore = PositionStore(DS.getAddress("PositionStore"));
        riskStore = RiskStore(DS.getAddress("RiskStore"));
    }

    /// @notice Updates funding tracker of `market` and `asset`
    /// @dev Only callable by other protocol contracts
    function updateFundingTracker(
        address asset,
        string calldata market
    ) external onlyContract {
        uint256 lastUpdated = fundingStore.getLastUpdated(asset, market);
        uint256 _now = block.timestamp;

        // condition is true only on the very first execution
        if (lastUpdated == 0) {
            fundingStore.setLastUpdated(asset, market, _now);
            return;
        }

        // returns if block.timestamp - lastUpdated is less than funding interval
        if (lastUpdated + fundingStore.fundingInterval() > _now) return;

        // positive funding increment indicates that shorts pay longs, negative that longs pay shorts
        (
            int256 fundingIncrement,
            int256 emaFundingRate,
            int256 onePeriodFR,
            int256 capedEmaFundingRate
        ) = getAccruedFundingV2(asset, market, 0); // in UNIT * bps

        // return if funding increment is zero
        if (fundingIncrement == 0) return;
        fundingStore.setLastEmaFundingRate(asset, market, emaFundingRate);
        fundingStore.setLastCappedEmaFundingRate(
            asset,
            market,
            capedEmaFundingRate
        );

        fundingStore.updateFundingTracker(asset, market, fundingIncrement);
        fundingStore.setLastUpdated(asset, market, _now);

        emit FundingUpdated(
            asset,
            market,
            positionStore.getOILong(asset, market),
            positionStore.getOIShort(asset, market),
            getAccruedFunding(asset, market, 1),
            fundingIncrement,
            onePeriodFR,
            fundingStore.getFundingTracker(asset, market)
        );
    }

    /// @notice Returns accrued funding of `market` and `asset`
    function getAccruedFunding(
        address asset,
        string memory market,
        uint256 intervals
    ) public view returns (int256) {
        if (intervals == 0) {
            intervals =
                (block.timestamp - fundingStore.getLastUpdated(asset, market)) /
                fundingStore.fundingInterval();
        }

        if (intervals == 0) return 0;

        uint256 OILong = positionStore.getOILong(asset, market);
        uint256 OIShort = positionStore.getOIShort(asset, market);

        if (OIShort == 0 && OILong == 0) return 0;

        uint256 OIDiff = OIShort > OILong ? OIShort - OILong : OILong - OIShort;

        MarketStore.Market memory marketInfo = marketStore.get(market);
        uint256 yearlyFundingFactor = marketInfo.fundingFactor;

        uint256 accruedFunding = (UNIT *
            yearlyFundingFactor *
            OIDiff *
            intervals) / (24 * 365 * (OILong + OIShort)); // in UNIT * bps

        if (OILong > OIShort) {
            // Longs pay shorts. Increase funding tracker.
            return int256(accruedFunding);
        } else {
            // Shorts pay longs. Decrease funding tracker.
            return -1 * int256(accruedFunding);
        }
    }

    /// @notice Returns accrued funding of `market` and `asset`
    function getAccruedFundingV2(
        address asset,
        string memory market,
        uint256 intervals
    ) public view returns (int256, int256, int256, int256) {
        if (intervals == 0) {
            intervals =
                (block.timestamp - fundingStore.getLastUpdated(asset, market)) /
                fundingStore.fundingInterval();
        }

        if (intervals == 0) return (0, 0, 0, 0);

        uint256 OILong = positionStore.getOILong(asset, market);
        uint256 OIShort = positionStore.getOIShort(asset, market);

        if (OIShort == 0 && OILong == 0) return (0, 0, 0, 0);

        MarketStore.Market memory marketInfo = marketStore.get(market);

        uint256 yearlyFundingFactor = marketInfo.fundingFactor;
        uint256 maxDelta = riskStore.getMaxDelta(market, asset);
        int256 lastEmaFundingRate = fundingStore.getLastEmaFundingRate(
            asset,
            market
        );
        uint256 minFactor = marketInfo.minFactor;
        uint256 sampleSize = marketInfo.sampleSize;

        uint256 absDelta = OIShort > OILong
            ? OIShort - OILong
            : OILong - OIShort;

        if (
            minFactor == 0 || sampleSize == 0 || absDelta == 0 || maxDelta == 0
        ) {
            return (0, 0, 0, 0);
        }

        // Δ/MaxDelta = (OILong - OIShort) / MaxDelta
        int256 deltaRatio = ((int256(OILong) - int256(OIShort)) *
            int256(UNIT)) / int256(maxDelta);

        // min(UNIT, Δ/MaxDelta)
        if (deltaRatio > int256(UNIT)) {
            deltaRatio = int256(UNIT);
        }

        // max(-UNIT, min(UNIT, Δ/MaxDelta))
        if (deltaRatio < -int256(UNIT)) {
            deltaRatio = -int256(UNIT);
        }

        // FR(Δ) = FundingFactor * max(-UNIT, min(UNIT, Δ/MaxDelta))
        int256 FR = int256(yearlyFundingFactor) * deltaRatio;

        // α = 2 * UNIT / (N + 1)
        int256 alpha = (2 * int256(UNIT)) / (int256(sampleSize) + 1);

        // FR(EMA_t) = (α * FR(t) + (1 - α) * FR(EMA_t-1)) / UNIT -> FR(EMA_t): bps × UNIT
        int256 emaFundingRate = (alpha *
            FR +
            (int256(UNIT) - alpha) *
            lastEmaFundingRate) / int256(UNIT);

        int256 incr = emaFundingRate;

        // Cap the funding rate
        if (incr > 0 && incr < int256(minFactor) * int256(UNIT)) {
            incr = int256(minFactor) * int256(UNIT);
        } else if (incr < 0 && incr > -int256(minFactor) * int256(UNIT)) {
            incr = -int256(minFactor) * int256(UNIT);
        }

        uint256 accruedFunding = (uint256(incr > 0 ? incr : -incr) *
            intervals) / (24 * 365);

        uint256 onePeriodFundingIncrement = (uint256(incr > 0 ? incr : -incr)) /
            (24 * 365);

        if (OILong > OIShort) {
            // Longs pay shorts. Increase funding tracker.
            return (
                int256(accruedFunding),
                emaFundingRate,
                int256(onePeriodFundingIncrement),
                incr
            );
        } else {
            // Shorts pay longs. Decrease funding tracker.
            return (
                -1 * int256(accruedFunding),
                emaFundingRate,
                -1 * int256(onePeriodFundingIncrement),
                incr
            );
        }
    }

    function getRealTimeFundingTracker(
        address asset,
        string calldata market
    ) public view returns (int256) {
        int256 currentFundingTracker = fundingStore.getFundingTracker(
            asset,
            market
        );
        uint256 lastUpdated = fundingStore.getLastUpdated(asset, market);
        int256 totalPeriodFundingIncrement = fundingStore
            .getLastCappedEmaFundingRate(asset, market) / int256(24 * 365);
        uint256 fundingInterval = fundingStore.fundingInterval();
        uint256 ratio = (UNIT * (block.timestamp - lastUpdated)) /
            (fundingInterval);
        if (ratio == 0) return currentFundingTracker;
        int256 realTimeFundingTracker = currentFundingTracker +
            (totalPeriodFundingIncrement * int256(ratio)) /
            int256(UNIT);
        return realTimeFundingTracker;
    }

    function getRealTimeFundingTrackers(
        address asset,
        string[] calldata markets
    ) external view returns (int256[] memory) {
        uint256 length = markets.length;
        int256[] memory realTimeFundingTrackers = new int256[](length);
        for (uint256 i = 0; i < length; i++) {
            realTimeFundingTrackers[i] = getRealTimeFundingTracker(
                asset,
                markets[i]
            );
        }
        return realTimeFundingTrackers;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "@openzeppelin/contracts/utils/Address.sol";

import {AssetStore} from "./AssetStore.sol";
import {DataStore} from "./DataStore.sol";
import {FundStore} from "./FundStore.sol";
import {OrderStore} from "./OrderStore.sol";
import {MarketStore} from "./MarketStore.sol";
import {RiskStore} from "./RiskStore.sol";

import "./Roles.sol";

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

/**
 * @title  Orders
 * @notice Implementation of order related logic, i.e. submitting orders / cancelling them
 */
contract Orders is Roles {
    // Libraries
    using Address for address payable;

    // Constants
    uint256 public constant UNIT = 10 ** 18;
    uint256 public constant BPS_DIVIDER = 10000;

    // Events

    // Order of function / event params: id, user, asset, market
    event OrderCreated(
        uint256 indexed orderId,
        address indexed user,
        address indexed asset,
        string market,
        uint256 margin,
        uint256 size,
        uint256 price,
        uint256 fee,
        bool isLong,
        uint8 orderType,
        bool isReduceOnly,
        uint256 expiry,
        uint256 cancelOrderId
    );

    event OrderCancelled(
        uint256 indexed orderId,
        address indexed user,
        string reason
    );

    // Contracts
    DataStore public DS;

    AssetStore public assetStore;
    FundStore public fundStore;
    MarketStore public marketStore;
    OrderStore public orderStore;
    RiskStore public riskStore;
    ReferralStore public referralStore;

    /// @dev Initializes DataStore address
    function initialize(address rs, address ds) external initializer {
        DS = DataStore(ds);
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @dev Reverts if new orders are paused
    modifier ifNotPaused() {
        require(!orderStore.areNewOrdersPaused(), "!paused");
        _;
    }

    /// @notice Initializes protocol contracts
    /// @dev Only callable by governance
    function link() external onlyGov {
        assetStore = AssetStore(DS.getAddress("AssetStore"));
        fundStore = FundStore(payable(DS.getAddress("FundStore")));
        marketStore = MarketStore(DS.getAddress("MarketStore"));
        orderStore = OrderStore(DS.getAddress("OrderStore"));
        riskStore = RiskStore(DS.getAddress("RiskStore"));
        referralStore = ReferralStore(DS.getAddress("ReferralStore"));
    }

    function submitSimpleOrders(
        OrderStore.Order[] calldata params,
        uint256[] calldata orderIdsToCancel
    ) external payable ifNotPaused {
        for (uint256 i = 0; i < orderIdsToCancel.length; i++) {
            OrderStore.Order memory orderToCancel = orderStore.get(
                orderIdsToCancel[i]
            );
            if (orderToCancel.size > 0 && orderToCancel.user == msg.sender) {
                _cancelOrder(orderIdsToCancel[i], "by-user");
            }
        }

        uint256 totalValueConsumed;
        for (uint256 i = 0; i < params.length; i++) {
            uint256 valueConsumed;
            (, valueConsumed) = _submitOrder(params[i]);
            totalValueConsumed += valueConsumed;
        }

        // Refund msg.value excess, if any
        if (msg.value > totalValueConsumed) {
            payable(msg.sender).sendValue(msg.value - totalValueConsumed);
        }
    }

    /// @notice Submits a new order
    /// @param params Order to submit
    /// @param tpPrice 18 decimal take profit price
    /// @param slPrice 18 decimal stop loss price
    function submitOrder(
        OrderStore.Order memory params,
        uint256 tpPrice,
        uint256 slPrice
    ) external payable ifNotPaused {
        // order cant be reduce-only if take profit or stop loss order is submitted alongside main order
        if (tpPrice > 0 || slPrice > 0) {
            params.isReduceOnly = false;
        }

        // Submit order
        uint256 valueConsumed;
        (, valueConsumed) = _submitOrder(params);

        // tp/sl price checks
        if (tpPrice > 0 || slPrice > 0) {
            if (params.price > 0) {
                if (tpPrice > 0) {
                    require(
                        (params.isLong && tpPrice > params.price) ||
                            (!params.isLong && tpPrice < params.price),
                        "!tp-invalid"
                    );
                }
                if (slPrice > 0) {
                    require(
                        (params.isLong && slPrice < params.price) ||
                            (!params.isLong && slPrice > params.price),
                        "!sl-invalid"
                    );
                }
            }

            if (tpPrice > 0 && slPrice > 0) {
                require(
                    (params.isLong && tpPrice > slPrice) ||
                        (!params.isLong && tpPrice < slPrice),
                    "!tpsl-invalid"
                );
            }

            // tp and sl order ids
            uint256 tpOrderId;
            uint256 slOrderId;

            // long -> short, short -> long for take profit / stop loss order
            params.isLong = !params.isLong;

            // reset order expiry for TP/SL orders
            if (params.expiry > 0) params.expiry = 0;

            // submit take profit order
            if (tpPrice > 0) {
                params.price = tpPrice;
                params.orderType = 1;
                params.isReduceOnly = true;

                // Order is reduce-only so valueConsumed is always zero
                (tpOrderId, ) = _submitOrder(params);
            }

            // submit stop loss order
            if (slPrice > 0) {
                params.price = slPrice;
                params.orderType = 2;
                params.isReduceOnly = true;

                // Order is reduce-only so valueConsumed is always zero
                (slOrderId, ) = _submitOrder(params);
            }

            // Update orders to cancel each other
            if (tpOrderId > 0 && slOrderId > 0) {
                orderStore.updateCancelOrderId(tpOrderId, slOrderId);
                orderStore.updateCancelOrderId(slOrderId, tpOrderId);
            }
        }

        // Refund msg.value excess, if any
        if (msg.value > valueConsumed) {
            payable(msg.sender).sendValue(msg.value - valueConsumed);
        }
    }

    /// @notice Submits a new order
    /// @dev Internal function invoked by {submitOrder}
    function _submitOrder(
        OrderStore.Order memory params
    ) internal returns (uint256, uint256) {
        // Set user and timestamp
        params.user = msg.sender;
        params.timestamp = block.timestamp;

        // Validations
        require(
            params.orderType == 0 ||
                params.orderType == 1 ||
                params.orderType == 2,
            "!order-type"
        );

        // execution price of trigger order cant be zero
        if (params.orderType != 0) {
            require(params.price > 0, "!price");
        }

        // check if base asset is supported and order size is above min size
        AssetStore.Asset memory asset = assetStore.get(params.asset);
        require(asset.minSize > 0, "!asset-exists");
        if (!params.isReduceOnly) {
            require(params.size >= asset.minSize, "!min-size");
        }
        // check if market exists
        MarketStore.Market memory market = marketStore.get(params.market);
        require(market.maxLeverage > 0, "!market-exists");

        // Order expiry validations
        if (params.expiry > 0) {
            // expiry value cant be in the past
            require(params.expiry >= block.timestamp, "!expiry-value");

            // params.expiry cant be after default expiry of market and trigger orders
            uint256 ttl = params.expiry - block.timestamp;
            if (params.orderType == 0)
                require(ttl <= orderStore.maxMarketOrderTTL(), "!max-expiry");
            else require(ttl <= orderStore.maxTriggerOrderTTL(), "!max-expiry");
        }

        // cant cancel an order of another user
        if (params.cancelOrderId > 0) {
            require(
                orderStore.isUserOrder(params.cancelOrderId, params.user),
                "!user-oco"
            );
        }

        params.fee = (params.size * market.fee) / BPS_DIVIDER;
        uint256 refereeDiscount = (params.fee *
            referralStore.getReferralFeeShare(params.user)) / BPS_DIVIDER;
        params.fee = params.fee - refereeDiscount;
        uint256 valueConsumed;

        if (params.isReduceOnly) {
            params.margin = 0;
            // Existing position is checked on execution so TP/SL can be submitted as reduce-only alongside a non-executed order
            // In this case, valueConsumed is zero as margin is zero and fee is taken from the order's margin when position is executed
        } else {
            require(!market.isReduceOnly, "!market-reduce-only");
            require(params.margin > 0, "!margin");

            uint256 leverage = (UNIT * params.size) / params.margin;
            require(leverage >= UNIT, "!min-leverage");
            require(leverage <= market.maxLeverage * UNIT, "!max-leverage");

            // Check against max OI if it's not reduce-only. this is not completely fail safe as user can place many
            // consecutive market orders of smaller size and get past the max OI limit here, because OI is not updated until
            // keeper picks up the order. That is why maxOI is checked on processing as well, which is fail safe.
            // This check is more of preemptive for user to not submit an order
            riskStore.checkMaxDelta(
                params.asset,
                params.market,
                params.size,
                params.isLong
            );

            // Transfer fee and margin to store
            valueConsumed = params.margin + params.fee;

            if (params.asset == address(0)) {
                fundStore.transferIn{value: valueConsumed}(
                    params.asset,
                    params.user,
                    valueConsumed
                );
            } else {
                fundStore.transferIn(params.asset, params.user, valueConsumed);
                valueConsumed = 0;
            }
        }

        // Add order to store and emit event
        params.orderId = orderStore.add(params);

        emit OrderCreated(
            params.orderId,
            params.user,
            params.asset,
            params.market,
            params.margin,
            params.size,
            params.price,
            params.fee,
            params.isLong,
            params.orderType,
            params.isReduceOnly,
            params.expiry,
            params.cancelOrderId
        );

        return (params.orderId, valueConsumed);
    }

    /// @notice Cancels order
    /// @param orderId Order to cancel
    function cancelOrder(uint256 orderId) external ifNotPaused {
        OrderStore.Order memory order = orderStore.get(orderId);
        require(order.size > 0, "!order");
        require(order.user == msg.sender, "!user");
        _cancelOrder(orderId, "by-user");
    }

    /// @notice Cancel several orders
    /// @param orderIds Array of orderIds to cancel
    function cancelOrders(uint256[] calldata orderIds) external ifNotPaused {
        for (uint256 i = 0; i < orderIds.length; i++) {
            OrderStore.Order memory order = orderStore.get(orderIds[i]);
            if (order.size > 0 && order.user == msg.sender) {
                _cancelOrder(orderIds[i], "by-user");
            }
        }
    }

    /// @notice Cancels order
    /// @dev Only callable by other protocol contracts
    /// @param orderId Order to cancel
    /// @param reason Cancellation reason
    function cancelOrder(
        uint256 orderId,
        string calldata reason
    ) external onlyContract {
        _cancelOrder(orderId, reason);
    }

    /// @notice Cancel several orders
    /// @dev Only callable by other protocol contracts
    /// @param orderIds Order ids to cancel
    /// @param reasons Cancellation reasons
    function cancelOrders(
        uint256[] calldata orderIds,
        string[] calldata reasons
    ) external onlyContract {
        for (uint256 i = 0; i < orderIds.length; i++) {
            _cancelOrder(orderIds[i], reasons[i]);
        }
    }

    /// @notice Cancels order
    /// @dev Internal function without access restriction
    /// @param orderId Order to cancel
    /// @param reason Cancellation reason
    function _cancelOrder(uint256 orderId, string memory reason) internal {
        OrderStore.Order memory order = orderStore.get(orderId);
        if (order.size == 0) return;

        orderStore.remove(orderId);

        if (!order.isReduceOnly) {
            fundStore.transferOut(
                order.asset,
                order.user,
                order.margin + order.fee
            );
        }

        emit OrderCancelled(orderId, order.user, reason);
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import {AssetStore} from "./AssetStore.sol";
import {DataStore} from "./DataStore.sol";
import {FundStore} from "./FundStore.sol";
import {PoolStore} from "./PoolStore.sol";

import "./Roles.sol";

/**
 * @title  Pool
 * @notice Users can deposit supported assets to back trader profits and receive
 *         a share of trader losses. Each asset pool is siloed, e.g. the ETH
 *         pool is independent from the USDC pool.
 */
contract Pool is Roles {
    // Constants
    uint256 public constant UNIT = 10 ** 18;
    uint256 public constant BPS_DIVIDER = 10000;

    // Events
    event PoolDeposit(
        address indexed user,
        address indexed asset,
        uint256 amount,
        uint256 feeAmount,
        uint256 clpAmount,
        uint256 poolBalance,
        uint256 depositId,
        uint256 lockupPeriod,
        uint256 unlockTimestamp
    );

    event DepositsUpdated(
        address indexed user,
        address indexed asset,
        uint256[] depositIds,
        uint256[] amounts
    );

    event PoolWithdrawal(
        address indexed user,
        address indexed asset,
        uint256 amount,
        uint256 feeAmount,
        uint256 clpAmount,
        uint256 poolBalance
    );

    event PoolPayIn(
        address indexed user,
        address indexed asset,
        string market,
        uint256 amount,
        uint256 bufferToPoolAmount,
        uint256 poolBalance,
        uint256 bufferBalance
    );

    event PoolPayOut(
        address indexed user,
        address indexed asset,
        string market,
        uint256 amount,
        uint256 poolBalance,
        uint256 bufferBalance
    );

    event BufferDeposit(
        address indexed user,
        address indexed asset,
        uint256 amount,
        uint256 bufferBalance
    );

    event BufferWithdrawal(
        address indexed user,
        address indexed asset,
        uint256 amount,
        uint256 bufferBalance
    );

    // Contracts
    DataStore public DS;

    AssetStore public assetStore;
    FundStore public fundStore;
    PoolStore public poolStore;

    // Ephemeral storage
    mapping(address => bool) private whitelistedKeepers;
    mapping(address => bool) private yellowlistedKeepers;
    mapping(address => int256) private globalUPLs; // asset => upl

    bool private isYellowlistSystemActivated;

    /// @dev Initializes DataStore address
    function initialize(address rs, address ds) external initializer {
        DS = DataStore(ds);
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @notice Initializes protocol contracts
    /// @dev Only callable by governance
    function link() external onlyGov {
        assetStore = AssetStore(DS.getAddress("AssetStore"));
        fundStore = FundStore(payable(DS.getAddress("FundStore")));
        poolStore = PoolStore(DS.getAddress("PoolStore"));
    }

    /// @notice Yellowlisted system enabling only yellow listed keepers
    /// @param _isActive Activation state
    function activateYellowlistSystem(bool _isActive) external onlyGov {
        isYellowlistSystemActivated = _isActive;
    }

    /// @notice Whitelisted keeper that can update global UPL
    /// @param keeper Keeper address
    function setWhitelistedKeeper(
        address keeper,
        bool isActive
    ) external onlyGov {
        whitelistedKeepers[keeper] = isActive;
    }

    /// @notice Yellowlisted keeper that can execute trades
    /// @param keeper Keeper address
    function setYellowlistedKeeper(
        address keeper,
        bool isActive
    ) external onlyGov {
        yellowlistedKeepers[keeper] = isActive;
    }

    /// @notice Verify if a keeper is Whitelisted
    /// @param keeper Keeper address
    function isKeeperWhitelisted(address keeper) external view returns (bool) {
        return whitelistedKeepers[keeper];
    }

    /// @notice Verify if a keeper is Yellowlisted
    /// @param keeper Keeper address
    function isKeeperYellowlisted(address keeper) external view returns (bool) {
        return !isYellowlistSystemActivated || yellowlistedKeepers[keeper];
    }

    /// @notice Set global UPL, called by whitelisted keeper
    /// @param assets Asset addresses
    /// @param upls Corresponding total unrealized profit / loss
    function setGlobalUPLs(
        address[] calldata assets,
        int256[] calldata upls
    ) external {
        require(whitelistedKeepers[msg.sender], "!unauthorized");
        for (uint256 i = 0; i < assets.length; i++) {
            globalUPLs[assets[i]] = upls[i];
        }
    }

    /// @notice Returns total unrealized p/l for `asset`
    function getGlobalUPL(address asset) external view returns (int256) {
        return globalUPLs[asset];
    }

    /// @notice Returns pool deposit tax for `asset` and amount in bps
    /// @param asset Asset address
    /// @param amount Amount to be deposited
    /// @param lockupPeriodIndex Lockup period index
    /// @return Deposit tax in bps
    function getDepositTaxBps(
        address asset,
        uint256 amount,
        uint256 lockupPeriodIndex
    ) public view returns (uint256) {
        uint256 lockupPeriod = poolStore.getLockupPeriod(lockupPeriodIndex);
        if (
            poolStore.isCustomDepositTaxesLockedActive(asset) &&
            lockupPeriod > 0
        ) {
            return poolStore.getDepositTaxLocked(asset);
        } else if (poolStore.isCustomDepositTaxesUnlockedActive(asset)) {
            return poolStore.getDepositTaxUnlocked(asset);
        }
        uint256 taxBps;
        uint256 balance = poolStore.getBalance(asset);
        uint256 bufferBalance = poolStore.getBufferBalance(asset);
        if (globalUPLs[asset] - int256(bufferBalance) < 0) {
            taxBps = uint256(
                (int256(BPS_DIVIDER) *
                    (int256(bufferBalance) - globalUPLs[asset])) /
                    (int256(balance) + int256(amount))
            );
        }
        return taxBps;
    }

    /// @notice Returns pool withdrawal tax for `asset` and amount in bps
    /// @param asset Asset address
    /// @param amount Amount to be withdrawn
    /// @return Withdrawal tax in bps
    function getWithdrawalTaxBps(
        address asset,
        uint256 amount
    ) public view returns (uint256) {
        if (poolStore.isCustomWithdrawalTaxesActive(asset)) {
            return poolStore.getWithdrawalTax(asset);
        }
        uint256 taxBps;
        uint256 balance = poolStore.getBalance(asset);
        if (amount >= balance) return BPS_DIVIDER;
        uint256 bufferBalance = poolStore.getBufferBalance(asset);
        if (globalUPLs[asset] - int256(bufferBalance) > 0) {
            taxBps = uint256(
                (int256(BPS_DIVIDER) *
                    (globalUPLs[asset] - int256(bufferBalance))) /
                    (int256(balance) - int256(amount))
            );
        }
        return taxBps;
    }

    // -- //

    /// @notice Credit trader loss to buffer and pay pool from buffer amount based on time and payout rate
    /// @param user User which incurred trading loss
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param amount Amount of trader loss
    function creditTraderLoss(
        address user,
        address asset,
        string memory market,
        uint256 amount
    ) external onlyContract {
        // credit trader loss to buffer
        poolStore.incrementBufferBalance(asset, amount);

        // local variables
        uint256 lastPaid = poolStore.getLastPaid(asset);
        uint256 _now = block.timestamp;
        uint256 amountToSendPool;

        if (lastPaid == 0) {
            // during the very first execution, set lastPaid and return
            poolStore.setLastPaid(asset, _now);
        } else {
            // get buffer balance and buffer payout period to calculate amountToSendPool
            uint256 bufferBalance = poolStore.getBufferBalance(asset);
            uint256 bufferPayoutPeriod = poolStore.getBufferPayoutPeriod(asset);
            require(bufferPayoutPeriod > 0, "!payout-period");

            // Stream buffer balance progressively into the pool
            amountToSendPool =
                (bufferBalance * (block.timestamp - lastPaid)) /
                bufferPayoutPeriod;
            if (amountToSendPool > bufferBalance)
                amountToSendPool = bufferBalance;

            // update storage
            poolStore.incrementBalance(asset, amountToSendPool);
            poolStore.decrementBufferBalance(asset, amountToSendPool);
            poolStore.setLastPaid(asset, _now);
        }

        // emit event
        emit PoolPayIn(
            user,
            asset,
            market,
            amount,
            amountToSendPool,
            poolStore.getBalance(asset),
            poolStore.getBufferBalance(asset)
        );
    }

    /// @notice Pay out trader profit, from buffer first then pool if buffer is depleted
    /// @param user Address to send funds to
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param amount Amount of trader profit
    function debitTraderProfit(
        address user,
        address asset,
        string calldata market,
        uint256 amount
    ) external onlyContract {
        // return if profit = 0
        if (amount == 0) return;

        uint256 bufferBalance = poolStore.getBufferBalance(asset);

        // decrement buffer balance first
        poolStore.decrementBufferBalance(asset, amount);

        // if amount is greater than available in the buffer, pay remaining from the pool
        if (amount > bufferBalance) {
            uint256 diffToPayFromPool = amount - bufferBalance;
            uint256 poolBalance = poolStore.getBalance(asset);
            require(diffToPayFromPool <= poolBalance, "!pool-balance");
            poolStore.decrementBalance(asset, diffToPayFromPool);
        }

        // transfer profit out
        fundStore.transferOut(asset, user, amount);

        // emit event
        emit PoolPayOut(
            user,
            asset,
            market,
            amount,
            poolStore.getBalance(asset),
            poolStore.getBufferBalance(asset)
        );
    }

    /// @notice Pay out trader profit, from buffer first then pool if buffer is depleted
    /// @param user Address to send funds to
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param market Market, e.g. "ETH-USD"
    /// @param amount Amount of trader profit
    function debitTraderProfitWithoutTransfer(
        address user,
        address asset,
        string calldata market,
        uint256 amount
    ) external onlyContract {
        // return if profit = 0
        if (amount == 0) return;

        uint256 bufferBalance = poolStore.getBufferBalance(asset);

        // decrement buffer balance first
        poolStore.decrementBufferBalance(asset, amount);

        // if amount is greater than available in the buffer, pay remaining from the pool
        if (amount > bufferBalance) {
            uint256 diffToPayFromPool = amount - bufferBalance;
            uint256 poolBalance = poolStore.getBalance(asset);
            require(diffToPayFromPool <= poolBalance, "!pool-balance");
            poolStore.decrementBalance(asset, diffToPayFromPool);
        }

        // emit event
        emit PoolPayOut(
            user,
            asset,
            market,
            amount,
            poolStore.getBalance(asset),
            poolStore.getBufferBalance(asset)
        );
    }

    /// @notice Deposit 'amount' of 'asset' into the pool
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param amount Amount to be deposited
    function deposit(
        address asset,
        uint256 amount,
        uint256 lockupPeriodIndex
    ) public payable {
        require(assetStore.isSupported(asset), "!asset");

        uint256 balance = poolStore.getBalance(asset);
        address user = msg.sender;

        // if asset is ETH (address(0)), set amount to msg.value
        if (asset == address(0)) {
            amount = msg.value;
            fundStore.transferIn{value: amount}(asset, user, amount);
        } else {
            fundStore.transferIn(asset, user, amount);
        }

        require(amount > 0, "!amount"); // zero amount is not allowed

        // deposit tax
        uint256 taxBps = getDepositTaxBps(asset, amount, lockupPeriodIndex);
        require(taxBps < BPS_DIVIDER, "!tax");
        uint256 tax = (amount * taxBps) / BPS_DIVIDER;
        uint256 amountMinusTax = amount - tax;

        // pool share is equal to pool balance of user divided by the total balance
        uint256 clpSupply = poolStore.getClpSupply(asset);
        uint256 clpAmount = balance == 0 || clpSupply == 0
            ? amountMinusTax
            : (amountMinusTax * clpSupply) / balance;

        // increment balances
        (uint256 dId, uint256 lockupPeriod) = poolStore.incrementUserClpBalance(
            asset,
            user,
            clpAmount,
            lockupPeriodIndex
        );
        poolStore.incrementBalance(asset, amountMinusTax);
        poolStore.incrementBufferBalance(asset, tax);

        // emit event
        emit PoolDeposit(
            user,
            asset,
            amount,
            tax,
            clpAmount,
            poolStore.getBalance(asset),
            dId,
            lockupPeriod,
            lockupPeriod + block.timestamp
        );
    }

    /// @notice Increment buffer balance and transfer funds in
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param amount Amount to be incremented
    function incrementBuffer(
        address asset,
        uint256 amount
    ) external payable onlyGov {
        require(amount > 0, "!amount");
        require(assetStore.isSupported(asset), "!asset");

        address user = msg.sender;

        // if asset is ETH (address(0)), set amount to msg.value
        if (asset == address(0)) {
            amount = msg.value;
            fundStore.transferIn{value: amount}(asset, user, amount);
        } else {
            fundStore.transferIn(asset, user, amount);
        }

        poolStore.incrementBufferBalance(asset, amount);

        emit BufferDeposit(
            user,
            asset,
            amount,
            poolStore.getBufferBalance(asset)
        );
    }

    /// @notice Decrement buffer balance and transfer funds out
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param amount Amount to be decremented
    function decrementBuffer(address asset, uint256 amount) external onlyGov {
        require(
            amount > 0 && amount <= poolStore.getBufferBalance(asset),
            "!amount"
        );
        require(assetStore.isSupported(asset), "!asset");

        address user = msg.sender;

        fundStore.transferOut(asset, user, amount);
        poolStore.decrementBufferBalance(asset, amount);

        emit BufferWithdrawal(
            user,
            asset,
            amount,
            poolStore.getBufferBalance(asset)
        );
    }

    /// @notice Withdraw 'amount' of 'asset'
    /// @param asset Asset address, e.g. address(0) for ETH
    /// @param amount Amount to be withdrawn
    function withdraw(address asset, uint256 amount) public {
        require(amount > 0, "!amount");
        require(assetStore.isSupported(asset), "!asset");

        address user = msg.sender;

        // check pool balance and clp supply
        uint256 balance = poolStore.getBalance(asset);
        uint256 clpSupply = poolStore.getClpSupply(asset);
        require(balance > 0 && clpSupply > 0, "!empty");

        // check user balance
        uint256 userBalance = poolStore.getUserBalance(asset, user);
        if (amount > userBalance) amount = userBalance;

        // withdrawal tax
        uint256 taxBps = getWithdrawalTaxBps(asset, amount);
        require(taxBps < BPS_DIVIDER, "!tax");
        uint256 tax = (amount * taxBps) / BPS_DIVIDER;
        uint256 amountMinusTax = amount - tax;

        // CLP amount
        uint256 clpAmount = (amount * clpSupply) / balance;

        // decrement balances
        (uint256[] memory depositIds, uint256[] memory amounts) = poolStore
            .decrementUserClpBalance(asset, user, clpAmount);
        poolStore.decrementBalance(asset, amount);
        poolStore.incrementBufferBalance(asset, tax);

        // transfer funds out
        fundStore.transferOut(asset, user, amountMinusTax);

        // emit event
        emit PoolWithdrawal(
            user,
            asset,
            amount,
            tax,
            clpAmount,
            poolStore.getBalance(asset)
        );

        emit DepositsUpdated(user, asset, depositIds, amounts);
    }
}

File 17 of 33 : Roles.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Governable.sol";
import "./RoleStore.sol";

/// @title Roles
/// @notice Role-based access control mechanism via onlyContract modifier
abstract contract Roles is Governable {
    bytes32 internal constant CONTRACT_ROLE = keccak256("CONTRACT");

    RoleStore public roleStore;

    /// @dev Reverts if caller address has not the contract role
    modifier onlyContract() {
        require(roleStore.hasRole(msg.sender, CONTRACT_ROLE), "!contract-role");
        _;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";
import "pyth-sdk-solidity/IPyth.sol";

contract PythUpdater is Roles {
    IPyth public pyth;

    function initialize(address rs, address _pyth) external initializer {
        roleStore = RoleStore(rs);
        pyth = IPyth(_pyth);
        _setGov(msg.sender);
    }

    function changePythContract(address _pyth) external onlyGov {
        pyth = IPyth(_pyth);
    }

    function withdraw() external onlyGov {
        // payable(msg.sender).transfer(address(this).balance);
        (bool success, ) = payable(msg.sender).call{
            value: address(this).balance
        }("");
        require(success, "Transfer failed");
    }

    function updatePriceFeed(
        bytes[] calldata priceUpdateData
    ) external onlyContract {
        uint256 pythFee = pyth.getUpdateFee(priceUpdateData);
        require(address(this).balance >= pythFee, "!updater-balance");
        pyth.updatePriceFeeds{value: pythFee}(priceUpdateData);
    }

    receive() external payable {}

    fallback() external payable {}
}

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

import "./Roles.sol";

/// @title ReferralStore
/// @notice Persistent storage for Referral.sol
contract ReferralStore is Roles {
    uint256 constant BPS_DIVIDER = 10000; // 100%

    mapping(address => address) public refereeToReferrer; // referree -> referrer
    mapping(string => address) public referralCodeToReferrer; // referral code -> referrer
    mapping(address => string) public referrerToReferralCode; // referrer -> referral code
    mapping(address => uint256) public referralFeeShare; // user -> referral fee share
    mapping(address => uint256) public rebateFeeShare; // user -> rebate fee share
    mapping(address => bool) public blacklisted; // user -> blacklisted

    uint256 public referrerCount; // number of referrers
    uint256 public refereeCount; // number of referees
    uint256 public defaultReferralFeeShare;
    uint256 public defaultRebateFeeShare;

    bool public referralEnabled;

    event ReferralFeeShareSet(address user, uint256 referralFeeShare);
    event RebateFeeShareSet(address user, uint256 rebateFeeShare);

    /// @notice Initialize the contract
    /// @param rs The address of the RoleStore
    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        referralEnabled = true;
        defaultReferralFeeShare = 125;
        defaultRebateFeeShare = 125;
    }

    function setReferralEnabled(bool _referralEnabled) external onlyGov {
        referralEnabled = _referralEnabled;
    }

    function setDefaultReferralFeeShare(
        uint256 _defaultReferralFeeShare
    ) external onlyGov {
        defaultReferralFeeShare = _defaultReferralFeeShare;
    }

    function setDefaultRebateFeeShare(
        uint256 _defaultRebateFeeShare
    ) external onlyGov {
        defaultRebateFeeShare = _defaultRebateFeeShare;
    }

    /// @notice Blacklist a user
    /// @param _referee The address of the user
    function blacklist(address _referee) external onlyGov {
        blacklisted[_referee] = true;
    }

    /// @notice Unblacklist a user
    /// @param _referee The address of the user
    function unblacklist(address _referee) external onlyGov {
        blacklisted[_referee] = false;
    }

    /// @notice Check if a user is blacklisted
    /// @param user The address of the user
    /// @return True if the user is blacklisted, false otherwise
    function isBlacklisted(address user) external view returns (bool) {
        return blacklisted[user];
    }

    /// @notice Register a new referrer
    /// @param _referrer The address of the referrer
    /// @param _referralCode The referral code
    function registerReferral(
        address _referrer,
        string memory _referralCode
    ) external onlyContract {
        referralCodeToReferrer[_referralCode] = _referrer;
        referrerToReferralCode[_referrer] = _referralCode;
        rebateFeeShare[_referrer] = defaultRebateFeeShare;
        referrerCount++;
    }

    /// @notice Set a referrer for a user
    /// @param _referee The address of the user
    /// @param _referralCode The referral code
    function setReferrer(
        address _referee,
        string memory _referralCode
    ) external onlyContract {
        address referrer = referralCodeToReferrer[_referralCode];
        refereeToReferrer[_referee] = referrer;
        referralFeeShare[_referee] = defaultReferralFeeShare;
        refereeCount++;
    }

    /// @notice Set the referral fee share for a user
    /// @param _user The address of the user
    /// @param _referralFeeShare The referral fee share
    function setReferralFeeShare(
        address _user,
        uint256 _referralFeeShare
    ) external onlyGov {
        referralFeeShare[_user] = _referralFeeShare;
        emit ReferralFeeShareSet(_user, _referralFeeShare);
    }

    /// @notice Set the referral fee shares for a users
    /// @param _users The addresses of the users
    /// @param _referralFeeShares The referral fee shares
    function setReferralFeeShares(
        address[] calldata _users,
        uint256[] calldata _referralFeeShares
    ) external onlyGov {
        for (uint256 i = 0; i < _users.length; i++) {
            referralFeeShare[_users[i]] = _referralFeeShares[i];
            emit ReferralFeeShareSet(_users[i], _referralFeeShares[i]);
        }
    }

    /// @notice Set the rebate fee share for a user
    /// @param _user The address of the user
    /// @param _rebateFeeShare The rebate fee share
    function setRebateFeeShare(
        address _user,
        uint256 _rebateFeeShare
    ) external onlyGov {
        rebateFeeShare[_user] = _rebateFeeShare;
        emit RebateFeeShareSet(_user, _rebateFeeShare);
    }

    /// @notice Set the rebate fee shares for a users
    /// @param _users The addresses of the users
    /// @param _rebateFeeShares The rebate fee shares
    function setRebateFeeShares(
        address[] calldata _users,
        uint256[] calldata _rebateFeeShares
    ) external onlyGov {
        for (uint256 i = 0; i < _users.length; i++) {
            rebateFeeShare[_users[i]] = _rebateFeeShares[i];
            emit RebateFeeShareSet(_users[i], _rebateFeeShares[i]);
        }
    }

    /// @notice Get the rebate fee share for a user
    /// @param _user The address of the user
    /// @return The rebate fee share
    function getRebateFeeShare(address _user) external view returns (uint256) {
        if (blacklisted[_user] || !referralEnabled) {
            return 0;
        }
        return rebateFeeShare[_user];
    }

    /// @notice Get the referral fee share for a user
    /// @param _user The address of the user
    /// @return The referral fee share
    function getReferralFeeShare(
        address _user
    ) external view returns (uint256) {
        if (blacklisted[_user] || !referralEnabled) {
            return 0;
        }
        return referralFeeShare[_user];
    }

    /// @notice Get the referrer by referral code
    /// @param _referralCode The referral code
    /// @return The address of the referrer
    function getReferrerByReferralCode(
        string memory _referralCode
    ) external view returns (address) {
        return referralCodeToReferrer[_referralCode];
    }

    /// @notice Get the referral code for a referrer
    /// @param _referrer The address of the referrer
    /// @return The referral code
    function getReferralCode(
        address _referrer
    ) external view returns (string memory) {
        return referrerToReferralCode[_referrer];
    }

    /// @notice Get the referrer for a user
    /// @param _referee The address of the user
    /// @return The address of the referrer
    function getReferrer(address _referee) external view returns (address) {
        return refereeToReferrer[_referee];
    }

    /// @notice Get the rebate fee shares for multiple users
    /// @param users The addresses of the users
    /// @return The rebate fee shares
    function getRebateFeeShares(
        address[] calldata users
    ) external view returns (uint256[] memory) {
        uint256[] memory rebateShares = new uint256[](users.length);
        for (uint256 i = 0; i < users.length; i++) {
            if (blacklisted[users[i]] || !referralEnabled) {
                rebateShares[i] = 0;
            } else {
                rebateShares[i] = rebateFeeShare[users[i]];
            }
        }
        return rebateShares;
    }

    /// @notice Get the referral fee shares for multiple users
    /// @param users The addresses of the users
    /// @return The referral fee shares
    function getReferralFeeShares(
        address[] calldata users
    ) external view returns (uint256[] memory) {
        uint256[] memory referralShares = new uint256[](users.length);
        for (uint256 i = 0; i < users.length; i++) {
            if (blacklisted[users[i]] || !referralEnabled) {
                referralShares[i] = 0;
            } else {
                referralShares[i] = referralFeeShare[users[i]];
            }
        }
        return referralShares;
    }
}

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

import "./Roles.sol";

/// @title RebateStore
/// @notice Store for Rebate.sol
contract RebateStore is Roles {
    uint256 constant BPS_DIVIDER = 10000; // 100%

    mapping(address => mapping(address => uint256)) public rebate; // user -> asset -> rebate

    /// @notice Initialize the RebateStore
    /// @param rs The address of the RoleStore
    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
    }

    /// @notice Increment the rebate for a user and asset
    /// @param _user The address of the user
    /// @param _asset The address of the asset
    /// @param _amount The amount of rebate
    function incrementRebate(
        address _user,
        address _asset,
        uint256 _amount
    ) external onlyContract {
        rebate[_user][_asset] += _amount;
    }

    /// @notice Reset the rebate for a user and asset
    /// @param _user The address of the user
    /// @param _asset The address of the asset
    function resetRebate(address _user, address _asset) external onlyContract {
        rebate[_user][_asset] = 0;
    }

    /// @notice Get the rebate for a user and asset
    /// @param _user The address of the user
    /// @param _asset The address of the asset
    /// @return The rebate
    function getRebate(
        address _user,
        address _asset
    ) external view returns (uint256) {
        return rebate[_user][_asset];
    }
}

File 21 of 33 : PythPriceUtils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "pyth-sdk-solidity/PythStructs.sol";

library PythPriceUtils {
    function toUint256(
        PythStructs.Price memory priceData
    ) internal pure returns (uint256) {
        require(priceData.price > 0, "!invalid-price");

        int256 exponent = int256(18) + priceData.expo;
        require(exponent >= 0, "!invalid-exp");

        uint256 base = 10 ** uint256(exponent);

        return uint256(int256(priceData.price)) * base;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";

/// @title BuyBackStore
/// @notice Persistent storage for BuyBack.sol
contract BuyBackStore is Roles {
    // Constants
    uint256 public constant BPS_DIVIDER = 10000;
    uint256 public constant UNIT = 10 ** 18;

    // Fee share for Buyback
    uint256 public feeShare;

    // Asset to balance
    mapping(address => uint256) private assetsBalances;
    uint256 public pinguBalance;

    // BuyBack reward in bps
    uint256 public buyBackReward;

    // BuyBack paused state
    bool public paused;

    // @notice Initialize the BuyBackStore
    /// @param rs The address of the RoleStore
    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        pinguBalance = 0;
        feeShare = 3500;
        buyBackReward = 100;
        paused = false;
    }

    /// @notice Set the fee share
    /// @param _feeShare The fee share
    function setFeeShare(uint256 _feeShare) external onlyGov {
        require(_feeShare <= BPS_DIVIDER, "!feeShare");
        feeShare = _feeShare;
    }

    /// @notice Set the buy back reward
    /// @param _buyBackReward The buy back reward
    function setBuyBackReward(uint256 _buyBackReward) external onlyGov {
        require(_buyBackReward <= BPS_DIVIDER, "!reward");
        buyBackReward = _buyBackReward;
    }

    /// @notice Set the paused state
    /// @param _paused The paused state
    function setPaused(bool _paused) external onlyGov {
        paused = _paused;
    }

    /// @notice Increment the asset balance
    /// @param asset The address of the asset
    /// @param amount The amount of the asset
    function incrementAssetBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        assetsBalances[asset] += amount;
    }

    /// @notice Decrement the asset balance
    /// @param asset The address of the asset
    /// @param amount The amount of the asset
    function decrementAssetBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        assetsBalances[asset] = assetsBalances[asset] <= amount
            ? 0
            : assetsBalances[asset] - amount;
    }

    /// @notice Reset the asset balance
    /// @param asset The address of the asset
    function resetAssetBalance(address asset) external onlyContract {
        assetsBalances[asset] = 0;
    }

    /// @notice Increment the Pingu balance
    /// @param amount The amount of the Pingu
    function incrementPinguBalance(uint256 amount) external onlyContract {
        pinguBalance += amount;
    }

    /// @notice Decrement the Pingu balance
    /// @param amount The amount of the Pingu
    function decrementPinguBalance(uint256 amount) external onlyContract {
        pinguBalance = pinguBalance <= amount ? 0 : pinguBalance - amount;
    }

    /// @notice Reset the Pingu balance
    function resetPinguBalance() external onlyContract {
        pinguBalance = 0;
    }

    /// @notice Get the asset balance
    /// @param asset The address of the asset
    /// @return The balance of the asset
    function getAssetBalance(address asset) external view returns (uint256) {
        return assetsBalances[asset];
    }

    /// @notice Get the asset balances
    /// @param assets The addresses of the assets
    /// @return The balances of the assets array
    function getAssetsBalances(
        address[] memory assets
    ) external view returns (uint256[] memory) {
        uint256 length = assets.length;
        uint256[] memory balances = new uint256[](length);
        for (uint256 i = 0; i < length; i++) {
            balances[i] = assetsBalances[assets[i]];
        }
        return balances;
    }

    /// @notice Get the Pingu balance
    /// @return The balance of the Pingu
    function getPinguBalance() external view returns (uint256) {
        return pinguBalance;
    }

    /// @notice Get the fee share
    /// @return The fee share
    function getFeeShare() external view returns (uint256) {
        return feeShare;
    }

    /// @notice Get the buy back reward
    /// @return The buy back reward
    function getBuyBackReward() external view returns (uint256) {
        return buyBackReward;
    }

    /// @notice Get the paused state
    /// @return The paused state
    function isPaused() external view returns (bool) {
        return paused;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

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

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

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

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

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

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

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

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

File 24 of 33 : IPythEvents.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;

/// @title IPythEvents contains the events that Pyth contract emits.
/// @dev This interface can be used for listening to the updates for off-chain and testing purposes.
interface IPythEvents {
    /// @dev Emitted when the price feed with `id` has received a fresh update.
    /// @param id The Pyth Price Feed ID.
    /// @param publishTime Publish time of the given price update.
    /// @param price Price of the given price update.
    /// @param conf Confidence interval of the given price update.
    event PriceFeedUpdate(
        bytes32 indexed id,
        uint64 publishTime,
        int64 price,
        uint64 conf
    );
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

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

/// @title Governable
/// @notice Basic access control mechanism, gov has access to certain functions
abstract contract Governable is Initializable {
    address public gov;

    event SetGov(address prevGov, address nextGov);

    /// @dev Reverts if called by any account other than gov
    modifier onlyGov() {
        require(msg.sender == gov, "!gov");
        _;
    }

    /// @notice Sets a new governance address
    /// @dev Only callable by governance
    function setGov(address _gov) external onlyGov {
        _setGov(_gov);
    }

    /// @notice Sets a new governance address
    /// @dev Internal function without access restriction
    function _setGov(address _gov) internal {
        require(_gov != address(0), "!zero-gov");
        address prevGov = gov;
        gov = _gov;
        emit SetGov(prevGov, _gov);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";

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

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

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

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

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

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

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity 0.8.17;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 *  Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.
 *  See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 *  In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./EnumerableSet.sol";
import "./Governable.sol";

/**
 * @title  RoleStore
 * @notice Role-based access control mechanism. Governance can grant and
 *         revoke roles dynamically via {grantRole} and {revokeRole}
 */
contract RoleStore is Governable {
    // Libraries
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;

    event RoleGranted(
        bytes32 indexed role,
        address indexed account,
        address indexed sender
    );
    event RoleRevoked(
        bytes32 indexed role,
        address indexed account,
        address indexed sender
    );

    // Set of roles
    EnumerableSet.Bytes32Set internal roles;

    // Role -> address
    mapping(bytes32 => EnumerableSet.AddressSet) internal roleMembers;

    function initialize() external initializer {
        _setGov(msg.sender);
    }

    /// @notice Grants `role` to `account`
    /// @dev Only callable by governance
    function grantRole(address account, bytes32 role) external onlyGov {
        // add role if not already present
        if (!roles.contains(role)) roles.add(role);

        require(roleMembers[role].add(account));
        emit RoleGranted(role, account, msg.sender);
    }

    /// @notice Revokes `role` from `account`
    /// @dev Only callable by governance
    function revokeRole(address account, bytes32 role) external onlyGov {
        require(roleMembers[role].remove(account));
        emit RoleRevoked(role, account, msg.sender);

        // Remove role if it has no longer any members
        if (roleMembers[role].length() == 0) {
            roles.remove(role);
        }
    }

    /// @notice Returns `true` if `account` has been granted `role`
    function hasRole(
        address account,
        bytes32 role
    ) external view returns (bool) {
        return roleMembers[role].contains(account);
    }

    /// @notice Returns number of roles
    function getRoleCount() external view returns (uint256) {
        return roles.length();
    }
}

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

pragma solidity ^0.8.2;

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

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

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

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

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

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

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

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

    /**
     * @dev Internal function that returns the initialized version. Returns `_initialized`
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initializing`
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

Settings
{
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "chainlink/=node_modules/@chainlink/",
    "pyth-sdk-solidity/=node_modules/@pythnetwork/pyth-sdk-solidity/",
    "@uniswap/v2-periphery/=node_modules/@uniswap/v2-periphery/",
    "@uniswap/v2-core/=node_modules/@uniswap/v2-core/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "viaIR": true
}

Contract Security Audit

Contract ABI

API
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"orderId","type":"uint256"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"string","name":"market","type":"string"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"poolFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"buyBackFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"treasuryFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"keeperFee","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isLiquidation","type":"bool"},{"indexed":false,"internalType":"uint256","name":"referrerRebate","type":"uint256"}],"name":"FeePaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"string","name":"market","type":"string"},{"indexed":false,"internalType":"uint256","name":"marginDiff","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionMargin","type":"uint256"}],"name":"MarginDecreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"string","name":"market","type":"string"},{"indexed":false,"internalType":"uint256","name":"marginDiff","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionMargin","type":"uint256"}],"name":"MarginIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"orderId","type":"uint256"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"string","name":"market","type":"string"},{"indexed":false,"internalType":"bool","name":"isLong","type":"bool"},{"indexed":false,"internalType":"uint256","name":"size","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"margin","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionMargin","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionSize","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionPrice","type":"uint256"},{"indexed":false,"internalType":"int256","name":"fundingTracker","type":"int256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"},{"indexed":false,"internalType":"int256","name":"pnl","type":"int256"},{"indexed":false,"internalType":"int256","name":"pnlUsd","type":"int256"},{"indexed":false,"internalType":"int256","name":"fundingFee","type":"int256"}],"name":"PositionDecreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"orderId","type":"uint256"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"string","name":"market","type":"string"},{"indexed":false,"internalType":"bool","name":"isLong","type":"bool"},{"indexed":false,"internalType":"uint256","name":"size","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"margin","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionMargin","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionSize","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"positionPrice","type":"uint256"},{"indexed":false,"internalType":"int256","name":"fundingTracker","type":"int256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"PositionIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"prevGov","type":"address"},{"indexed":false,"internalType":"address","name":"nextGov","type":"address"}],"name":"SetGov","type":"event"},{"inputs":[],"name":"BPS_DIVIDER","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DS","outputs":[{"internalType":"contract DataStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNIT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"uint256","name":"margin","type":"uint256"}],"name":"addMargin","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"assetStore","outputs":[{"internalType":"contract AssetStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"buyBackStore","outputs":[{"internalType":"contract BuyBackStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"string","name":"_market","type":"string"},{"internalType":"bytes[]","name":"priceUpdateData","type":"bytes[]"}],"name":"closePositionWithoutProfit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"orderId","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"uint256","name":"fee","type":"uint256"},{"internalType":"bool","name":"isLiquidation","type":"bool"},{"internalType":"address","name":"keeper","type":"address"}],"name":"creditFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"orderId","type":"uint256"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"address","name":"keeper","type":"address"}],"name":"decreasePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fundStore","outputs":[{"internalType":"contract FundStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"funding","outputs":[{"internalType":"contract Funding","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fundingStore","outputs":[{"internalType":"contract FundingStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"bool","name":"isLong","type":"bool"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"positionPrice","type":"uint256"},{"internalType":"uint256","name":"size","type":"uint256"},{"internalType":"int256","name":"fundingTracker","type":"int256"}],"name":"getPnL","outputs":[{"internalType":"int256","name":"pnl","type":"int256"},{"internalType":"int256","name":"fundingFee","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gov","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"orderId","type":"uint256"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"address","name":"keeper","type":"address"}],"name":"increasePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"rs","type":"address"},{"internalType":"address","name":"ds","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"link","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"marketStore","outputs":[{"internalType":"contract MarketStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"orderStore","outputs":[{"internalType":"contract OrderStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolStore","outputs":[{"internalType":"contract PoolStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"positionStore","outputs":[{"internalType":"contract PositionStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pyth","outputs":[{"internalType":"contract IPyth","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pythUpdater","outputs":[{"internalType":"contract PythUpdater","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rebateStore","outputs":[{"internalType":"contract RebateStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referralStore","outputs":[{"internalType":"contract ReferralStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"uint256","name":"margin","type":"uint256"},{"internalType":"bytes[]","name":"priceUpdateData","type":"bytes[]"}],"name":"removeMargin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"riskStore","outputs":[{"internalType":"contract RiskStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"roleStore","outputs":[{"internalType":"contract RoleStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_gov","type":"address"}],"name":"setGov","outputs":[],"stateMutability":"nonpayable","type":"function"}]

608080604052346100175761585490816200001d8239f35b600080fdfe608080604052600436101561001357600080fd5b600090813560e01c9081630278198d14613c8057508063032e73e314613c57578063077d17f814613c2e57806312d43a5114613c0357806316f0115b14613bda5780631c4695f4146134035780632ac38dbd146133da5780633157d39d146133b15780633f34b2b21461293f5780634242bac01461291657806346ffceec1461280f578063485cc955146126b65780634a4a7b041461268d578063597a0e36146126645780635f7ddaaa1461263b57806360465d111461261257806362ef7229146121835780636c36609414611e6c5780637c4283bc14611e4f578063835f165114611dde578063861b6a9014611db55780639d8e217714611d92578063a5a06d1d1461188a578063a9aa28e114610276578063b8d2c6931461024d578063cb4c86b714610224578063cfad57a2146101e8578063d4dd357e146101bf578063f4b88717146101965763f98d06f01461016b57600080fd5b34610193578060031936011261019357600e546040516001600160a01b039091168152602090f35b80fd5b5034610193578060031936011261019357600f546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576010546040516001600160a01b039091168152602090f35b503461019357602036600319011261019357610221610205613cbb565b61021c60018060a01b03845460101c163314613dfc565b613e2e565b80f35b5034610193578060031936011261019357600c546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576006546040516001600160a01b039091168152602090f35b50346101935761028536613cd1565b60015460405163ac4ab3fb60e01b81523360048201526000805160206157ff8339815191526024820152929392906001600160a01b0316602082604481845afa91821561147357869261184a575b506102df602492613ef2565b600754604051634a83e9cd60e11b81526004810186905292879184919082906001600160a01b03165afa91821561147357869261182e575b506009546020830151604080850151606086015191516306e32f3b60e11b8152938a9385936001600160a01b03928316938593849361035e939282169116600485016141d2565b03915afa908115611823578791611809575b50608081015160a0840151919082811115611803575081955b610394878094614283565b9689948a90610140880151156117d0575b6103c16103b68460e08b01516141fb565b60a08a015190614231565b9060448d60018060a01b0360208c015116928b6020606060018060a01b03604084015116920151926040519586809263ac4ab3fb60e01b82523360048301526000805160206157ff83398151915260248301525afa9485156112b0578e94879496611783575b5061043461043a96613ef2565b89614671565b6101408801511561177b57945b60095460408901516060808b0151908801518f93901515926001600160a01b039081169116803b15611492578492838993610498604051978896879586946305dfed9960e11b8652600486016140bf565b03925af1801561100957611767575b50600c5460408a015160608b01516001600160a01b039283169290911690823b15611496576104ef92849283604051809681958294635ff2138760e01b8452600484016140f2565b03925af180156110095761174f575b506105308c8560018060a01b0360408d0151169160608d01519060608b0151151560e08c01519260c08d0151956154c5565b94909283916105516105468260a08c01516141fb565b60808b015190614231565b9461055f60a08b015161430d565b1261171f57505050905061057660a086015161430d565b60a08601519660808701518360808901525b600a5460408c01516001600160a01b039182169116813b1561100557859160448392604051948593849263e3af01bb60e01b845260048401528960248401525af19081156114e657859161170b575b505060808801516116a95760095460208c015160408d015160608e01516001600160a01b039182169392821692909116803b1561144b57610632938880946040519687958694859363e512766b60e01b8552600485016141d2565b03925af19081156114e6578591611695575b50505b83831215611605576106588361430d565b600d5460208d015160408e015160608f01516001600160a01b039182169392821692909116803b156116015784938980946106a96040519788968795869463b931db6d60e01b865260048601614251565b03925af1801561147357849187916115ea575b50506106c791614224565b8981106115d4575b505b6007546001600160a01b0316803b1561149257848091602460405180948193634cc8221560e01b83528d60048401525af19081156114e65785916115c0575b505060045460408c015160208d01516001600160a01b03908116979181169216803b156112985760405163078d3b7960e01b81526001600160a01b039384166004820152979092166024880152604487015284908690606490829084905af19384156115b4578b958f95611590575b5050917f5a3ca482b3cc533b228c98d56dbb9e80ed3986e661e13396977a90a594476b8c95916101a0949360018060a01b036020880151169960018060a01b036040890151169b61010060608a015199015115159660a08301519060808401519260c060e0860151950151956108006040519d8d8f9e8f908152019061409a565b9a60208d015260408c015260608b015260808a015260a089015260c088015260e08701526101008601526101208501526101408401528d6101608401526101808301520390a46101408201511580611587575b61085b578580f35b60018060a01b036020830151169160608101519160018060a01b03604083015116956108a261010084015115159360a06108998460e08401516141fb565b91015190614231565b9160405194856101c08101106001600160401b036101c088011117611571578a986020976101c088016040528a88528888015260408701526060860152608085015260a08401528560c084015260e083015261010082015283610120820152836101408201524261016082015283610180820152836101a082015260018060a01b036007541660405180958180946367637b9160e01b82528660048301528051602483015260018060a01b038782015116604483015260018060a01b0360408201511660648301526101a061098860608301516101c060848601526101e485019061409a565b91608081015160a485015260a081015160c485015260c081015160e485015260e0810151610104850152610100810151151561012485015260ff6101208201511661014485015261014081015115156101648501526101608101516101848501526101808101516101a485015201516101c483015203925af1908115611566578491611531575b60015460405163ac4ab3fb60e01b81523360048201526000805160206157ff83398151915260248201529350602090849060449082906001600160a01b03165afa9283156114e65785936114f1575b50610a6a602493613ef2565b600754604051634a83e9cd60e11b81526004810184905293869185919082906001600160a01b03165afa9283156114e65785936114c2575b50600a546040840151606085015160a08601516101008701518994901515936001600160a01b0390811693911690813b15611005578593610af960405196879586948594636615984360e11b8652600486016140bf565b03915afa8015611009576114ae575b506009546040850151606086015160a08701516101008801511515936001600160a01b03938416939192911690813b1561100557858094610b5f6040519788968795869463428d156160e01b8652600486016140bf565b03925af180156110095761149a575b50600c54604085015160608601516001600160a01b039283169290911690823b1561149657610bb692849283604051809681958294635ff2138760e01b8452600484016140f2565b03925af180156110095761147e575b506009546020850151604080870151606088015191516306e32f3b60e11b815297949388936001600160a01b039182169385938493610c0c939181169116600485016141d2565b03915afa93841561147357869461144f575b50610c65610c4c610c38608087015160e0880151906141fb565b610c468860a08601516141fb565b90614224565b610c5f608087015160a085015190614224565b90614231565b8660018060a01b03600a541660018060a01b036040850151169060608501519160a08601519160808a01519361010088015115159260608c0151151594833b1561144b578795610cd9956040519889978896879663b525a2df60e01b8852600488015260c0602488015260c487019061409a565b9360448601526064850152608484015260a483015203915afa801561100957611437575b5060808601518061106e5750506020828101516001600160a01b0390811687526040808501805183168985015260608087018051848c015242610100808d01919091528801511515918b0191909152600c5491519051925163f612620760e01b8152949385939281169284928392610d7a929116600484016140f2565b03915afa90811561106357889161102c575b5060c08601525b610da560a08301516080870151614224565b6080860152610dbc608083015160a0870151614224565b60a086015260e085015260095486906001600160a01b0316803b15611014578160405180926378eaac7d60e01b8252818381610dfb8c60048301614290565b03925af1801561100957611018575b506007546001600160a01b0316803b1561101457818091602460405180948193634cc8221560e01b83528a60048401525af1801561100957610ff1575b5050602081810151604080840151606085015160e0860151600154935163ac4ab3fb60e01b81523360048201526000805160206157ff83398151915260248201526001600160a01b0393841698969195929492841693909283916044918391165afa908115610fe6578b91610f80575b50916000805160206157df83398151915296610edc9492610434610f44989795613ef2565b60018060a01b036020820151169460018060a01b036040830151169660608301519261010081015115159260a08201519260808301519060a08301519060808401519260e060c081870151960151960151966040519a8b9a6101408c526101408c019061409a565b9860208b015260408a01526060890152608088015260a087015260c086015260e08501526101008401526101208301520390a438808080808580f35b939195949290506020843d602011610fde575b81610fa060209383613d0e565b81010312610fda576000805160206157df83398151915296610f4496610434610fcb610edc97613ee5565b93959798505092945096610eb7565b8a80fd5b3d9150610f93565b6040513d8d823e3d90fd5b610ffa90613cfb565b611005578538610e47565b8580fd5b6040513d84823e3d90fd5b5080fd5b61102190613cfb565b611005578538610e0a565b90506020813d60201161105b575b8161104760209383613d0e565b81010312611056575138610d8c565b600080fd5b3d915061103a565b6040513d8a823e3d90fd5b61109e9060018060a01b036020890151169060408901518a60608b0151151560e08c01519260c08d0151956154c5565b809150611134575b5050600c54602086810151604080890151905163f612620760e01b81529384926001600160a01b0391821692849283926110e5929116600484016140f2565b03915afa908115611063578891611102575b5060c0860152610d93565b90506020813d60201161112c575b8161111d60209383613d0e565b810103126110565751386110f7565b3d9150611110565b8181131561140c57805b60a0880151916060890151158481159283611402575b83156113e4575b5050506000146112bb5760a088015180821061117e575b505050505b86386110a6565b8161118891614283565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b15611298578680946111d96040519788968795869463b931db6d60e01b865260048601614251565b03925af19081156112b057839161129c575b505061120990611204608089015160a08a0151906141fb565b614231565b611217816080890151614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b156110055785809461126e604051978896879586946305dfed9960e11b8652600486016140bf565b03925af1801561100957611284575b8080611172565b61128d90613cfb565b61129857863861127d565b8680fd5b6112a590613cfb565b6110145781386111eb565b6040513d85823e3d90fd5b6112c58183614224565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b156112985786809461131660405197889687958694632087829b60e11b865260048601614251565b03925af19081156112b05783916113d0575b505061134190611204608089015160a08a0151906141fb565b61134f608088015182614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b15611005578580946113a66040519788968795869463428d156160e01b8652600486016140bf565b03925af18015611009576113bc575b5050611177565b6113c590613cfb565b6112985786386113b5565b6113d990613cfb565b611014578138611328565b91925090826113f8575b505038848161115b565b12905083386113ee565b8181139350611154565b9050600160ff1b811461142357808891820361113e565b634e487b7160e01b88526011600452602488fd5b61144090613cfb565b611298578638610cfd565b8780fd5b61146c9194503d8088833e6114648183613d0e565b810190614114565b9238610c1e565b6040513d88823e3d90fd5b61148790613cfb565b611492578438610bc5565b8480fd5b8380fd5b6114a390613cfb565b611492578438610b6e565b6114b790613cfb565b611492578438610b08565b6114df9193503d8087833e6114d78183613d0e565b810190613f94565b9138610aa2565b6040513d87823e3d90fd5b92506020833d602011611529575b8161150c60209383613d0e565b8101031261149257610a6a611522602494613ee5565b9350610a5e565b3d91506114ff565b90506020823d60201161155e575b8161154c60209383613d0e565b81010312611056576044915190610a0f565b3d915061153f565b6040513d86823e3d90fd5b634e487b7160e01b600052604160045260246000fd5b50831515610853565b909294506115a091939550613cfb565b6115b057918b9189938e3861077f565b8c80fd5b604051903d90823e3d90fd5b6115c990613cfb565b611496578338610710565b94610c466115e392968b614283565b93386106cf565b6115f5919250613cfb565b611492578285386106bc565b8880fd5b600d5460208c015160408d015160608e01519397936001600160a01b039182169392821692909116803b1561144b578693888094611659604051978896879586946309a599fb60e31b865260048601614251565b03925af19081156114e6578591611681575b505061167b90610c46838b614283565b936106d1565b61168a90613cfb565b61149657833861166b565b61169e90613cfb565b611496578338610644565b6009546001600160a01b0316803b15611492576040516378eaac7d60e01b815290859082908183816116de8f60048301614290565b03925af19081156114e65785916116f7575b5050610647565b61170090613cfb565b6114965783386116f0565b61171490613cfb565b6114965783386105d7565b611745906117368660a08c9d9697989d0151614283565b60a08b015260808a0151614283565b6080890152610588565b61175890613cfb565b611763578b386104fe565b8b80fd5b61177090613cfb565b611763578b386104a7565b508a94610447565b9350935093506020823d6020116117c8575b816117a260209383613d0e565b810103126117c45761043a938d936104346117bd8895613ee5565b9650610427565b8f80fd5b3d9150611795565b9550506117ef6117e48260808901516141fb565b60a088015190614231565b6117fd816080890151614283565b956103a5565b95610389565b61181d91503d8089833e6114648183613d0e565b38610370565b6040513d89823e3d90fd5b6118439192503d8088833e6114d78183613d0e565b9038610317565b91506020823d602011611882575b8161186560209383613d0e565b81010312611005576102df61187b602493613ee5565b92506102d3565b3d9150611858565b5034610193576080366003190112610193576118a4613cbb565b6001600160401b0390602435828111611496576118c5903690600401613d9f565b919092606435908111611492576118e0903690600401613dcc565b600754604051637699d2c160e11b815292939290602090829060049082906001600160a01b03165afa8015611823578790611d57575b6119219150156145e1565b60065460405163349f642f60e11b81526020600482015290879082906001600160a01b03168180611956602482018b8d614351565b03915afa908115611823578791611d35575b506009546040516306e32f3b60e11b81529490889086906001600160a01b0316818061199a8b8d8b3360048601614372565b03915afa948515611063578895611d19575b506119bc6080860151151561439b565b6119cd60443560a087015111614617565b6119dd60443560a0870151614283565b926080860151670de0b6b3a7640000908082029082820403611d055785611a0391614231565b6060850151828102928184041490151715611d055711611cd057600f5489926001600160a01b0390911691823b1561149657611a58928492836040518096819582946382f2d25960e01b8452600484016143d3565b03925af1801561100957611cbc575b5050611a97611aa082610120611a84610140611aca960151615615565b611a918296921515614575565b42614283565b910151116145aa565b606085015115159060e086015160808701519160c088015193611ac4368b8d613d4a565b886154c5565b50868112611be9575b5060a083015260095485906001600160a01b0316803b15611014578160405180926378eaac7d60e01b8252818381611b0e8a60048301614290565b03925af1801561100957611bd5575b506004546001600160a01b0316803b156110145760405163078d3b7960e01b81526001600160a01b038416600482015233602482015260448035908201529082908290606490829084905af1801561100957611bc1575b505060a07f0f449301999d3383602e2a69160bbb040a065132cd68168def96131d8b9946a392015190611bbb60405192839260018060a01b0316963396604435918561464d565b0390a380f35b611bca90613cfb565b611492578438611b74565b611bde90613cfb565b611492578438611b1d565b611bf29061430d565b600954604051630d61264760e31b815290602090829060049082906001600160a01b03165afa908115611063578891611c8a575b50612710908103818111611c7657611c3e90846141fb565b041115611c4b5738611ad3565b606460405162461bcd60e51b8152602060048201526004602482015263085d5c1b60e21b6044820152fd5b634e487b7160e01b89526011600452602489fd5b90506020813d602011611cb4575b81611ca560209383613d0e565b81010312611056575138611c26565b3d9150611c98565b611cc590613cfb565b611298578638611a67565b60405162461bcd60e51b815260206004820152600d60248201526c216d61782d6c6576657261676560981b6044820152606490fd5b634e487b7160e01b8b52601160045260248bfd5b611d2e9195503d808a833e6114648183613d0e565b93386119ac565b611d5191503d8089833e611d498183613d0e565b810190614462565b38611968565b506020813d602011611d8a575b81611d7160209383613d0e565b8101031261129857611d8561192191613ee5565b611916565b3d9150611d64565b50346101935780600319360112610193576020604051670de0b6b3a76400008152f35b5034610193578060031936011261019357600a546040516001600160a01b039091168152602090f35b50346101935760e036600319011261019357611df8613cbb565b90602435906001600160401b0382116101935750611e1a903690600401613d81565b60443591821515830361105657604092611e439260c4359260a4359260843592606435926154c5565b82519182526020820152f35b503461019357806003193601126101935760206040516127108152f35b50606036600319011261019357611e81613cbb565b6024356001600160401b03811161206157611ea0903690600401613d9f565b6044359260018060a01b039160046020846007541660405192838092637699d2c160e11b82525afa8015611823578790612149575b611ee09150156145e1565b849280600954168760405180926306e32f3b60e11b82528180611f09888c8b3360048601614372565b03915afa90811561106357889161212f575b506080810194611f2d8651151561439b565b888386169889156000146120c25750905034948360045416803b156120615760405163e4652f4960e01b81526001600160a01b03929092166004830152336024830152604482018790528290829060649082908a905af18015611009576120ae575b50505b611f9d841515614617565b60a0810194611fad858751614224565b865251670de0b6b3a764000090808202908282040361209a578651611fd191614231565b1061206557879160095416803b15612061576040516378eaac7d60e01b815291839183918290849082906120089060048301614290565b03925af180156110095761204d575b5050611bbb7f69dea4780434a9e7bcd91f9c264463d2db6f4f8088762fd4b51b944b57908e78935160405193849333978561464d565b61205690613cfb565b611005578538612017565b8280fd5b60405162461bcd60e51b815260206004820152600d60248201526c216d696e2d6c6576657261676560981b6044820152606490fd5b634e487b7160e01b8a52601160045260248afd5b6120b790613cfb565b61144b578738611f8f565b909195846004541691823b156114965760405163e4652f4960e01b81526001600160a01b0392909216600483015233602483015260448201529082908290606490829084905af180156110095761211b575b5050611f92565b61212490613cfb565b61144b578738612114565b61214391503d808a833e6114648183613d0e565b38611f1b565b506020813d821161217b575b8161216260209383613d0e565b8101031261129857612176611ee091613ee5565b611ed5565b3d9150612155565b5034610193576060366003190112610193578061219e613cbb565b6001600160401b0360243581811161260d576121be903690600401613d9f565b939091604435908111611014576121d9903690600401613dcc565b6009546040516306e32f3b60e11b81529392906001600160a01b03168385806122088b8a8c3360048601614372565b0381845afa9485156115665784956125f1575b5061222b6080860151151561439b565b60808501516060860151151590823b156110055761227c928a878b8b948296604051988997889687956305dfed9960e11b875260018060a01b03166004870152608060248701526084860191614351565b916044840152606483015203925af19081156115665784916125dd575b5050600c546001600160a01b0316803b156114965760408051635ff2138760e01b81526001600160a01b0389166004820152602481019190915290849082908183816122e9604482018f8e614351565b03925af19081156115665784916125c9575b5050600f546001600160a01b031691823b1561149657612334928492836040518096819582946382f2d25960e01b8452600484016143d3565b03925af18015611009576125b5575b505060065460405163349f642f60e11b8152602060048201529390869085906001600160a01b0316818061237b602482018b8a614351565b03915afa93841561147357611a97946123b491889161259b575b506101206123a7610140830151615615565b611a918299921515614575565b856123dc6060840151151560e08501516080860151908860c088015193611ac4368d8c613d4a565b5012612566576009548693906001600160a01b0316803b156114925784604051809263e512766b60e01b825281838161241b8d898b3360048601614372565b03925af19081156114e6578591612552575b505060045460a0840180519094916001600160a01b0316803b156112985760405163078d3b7960e01b81526001600160a01b0386166004820152336024820152604481019290925286908290606490829084905af190811561147357869161253e575b50507f5a3ca482b3cc533b228c98d56dbb9e80ed3986e661e13396977a90a594476b8c936060820151159660808301519151906124e460c060e0860151950151956040519b8c6101a08091528d0191614351565b9860208b01528260408b01528160608b015260808a015260a089015260c088015260e08701526101008601528261012086015282610140860152826101608601528261018086015260018060a01b0316938033940390a480f35b61254790613cfb565b611492578438612490565b61255b90613cfb565b61149657833861242d565b60405162461bcd60e51b815260206004820152600d60248201526c21706e6c2d706f73697469766560981b6044820152606490fd5b6125af91503d808a833e611d498183613d0e565b38612395565b6125be90613cfb565b611492578438612343565b6125d290613cfb565b6120615782386122fb565b6125e690613cfb565b612061578238612299565b6126069195503d8086833e6114648183613d0e565b933861221b565b505050fd5b50346101935780600319360112610193576008546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576005546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576003546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576001546040516001600160a01b039091168152602090f35b5034610193576040366003190112610193576126d0613cbb565b6126d8613ca5565b82549160ff8360081c161592838094612802575b80156127eb575b1561278f5760ff19811660011785558361277e575b5060018060a01b0390816bffffffffffffffffffffffff60a01b93168360025416176002551690600154161760015561274033613e2e565b6127475780f35b61ff001981541681557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a180f35b61ffff191661010117845538612708565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b1580156126f35750600160ff8216146126f3565b50600160ff8216106126ec565b50346101935760e036600319011261019357612829613ca5565b6001600160a01b0390604435908282168203611056576064356001600160401b0381116114925761285e903690600401613d81565b9060a4359182151583036110565760c435938585168503611056576020604496600154166040519788809263ac4ab3fb60e01b82523360048301526000805160206157ff83398151915260248301525afa9586156118235787966128d6575b506128ca61022196613ef2565b60843592600435614d8b565b95506020863d821161290e575b816128f060209383613d0e565b81010312611298576128ca61290761022197613ee5565b96506128bd565b3d91506128e3565b50346101935780600319360112610193576002546040516001600160a01b039091168152602090f35b503461019357604461295036613cd1565b60015460405163ac4ab3fb60e01b81523360048201526000805160206157ff8339815191526024820152929492939260209185919082906001600160a01b03165afa9283156114e6578593613371575b506129ac602493613ef2565b600754604051634a83e9cd60e11b81526004810184905293869185919082906001600160a01b03165afa9283156114e6578593613355575b50600a546040840151606085015160a0860151610100870151151593899391926001600160a01b0391821692909116823b1561149257612a3a60405196879586948594636615984360e11b8652600486016140bf565b03915afa801561147357613342575b506009546040840151606085015160a08601516101008701518994901515936001600160a01b0390811693911690813b1561100557858094612aa16040519788968795869463428d156160e01b8652600486016140bf565b03925af180156110095761332e575b50600c54604085015160608601516001600160a01b039283169290911690823b1561149657612af892849283604051809681958294635ff2138760e01b8452600484016140f2565b03925af180156110095761331a575b506009546020850151604080870151606088015191516306e32f3b60e11b815297949388936001600160a01b039182169385938493612b4e939181169116600485016141d2565b03915afa9384156114735786946132fe575b50612b7a610c4c610c38608087015160e0880151906141fb565b8660018060a01b03600a541660018060a01b036040850151169060608501519160a08601519160808a01519361010088015115159260608c0151151594833b1561144b578795612bee956040519889978896879663b525a2df60e01b8852600488015260c0602488015260c487019061409a565b9360448601526064850152608484015260a483015203915afa8015611009576132ea575b50608086015180612f495750506020828101516001600160a01b0390811687526040808501805183168985015260608087018051848c015242610100808d01919091528801511515918b0191909152600c5491519051925163f612620760e01b8152949385939281169284928392612c8f929116600484016140f2565b03915afa908115611063578891612f17575b5060c08601525b612cba60a08301516080870151614224565b6080860152612cd1608083015160a0870151614224565b60a086015260e085015260095486906001600160a01b0316803b15611014578160405180926378eaac7d60e01b8252818381612d108c60048301614290565b03925af1801561100957612f03575b506007546001600160a01b0316803b1561101457818091602460405180948193634cc8221560e01b83528a60048401525af1801561100957612eef575b5050602081810151604080840151606085015160e0860151600154935163ac4ab3fb60e01b81523360048201526000805160206157ff83398151915260248201526001600160a01b0393841698969195929492841693909283916044918391165afa908115610fe6578b91612e8d575b50916000805160206157df83398151915296612df19492610434612e57989795613ef2565b60018060a01b036020820151169460018060a01b036040830151169660608301519261010081015115159260a08201519260808301519060a08301519060808401519260e060c081870151960151960151966040519a8b9a610140808d528c019061409a565b9860208b015260408a01526060890152608088015260a087015260c086015260e08501526101008401526101208301520390a480f35b939195949290506020843d602011612ee7575b81612ead60209383613d0e565b81010312610fda576000805160206157df83398151915296612e5796610434612ed8612df197613ee5565b93959798505092945096612dcc565b3d9150612ea0565b612ef890613cfb565b611005578538612d5c565b612f0c90613cfb565b611005578538612d1f565b90506020813d602011612f41575b81612f3260209383613d0e565b81010312611056575138612ca1565b3d9150612f25565b612f799060018060a01b036020890151169060408901518a60608b0151151560e08c01519260c08d0151956154c5565b80915061300f575b5050600c54602086810151604080890151905163f612620760e01b81529384926001600160a01b039182169284928392612fc0929116600484016140f2565b03915afa908115611063578891612fdd575b5060c0860152612ca8565b90506020813d602011613007575b81612ff860209383613d0e565b81010312611056575138612fd2565b3d9150612feb565b818113156132d357805b60a08801519160608901511584811592836132c9575b83156132ab575b5050506000146131825760a0880151808210613059575b505050505b8638612f81565b8161306391614283565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b15611298578680946130b46040519788968795869463b931db6d60e01b865260048601614251565b03925af19081156112b057839161316e575b50506130df90611204608089015160a08a0151906141fb565b6130ed816080890151614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b1561100557858094613144604051978896879586946305dfed9960e11b8652600486016140bf565b03925af180156110095761315a575b808061304d565b61316390613cfb565b611298578638613153565b61317790613cfb565b6110145781386130c6565b61318c8183614224565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b15611298578680946131dd60405197889687958694632087829b60e11b865260048601614251565b03925af19081156112b0578391613297575b505061320890611204608089015160a08a0151906141fb565b613216608088015182614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b156110055785809461326d6040519788968795869463428d156160e01b8652600486016140bf565b03925af1801561100957613283575b5050613052565b61328c90613cfb565b61129857863861327c565b6132a090613cfb565b6110145781386131ef565b91925090826132bf575b5050388481613036565b12905083386132b5565b818113935061302f565b9050600160ff1b8114611423578088918203613019565b6132f390613cfb565b611298578638612c12565b6133139194503d8088833e6114648183613d0e565b9238612b60565b61332390613cfb565b611492578438612b07565b61333790613cfb565b611492578438612ab0565b61334e90959195613cfb565b9338612a49565b61336a9193503d8087833e6114d78183613d0e565b91386129e4565b92506020833d6020116133a9575b8161338c60209383613d0e565b81010312611492576129ac6133a2602494613ee5565b93506129a0565b3d915061337f565b50346101935780600319360112610193576009546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576007546040516001600160a01b039091168152602090f35b503461019357806003193601126101935760018060a01b0361342c81835460101c163314613dfc565b8060025416906040519163bf40fac160e01b8084526020918260048601526024600a8187015260449269417373657453746f726560b01b8488015260649085888381875afa978815613bcf578998613b98575b50866bffffffffffffffffffffffff60a01b98168860035416176003556040518181528660048201526009848201526846756e6453746f726560b81b8682015286818481885afa80156138ed5788918b91613b60575b5016886004541617600455604051818152866004820152600c848201526b46756e64696e6753746f726560a01b8682015286818481885afa80156138ed5788918b91613b28575b5016886005541617600555604051818152866004820152600b848201526a4d61726b657453746f726560a81b8682015286818481885afa80156138ed5788918b91613af0575b5016886006541617600655604051818152866004820152600a84820152694f7264657253746f726560b01b8682015286818481885afa80156138ed5788918b91613ab8575b501688600754161760075560405181815286600482015260098482015268506f6f6c53746f726560b81b8682015286818481885afa80156138ed5788918b91613a80575b5016886008541617600855604051818152866004820152600d848201526c506f736974696f6e53746f726560981b8682015286818481885afa80156138ed5788918b91613a48575b5016886009541617600955604051818152866004820152600984820152685269736b53746f726560b81b8682015286818481885afa80156138ed5788918b91613a10575b501688600a541617600a55604051818152866004820152600c848201526b4275794261636b53746f726560a01b8682015286818481885afa80156138ed5788918b916139d8575b501688600b541617600b556040518181528660048201526007848201526646756e64696e6760c81b8682015286818481885afa80156138ed5788918b916139a0575b501688600c541617600c5560405181815286600482015260048482015263141bdbdb60e21b8682015286818481885afa80156138ed5788918b91613968575b501688600d541617600d55604051818152866004820152600484820152630a0f2e8d60e31b8682015286818481885afa80156138ed5788918b91613930575b501688600e541617600e55604051818152866004820152600b848201526a283cba342ab83230ba32b960a91b8682015286818481885afa80156138ed5788918b916138f8575b501688600f541617600f5560405193818552866004860152600d848601526c526566657272616c53746f726560981b8686015286858481845afa9485156138ed57879589918c9161389a575b50966a52656261746553746f726560a81b91600b98168b6010541617601055604051978896879586528860048701528501528301525afa9182156114e6578592613864575b50501690601154161760115580f35b90809250813d8311613893575b61387b8183613d0e565b810103126114965761388c90613ed1565b3880613855565b503d613871565b97968092508891503d83116138e6575b6138b48183613d0e565b810103126138e2576a52656261746553746f726560a81b8795896138d9600b99613ed1565b91985091613810565b8980fd5b503d6138aa565b6040513d8c823e3d90fd5b809250888092503d8311613929575b6139118183613d0e565b810103126138e2576139238891613ed1565b386137c4565b503d613907565b809250888092503d8311613961575b6139498183613d0e565b810103126138e25761395b8891613ed1565b3861377e565b503d61393f565b809250888092503d8311613999575b6139818183613d0e565b810103126138e2576139938891613ed1565b3861373f565b503d613977565b809250888092503d83116139d1575b6139b98183613d0e565b810103126138e2576139cb8891613ed1565b38613700565b503d6139af565b809250888092503d8311613a09575b6139f18183613d0e565b810103126138e257613a038891613ed1565b386136be565b503d6139e7565b809250888092503d8311613a41575b613a298183613d0e565b810103126138e257613a3b8891613ed1565b38613677565b503d613a1f565b809250888092503d8311613a79575b613a618183613d0e565b810103126138e257613a738891613ed1565b38613633565b503d613a57565b809250888092503d8311613ab1575b613a998183613d0e565b810103126138e257613aab8891613ed1565b386135eb565b503d613a8f565b809250888092503d8311613ae9575b613ad18183613d0e565b810103126138e257613ae38891613ed1565b386135a7565b503d613ac7565b809250888092503d8311613b21575b613b098183613d0e565b810103126138e257613b1b8891613ed1565b38613562565b503d613aff565b809250888092503d8311613b59575b613b418183613d0e565b810103126138e257613b538891613ed1565b3861351c565b503d613b37565b809250888092503d8311613b91575b613b798183613d0e565b810103126138e257613b8b8891613ed1565b386134d5565b503d613b6f565b9097508581813d8311613bc8575b613bb08183613d0e565b8101031261160157613bc190613ed1565b963861347f565b503d613ba6565b6040513d8b823e3d90fd5b5034610193578060031936011261019357600d546040516001600160a01b039091168152602090f35b50346101935780600319360112610193575460405160109190911c6001600160a01b03168152602090f35b50346101935780600319360112610193576004546040516001600160a01b039091168152602090f35b5034610193578060031936011261019357600b546040516001600160a01b039091168152602090f35b9050346110145781600319360112611014576011546001600160a01b03168152602090f35b602435906001600160a01b038216820361105657565b600435906001600160a01b038216820361105657565b60609060031901126110565760043590602435906044356001600160a01b03811681036110565790565b6001600160401b03811161157157604052565b90601f801991011681019081106001600160401b0382111761157157604052565b6001600160401b03811161157157601f01601f191660200190565b929192613d5682613d2f565b91613d646040519384613d0e565b829481845281830111611056578281602093846000960137010152565b9080601f8301121561105657816020613d9c93359101613d4a565b90565b9181601f84011215611056578235916001600160401b038311611056576020838186019501011161105657565b9181601f84011215611056578235916001600160401b038311611056576020808501948460051b01011161105657565b15613e0357565b606460405162461bcd60e51b815260206004820152600460248201526310b3b7bb60e11b6044820152fd5b6001600160a01b03818116918215613ea0576000805462010000600160b01b03198116601093841b62010000600160b01b031617909155604080519190921c909216825260208201929092527f53351836099c03ffc3b1727d8abd4b0222afa87d4ed76ae3102d51369ef7f7859190a1565b60405162461bcd60e51b815260206004820152600960248201526810bd32b93796b3b7bb60b91b6044820152606490fd5b51906001600160a01b038216820361105657565b5190811515820361105657565b15613ef957565b60405162461bcd60e51b815260206004820152600e60248201526d21636f6e74726163742d726f6c6560901b6044820152606490fd5b60005b838110613f425750506000910152565b8181015183820152602001613f32565b81601f82011215611056578051613f6881613d2f565b92613f766040519485613d0e565b8184526020828401011161105657613d9c9160208085019101613f2f565b6020818303126110565780516001600160401b03918282116110565701906101c092838382031261105657604051938401848110838211176115715760405282518452613fe360208401613ed1565b6020850152613ff460408401613ed1565b6040850152606083015191821161105657614010918301613f52565b60608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e083015261010061404b818301613ee5565b90830152610120808201519060ff8216820361105657830152610140614072818301613ee5565b90830152610160808201519083015261018080820151908301526101a0809101519082015290565b906020916140b381518092818552858086019101613f2f565b601f01601f1916010190565b929493906060926140e59160018060a01b0316855260806020860152608085019061409a565b9460408401521515910152565b6001600160a01b039091168152604060208201819052613d9c9291019061409a565b6020818303126110565780516001600160401b039182821161105657019061012092838382031261105657604051938401848110838211176115715760405261415c83613ed1565b845261416a60208401613ed1565b6020850152604083015191821161105657614186918301613f52565b604083015261419760608201613ee5565b60608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e0830152610100809101519082015290565b6001600160a01b03918216815291166020820152606060408201819052613d9c9291019061409a565b8181029291811591840414171561420e57565b634e487b7160e01b600052601160045260246000fd5b9190820180921161420e57565b811561423b570490565b634e487b7160e01b600052601260045260246000fd5b94939261427e9160609360018060a01b03809216885216602087015260806040870152608086019061409a565b930152565b9190820391821161420e57565b6020815260018060a01b03808351166020830152602083015116604082015260408201516142cc6101209182606085015261014084019061409a565b92606081015115156080840152608081015160a084015260a081015160c084015260c081015160e084015260e0810151906101009182850152015191015290565b60008190039190600160ff1b811460011661420e5760001983050361420e57565b818102929160008212600160ff1b82141661420e57818405149015171561420e57565b908060209392818452848401376000828201840152601f01601f1916010190565b6001600160a01b03918216815291166020820152606060408201819052613d9c93910191614351565b156143a257565b60405162461bcd60e51b815260206004820152600960248201526810b837b9b4ba34b7b760b91b6044820152606490fd5b9160208181850182865252604084019360408360051b82010194846000925b858410614403575050505050505090565b90919293949596603f198282030184528735601e19843603018112156110565783018681019190356001600160401b0381116110565780360383136110565761445188928392600195614351565b9901940194019295949391906143f2565b6020818303126110565780516001600160401b03918282116110565701906101e0928383820312611056576040519384018481108382111761157157604052825182811161105657816144b6918501613f52565b84526020830151918211611056576144cf918301613f52565b60208301526144e060408201613ed1565b6040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e0830152610100808201519083015261012080820151908301526101408082015190830152610160614546818301613ee5565b90830152610180614558818301613ee5565b908301526101a080820151908301526101c0809101519082015290565b1561457c57565b60405162461bcd60e51b815260206004820152600660248201526521707269636560d01b6044820152606490fd5b156145b157565b60405162461bcd60e51b8152602060048201526008602482015267216d61782d61676560c01b6044820152606490fd5b156145e857565b60405162461bcd60e51b8152602060048201526007602482015266085c185d5cd95960ca1b6044820152606490fd5b1561461e57565b60405162461bcd60e51b815260206004820152600760248201526610b6b0b933b4b760c91b6044820152606490fd5b906146679060409396959496606084526060840191614351565b9460208201520152565b929094916000928515614d8257600954604051632bdc62f560e21b81529490602090869060049082906001600160a01b03165afa8015614d75578190614d3a575b600b546040516374d6f48760e11b81529650602090879060049082906001600160a01b03165afa958615611009578296614d06575b506008546040516374d6f48760e11b81526001600160a01b0390911690602081600481855afa908115611566578491614cd4575b5089670de0b6b3a7640000810204670de0b6b3a764000003614cc05783926001600160a01b038616151580614cb7575b614c95575b50601054604051634a9fefc760e01b81526001600160a01b038d8116600483015290911695906020816024818a5afa908115611473578691614c5b575b5085968c60018060a01b0383169182614bb2575b50886147ba88670de0b6b3a76400006147bf9402614283565b614283565b809b8015600014614b995750506147e6879b8c955b80614b8057506147ba899d8e92614283565b94803b1561144b5760405163de900ab960e01b81526001600160a01b038b166004820152670de0b6b3a76400008d0460248201529088908290604490829084905af1801561106357614b6d575b50600b546001600160a01b0316803b1561144b5760405163e7904f1960e01b81526001600160a01b038b166004820152670de0b6b3a7640000860460248201529088908290604490829084905af1801561106357908891614b59575b5050614adc575b506004805460025460405163bf40fac160e01b815260209381018490526008602482015267747265617375727960c01b60448201526001600160a01b03928316939092909183916064918391165afa908115611823578791614aa2575b50813b156112985760405163078d3b7960e01b81526001600160a01b038a81166004830152919091166024820152670de0b6b3a7640000850460448201529086908290606490829084905af1801561147357908691614a8e575b50506004546001600160a01b031690813b156110055760405163078d3b7960e01b81526001600160a01b038981166004830152919091166024820152670de0b6b3a7640000850460448201529085908290606490829084905af180156114e657908591614a7a575b5050604051978897610100808a5289016149ce9161409a565b9a670de0b6b3a764000002670de0b6b3a764000090046020890152670de0b6b3a764000090046040880152670de0b6b3a764000090046060870152670de0b6b3a764000090046080860152670de0b6b3a7640000900460a085015260c0840152670de0b6b3a7640000900460e0830152600160a01b600190031694600160a01b600190031693037fefec25506ec34f1da5d044e02e9e6af1270aadcf8747bb65b34bc283ad1e76e791a4565b614a8390613cfb565b6114965783386149b5565b614a9790613cfb565b61149257843861494d565b90506020813d602011614ad4575b81614abd60209383613d0e565b8101031261129857614ace90613ed1565b386148f3565b3d9150614ab0565b6011546001600160a01b0316803b15611298576040516346f1a43360e11b81526001600160a01b0392831660048201529189166024830152670de0b6b3a76400008804604483015286908290606490829084905af1801561147357908691614b45575b50614896565b614b4e90613cfb565b611492578438614b3f565b614b6290613cfb565b61129857863861488f565b614b7990979197613cfb565b9538614833565b612710614b906147ba92846141fb565b049d8e92614283565b614ba9612710916147e6936141fb565b049b8c956147d4565b6024929394959697989950602091506040519283809263f8374de160e01b82528660048301525afa90811561106357908d918991614c1e575b50816147ba89612710614c136147bf95670de0b6b3a76400009e9d9c9b9a9998978f026141fb565b049b505050906147a1565b9150506020813d602011614c53575b81614c3a60209383613d0e565b8101031261144b57518c90670de0b6b3a7640000614beb565b3d9150614c2d565b90506020813d602011614c8d575b81614c7660209383613d0e565b8101031261100557614c8790613ed1565b3861478d565b3d9150614c69565b612710919350614caf90670de0b6b3a76400008c026141fb565b049138614750565b5080151561474b565b634e487b7160e01b84526011600452602484fd5b90506020813d602011614cfe575b81614cef60209383613d0e565b8101031261149657513861471b565b3d9150614ce2565b9095506020813d602011614d32575b81614d2260209383613d0e565b81010312611014575194386146e7565b3d9150614d15565b50909192936020813d602011614d6d575b81614d5860209383613d0e565b810103126110145790600494939291516146b2565b3d9150614d4b565b50604051903d90823e3d90fd5b50505050505050565b939492919095600093861561548757600954604051632bdc62f560e21b815290602090829060049082906001600160a01b03165afa908115611473578691615455575b50600b546040516374d6f48760e11b808252909791602090899060049082906001600160a01b03165afa978815611009578298615421575b506008546040519182526001600160a01b031691602082600481865afa918215614d755781926153ed575b508a670de0b6b3a7640000810204670de0b6b3a7640000036153d9579283906001600160a01b0387161515806153d0575b6153ae575b50601054604051634a9fefc760e01b81526001600160a01b038e8116600483015290911696906020816024818b5afa9081156112b0578391615374575b5082978d60018060a01b03831691826152c1575b50896147ba89670de0b6b3a7640000614ed19402614283565b809c80156000146152a8575050614ef8849c8d965b8061528f57506147ba869e8f92614283565b95803b156114925760405163de900ab960e01b81526001600160a01b038c166004820152670de0b6b3a76400008e0460248201529085908290604490829084905af180156114e65761527c575b50600b546001600160a01b0316803b156114925760405163e7904f1960e01b81526001600160a01b038c166004820152670de0b6b3a7640000870460248201529085908290604490829084905af180156114e657908591615268575b50506151eb575b506004805460025460405163bf40fac160e01b815260209381018490526008602482015267747265617375727960c01b6044820152926001600160a01b0392831692909184916064918391165afa9182156115665784926151af575b50803b156114965760405163078d3b7960e01b81526001600160a01b038b81166004830152929092166024830152670de0b6b3a76400008604604483015283908290606490829084905af180156112b05790839161519b575b50506004546001600160a01b0316803b156120615760405163078d3b7960e01b81526001600160a01b038a81166004830152929092166024830152670de0b6b3a76400008604604483015282908290606490829084905af1801561100957615187575b5050604051978897610100808a5289016150d99161409a565b9a670de0b6b3a764000002670de0b6b3a764000090046020890152670de0b6b3a764000090046040880152670de0b6b3a764000090046060870152670de0b6b3a764000090046080860152670de0b6b3a7640000900460a0850152151560c0840152670de0b6b3a7640000900460e0830152600160a01b600190031694600160a01b600190031693037fefec25506ec34f1da5d044e02e9e6af1270aadcf8747bb65b34bc283ad1e76e791a4565b6151918291613cfb565b61019357806150c0565b6151a490613cfb565b61101457813861505d565b9091506020813d6020116151e3575b816151cb60209383613d0e565b81010312611496576151dc90613ed1565b9038615004565b3d91506151be565b6011546001600160a01b0316803b15611496576040516346f1a43360e11b81526001600160a01b039283166004820152918a166024830152670de0b6b3a76400008904604483015283908290606490829084905af180156112b057908391615254575b50614fa8565b61525d90613cfb565b61101457813861524e565b61527190613cfb565b611496578338614fa1565b61528890949194613cfb565b9238614f45565b61271061529f6147ba92846141fb565b049e8f92614283565b6152b861271091614ef8936141fb565b049c8d96614ee6565b602492939495969798999a50602091506040519283809263f8374de160e01b82528660048301525afa9081156114e657908e918691615337575b50816147ba8a61271061532c614ed195670de0b6b3a76400009f9e9d9c9b9a999897670de0b6b3a7640000026141fb565b049c50505090614eb8565b9150506020813d60201161536c575b8161535360209383613d0e565b8101031261149257518d90670de0b6b3a76400006152fb565b3d9150615346565b90506020813d6020116153a6575b8161538f60209383613d0e565b81010312612061576153a090613ed1565b38614ea4565b3d9150615382565b6127109194506153c890670de0b6b3a76400008d026141fb565b049238614e67565b50801515614e62565b634e487b7160e01b81526011600452602490fd5b9091506020813d602011615419575b8161540960209383613d0e565b8101031261101457519038614e31565b3d91506153fc565b9097506020813d60201161544d575b8161543d60209383613d0e565b8101031261101457519638614e06565b3d9150615430565b90506020813d60201161547f575b8161547060209383613d0e565b81010312611005575138614dce565b3d9150615463565b5050505050505050565b8181039291600013801582851316918412161761420e57565b811561423b57600160ff1b811460001983141661420e570590565b94939695929091968115801561560d575b8015615605575b6155f5579160209161553b93896000146155df576155076155018261550c94615491565b8861432e565b6154aa565b955b600c5460405163f612620760e01b81529485936001600160a01b03909216928492839291600484016140f2565b03915afa9081156155d3576000916155a0575b509161556861556e9269021e19e0c9bab240000094615491565b9061432e565b0580936000146155855761558191615491565b9190565b8101906000848312911290801582169115161761420e579190565b906020823d82116155cb575b816155b960209383613d0e565b8101031261019357505161556861554e565b3d91506155ac565b6040513d6000823e3d90fd5b6155076155016155ef9383615491565b9561550e565b5050505050509050600090600090565b5084156154dd565b5080156154d6565b600e54604080516396834ad360e01b815260048082019490945293929091602491906080908690849082906001600160a01b03165afa9485156157d357600095615733575b506000855160070b1315615701578285015160030b92836012019384126001166156ed57600084126156bd5750604d83116156aa5750506156a4606091600a0a845160070b6141fb565b92015190565b601190634e487b7160e01b600052526000fd5b6064926020600c92519362461bcd60e51b85528401528201526b021696e76616c69642d6578760a41b6044820152fd5b50601190634e487b7160e01b600052526000fd5b600e606492602085519362461bcd60e51b85528401528201526d21696e76616c69642d707269636560901b6044820152fd5b6080959195813d82116157cb575b8161574e60809383613d0e565b81010312611014578351916001600160401b0360808401818111858210176157b957865282518060070b81036120615784526020830151908116810361101457602084015284820151908160030b82036101935750906060918584015201516060820152933861565a565b634e487b7160e01b8352604189528583fd5b3d9150615741565b83513d6000823e3d90fdfe3a1062142d0d194eaf2928092e53c3f84f5602268f2b82effd44010aff82cb90a66b7a3e6b19d24ccb6f717fc232a1bb0278a7f83f8e2211835fc4ed0fe69f19a264697066735822122081f86476a896ed9a02a87190b3ea3c665bd96982816930959726b11b4ae489f464736f6c63430008110033

Deployed Bytecode

0x608080604052600436101561001357600080fd5b600090813560e01c9081630278198d14613c8057508063032e73e314613c57578063077d17f814613c2e57806312d43a5114613c0357806316f0115b14613bda5780631c4695f4146134035780632ac38dbd146133da5780633157d39d146133b15780633f34b2b21461293f5780634242bac01461291657806346ffceec1461280f578063485cc955146126b65780634a4a7b041461268d578063597a0e36146126645780635f7ddaaa1461263b57806360465d111461261257806362ef7229146121835780636c36609414611e6c5780637c4283bc14611e4f578063835f165114611dde578063861b6a9014611db55780639d8e217714611d92578063a5a06d1d1461188a578063a9aa28e114610276578063b8d2c6931461024d578063cb4c86b714610224578063cfad57a2146101e8578063d4dd357e146101bf578063f4b88717146101965763f98d06f01461016b57600080fd5b34610193578060031936011261019357600e546040516001600160a01b039091168152602090f35b80fd5b5034610193578060031936011261019357600f546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576010546040516001600160a01b039091168152602090f35b503461019357602036600319011261019357610221610205613cbb565b61021c60018060a01b03845460101c163314613dfc565b613e2e565b80f35b5034610193578060031936011261019357600c546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576006546040516001600160a01b039091168152602090f35b50346101935761028536613cd1565b60015460405163ac4ab3fb60e01b81523360048201526000805160206157ff8339815191526024820152929392906001600160a01b0316602082604481845afa91821561147357869261184a575b506102df602492613ef2565b600754604051634a83e9cd60e11b81526004810186905292879184919082906001600160a01b03165afa91821561147357869261182e575b506009546020830151604080850151606086015191516306e32f3b60e11b8152938a9385936001600160a01b03928316938593849361035e939282169116600485016141d2565b03915afa908115611823578791611809575b50608081015160a0840151919082811115611803575081955b610394878094614283565b9689948a90610140880151156117d0575b6103c16103b68460e08b01516141fb565b60a08a015190614231565b9060448d60018060a01b0360208c015116928b6020606060018060a01b03604084015116920151926040519586809263ac4ab3fb60e01b82523360048301526000805160206157ff83398151915260248301525afa9485156112b0578e94879496611783575b5061043461043a96613ef2565b89614671565b6101408801511561177b57945b60095460408901516060808b0151908801518f93901515926001600160a01b039081169116803b15611492578492838993610498604051978896879586946305dfed9960e11b8652600486016140bf565b03925af1801561100957611767575b50600c5460408a015160608b01516001600160a01b039283169290911690823b15611496576104ef92849283604051809681958294635ff2138760e01b8452600484016140f2565b03925af180156110095761174f575b506105308c8560018060a01b0360408d0151169160608d01519060608b0151151560e08c01519260c08d0151956154c5565b94909283916105516105468260a08c01516141fb565b60808b015190614231565b9461055f60a08b015161430d565b1261171f57505050905061057660a086015161430d565b60a08601519660808701518360808901525b600a5460408c01516001600160a01b039182169116813b1561100557859160448392604051948593849263e3af01bb60e01b845260048401528960248401525af19081156114e657859161170b575b505060808801516116a95760095460208c015160408d015160608e01516001600160a01b039182169392821692909116803b1561144b57610632938880946040519687958694859363e512766b60e01b8552600485016141d2565b03925af19081156114e6578591611695575b50505b83831215611605576106588361430d565b600d5460208d015160408e015160608f01516001600160a01b039182169392821692909116803b156116015784938980946106a96040519788968795869463b931db6d60e01b865260048601614251565b03925af1801561147357849187916115ea575b50506106c791614224565b8981106115d4575b505b6007546001600160a01b0316803b1561149257848091602460405180948193634cc8221560e01b83528d60048401525af19081156114e65785916115c0575b505060045460408c015160208d01516001600160a01b03908116979181169216803b156112985760405163078d3b7960e01b81526001600160a01b039384166004820152979092166024880152604487015284908690606490829084905af19384156115b4578b958f95611590575b5050917f5a3ca482b3cc533b228c98d56dbb9e80ed3986e661e13396977a90a594476b8c95916101a0949360018060a01b036020880151169960018060a01b036040890151169b61010060608a015199015115159660a08301519060808401519260c060e0860151950151956108006040519d8d8f9e8f908152019061409a565b9a60208d015260408c015260608b015260808a015260a089015260c088015260e08701526101008601526101208501526101408401528d6101608401526101808301520390a46101408201511580611587575b61085b578580f35b60018060a01b036020830151169160608101519160018060a01b03604083015116956108a261010084015115159360a06108998460e08401516141fb565b91015190614231565b9160405194856101c08101106001600160401b036101c088011117611571578a986020976101c088016040528a88528888015260408701526060860152608085015260a08401528560c084015260e083015261010082015283610120820152836101408201524261016082015283610180820152836101a082015260018060a01b036007541660405180958180946367637b9160e01b82528660048301528051602483015260018060a01b038782015116604483015260018060a01b0360408201511660648301526101a061098860608301516101c060848601526101e485019061409a565b91608081015160a485015260a081015160c485015260c081015160e485015260e0810151610104850152610100810151151561012485015260ff6101208201511661014485015261014081015115156101648501526101608101516101848501526101808101516101a485015201516101c483015203925af1908115611566578491611531575b60015460405163ac4ab3fb60e01b81523360048201526000805160206157ff83398151915260248201529350602090849060449082906001600160a01b03165afa9283156114e65785936114f1575b50610a6a602493613ef2565b600754604051634a83e9cd60e11b81526004810184905293869185919082906001600160a01b03165afa9283156114e65785936114c2575b50600a546040840151606085015160a08601516101008701518994901515936001600160a01b0390811693911690813b15611005578593610af960405196879586948594636615984360e11b8652600486016140bf565b03915afa8015611009576114ae575b506009546040850151606086015160a08701516101008801511515936001600160a01b03938416939192911690813b1561100557858094610b5f6040519788968795869463428d156160e01b8652600486016140bf565b03925af180156110095761149a575b50600c54604085015160608601516001600160a01b039283169290911690823b1561149657610bb692849283604051809681958294635ff2138760e01b8452600484016140f2565b03925af180156110095761147e575b506009546020850151604080870151606088015191516306e32f3b60e11b815297949388936001600160a01b039182169385938493610c0c939181169116600485016141d2565b03915afa93841561147357869461144f575b50610c65610c4c610c38608087015160e0880151906141fb565b610c468860a08601516141fb565b90614224565b610c5f608087015160a085015190614224565b90614231565b8660018060a01b03600a541660018060a01b036040850151169060608501519160a08601519160808a01519361010088015115159260608c0151151594833b1561144b578795610cd9956040519889978896879663b525a2df60e01b8852600488015260c0602488015260c487019061409a565b9360448601526064850152608484015260a483015203915afa801561100957611437575b5060808601518061106e5750506020828101516001600160a01b0390811687526040808501805183168985015260608087018051848c015242610100808d01919091528801511515918b0191909152600c5491519051925163f612620760e01b8152949385939281169284928392610d7a929116600484016140f2565b03915afa90811561106357889161102c575b5060c08601525b610da560a08301516080870151614224565b6080860152610dbc608083015160a0870151614224565b60a086015260e085015260095486906001600160a01b0316803b15611014578160405180926378eaac7d60e01b8252818381610dfb8c60048301614290565b03925af1801561100957611018575b506007546001600160a01b0316803b1561101457818091602460405180948193634cc8221560e01b83528a60048401525af1801561100957610ff1575b5050602081810151604080840151606085015160e0860151600154935163ac4ab3fb60e01b81523360048201526000805160206157ff83398151915260248201526001600160a01b0393841698969195929492841693909283916044918391165afa908115610fe6578b91610f80575b50916000805160206157df83398151915296610edc9492610434610f44989795613ef2565b60018060a01b036020820151169460018060a01b036040830151169660608301519261010081015115159260a08201519260808301519060a08301519060808401519260e060c081870151960151960151966040519a8b9a6101408c526101408c019061409a565b9860208b015260408a01526060890152608088015260a087015260c086015260e08501526101008401526101208301520390a438808080808580f35b939195949290506020843d602011610fde575b81610fa060209383613d0e565b81010312610fda576000805160206157df83398151915296610f4496610434610fcb610edc97613ee5565b93959798505092945096610eb7565b8a80fd5b3d9150610f93565b6040513d8d823e3d90fd5b610ffa90613cfb565b611005578538610e47565b8580fd5b6040513d84823e3d90fd5b5080fd5b61102190613cfb565b611005578538610e0a565b90506020813d60201161105b575b8161104760209383613d0e565b81010312611056575138610d8c565b600080fd5b3d915061103a565b6040513d8a823e3d90fd5b61109e9060018060a01b036020890151169060408901518a60608b0151151560e08c01519260c08d0151956154c5565b809150611134575b5050600c54602086810151604080890151905163f612620760e01b81529384926001600160a01b0391821692849283926110e5929116600484016140f2565b03915afa908115611063578891611102575b5060c0860152610d93565b90506020813d60201161112c575b8161111d60209383613d0e565b810103126110565751386110f7565b3d9150611110565b8181131561140c57805b60a0880151916060890151158481159283611402575b83156113e4575b5050506000146112bb5760a088015180821061117e575b505050505b86386110a6565b8161118891614283565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b15611298578680946111d96040519788968795869463b931db6d60e01b865260048601614251565b03925af19081156112b057839161129c575b505061120990611204608089015160a08a0151906141fb565b614231565b611217816080890151614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b156110055785809461126e604051978896879586946305dfed9960e11b8652600486016140bf565b03925af1801561100957611284575b8080611172565b61128d90613cfb565b61129857863861127d565b8680fd5b6112a590613cfb565b6110145781386111eb565b6040513d85823e3d90fd5b6112c58183614224565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b156112985786809461131660405197889687958694632087829b60e11b865260048601614251565b03925af19081156112b05783916113d0575b505061134190611204608089015160a08a0151906141fb565b61134f608088015182614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b15611005578580946113a66040519788968795869463428d156160e01b8652600486016140bf565b03925af18015611009576113bc575b5050611177565b6113c590613cfb565b6112985786386113b5565b6113d990613cfb565b611014578138611328565b91925090826113f8575b505038848161115b565b12905083386113ee565b8181139350611154565b9050600160ff1b811461142357808891820361113e565b634e487b7160e01b88526011600452602488fd5b61144090613cfb565b611298578638610cfd565b8780fd5b61146c9194503d8088833e6114648183613d0e565b810190614114565b9238610c1e565b6040513d88823e3d90fd5b61148790613cfb565b611492578438610bc5565b8480fd5b8380fd5b6114a390613cfb565b611492578438610b6e565b6114b790613cfb565b611492578438610b08565b6114df9193503d8087833e6114d78183613d0e565b810190613f94565b9138610aa2565b6040513d87823e3d90fd5b92506020833d602011611529575b8161150c60209383613d0e565b8101031261149257610a6a611522602494613ee5565b9350610a5e565b3d91506114ff565b90506020823d60201161155e575b8161154c60209383613d0e565b81010312611056576044915190610a0f565b3d915061153f565b6040513d86823e3d90fd5b634e487b7160e01b600052604160045260246000fd5b50831515610853565b909294506115a091939550613cfb565b6115b057918b9189938e3861077f565b8c80fd5b604051903d90823e3d90fd5b6115c990613cfb565b611496578338610710565b94610c466115e392968b614283565b93386106cf565b6115f5919250613cfb565b611492578285386106bc565b8880fd5b600d5460208c015160408d015160608e01519397936001600160a01b039182169392821692909116803b1561144b578693888094611659604051978896879586946309a599fb60e31b865260048601614251565b03925af19081156114e6578591611681575b505061167b90610c46838b614283565b936106d1565b61168a90613cfb565b61149657833861166b565b61169e90613cfb565b611496578338610644565b6009546001600160a01b0316803b15611492576040516378eaac7d60e01b815290859082908183816116de8f60048301614290565b03925af19081156114e65785916116f7575b5050610647565b61170090613cfb565b6114965783386116f0565b61171490613cfb565b6114965783386105d7565b611745906117368660a08c9d9697989d0151614283565b60a08b015260808a0151614283565b6080890152610588565b61175890613cfb565b611763578b386104fe565b8b80fd5b61177090613cfb565b611763578b386104a7565b508a94610447565b9350935093506020823d6020116117c8575b816117a260209383613d0e565b810103126117c45761043a938d936104346117bd8895613ee5565b9650610427565b8f80fd5b3d9150611795565b9550506117ef6117e48260808901516141fb565b60a088015190614231565b6117fd816080890151614283565b956103a5565b95610389565b61181d91503d8089833e6114648183613d0e565b38610370565b6040513d89823e3d90fd5b6118439192503d8088833e6114d78183613d0e565b9038610317565b91506020823d602011611882575b8161186560209383613d0e565b81010312611005576102df61187b602493613ee5565b92506102d3565b3d9150611858565b5034610193576080366003190112610193576118a4613cbb565b6001600160401b0390602435828111611496576118c5903690600401613d9f565b919092606435908111611492576118e0903690600401613dcc565b600754604051637699d2c160e11b815292939290602090829060049082906001600160a01b03165afa8015611823578790611d57575b6119219150156145e1565b60065460405163349f642f60e11b81526020600482015290879082906001600160a01b03168180611956602482018b8d614351565b03915afa908115611823578791611d35575b506009546040516306e32f3b60e11b81529490889086906001600160a01b0316818061199a8b8d8b3360048601614372565b03915afa948515611063578895611d19575b506119bc6080860151151561439b565b6119cd60443560a087015111614617565b6119dd60443560a0870151614283565b926080860151670de0b6b3a7640000908082029082820403611d055785611a0391614231565b6060850151828102928184041490151715611d055711611cd057600f5489926001600160a01b0390911691823b1561149657611a58928492836040518096819582946382f2d25960e01b8452600484016143d3565b03925af1801561100957611cbc575b5050611a97611aa082610120611a84610140611aca960151615615565b611a918296921515614575565b42614283565b910151116145aa565b606085015115159060e086015160808701519160c088015193611ac4368b8d613d4a565b886154c5565b50868112611be9575b5060a083015260095485906001600160a01b0316803b15611014578160405180926378eaac7d60e01b8252818381611b0e8a60048301614290565b03925af1801561100957611bd5575b506004546001600160a01b0316803b156110145760405163078d3b7960e01b81526001600160a01b038416600482015233602482015260448035908201529082908290606490829084905af1801561100957611bc1575b505060a07f0f449301999d3383602e2a69160bbb040a065132cd68168def96131d8b9946a392015190611bbb60405192839260018060a01b0316963396604435918561464d565b0390a380f35b611bca90613cfb565b611492578438611b74565b611bde90613cfb565b611492578438611b1d565b611bf29061430d565b600954604051630d61264760e31b815290602090829060049082906001600160a01b03165afa908115611063578891611c8a575b50612710908103818111611c7657611c3e90846141fb565b041115611c4b5738611ad3565b606460405162461bcd60e51b8152602060048201526004602482015263085d5c1b60e21b6044820152fd5b634e487b7160e01b89526011600452602489fd5b90506020813d602011611cb4575b81611ca560209383613d0e565b81010312611056575138611c26565b3d9150611c98565b611cc590613cfb565b611298578638611a67565b60405162461bcd60e51b815260206004820152600d60248201526c216d61782d6c6576657261676560981b6044820152606490fd5b634e487b7160e01b8b52601160045260248bfd5b611d2e9195503d808a833e6114648183613d0e565b93386119ac565b611d5191503d8089833e611d498183613d0e565b810190614462565b38611968565b506020813d602011611d8a575b81611d7160209383613d0e565b8101031261129857611d8561192191613ee5565b611916565b3d9150611d64565b50346101935780600319360112610193576020604051670de0b6b3a76400008152f35b5034610193578060031936011261019357600a546040516001600160a01b039091168152602090f35b50346101935760e036600319011261019357611df8613cbb565b90602435906001600160401b0382116101935750611e1a903690600401613d81565b60443591821515830361105657604092611e439260c4359260a4359260843592606435926154c5565b82519182526020820152f35b503461019357806003193601126101935760206040516127108152f35b50606036600319011261019357611e81613cbb565b6024356001600160401b03811161206157611ea0903690600401613d9f565b6044359260018060a01b039160046020846007541660405192838092637699d2c160e11b82525afa8015611823578790612149575b611ee09150156145e1565b849280600954168760405180926306e32f3b60e11b82528180611f09888c8b3360048601614372565b03915afa90811561106357889161212f575b506080810194611f2d8651151561439b565b888386169889156000146120c25750905034948360045416803b156120615760405163e4652f4960e01b81526001600160a01b03929092166004830152336024830152604482018790528290829060649082908a905af18015611009576120ae575b50505b611f9d841515614617565b60a0810194611fad858751614224565b865251670de0b6b3a764000090808202908282040361209a578651611fd191614231565b1061206557879160095416803b15612061576040516378eaac7d60e01b815291839183918290849082906120089060048301614290565b03925af180156110095761204d575b5050611bbb7f69dea4780434a9e7bcd91f9c264463d2db6f4f8088762fd4b51b944b57908e78935160405193849333978561464d565b61205690613cfb565b611005578538612017565b8280fd5b60405162461bcd60e51b815260206004820152600d60248201526c216d696e2d6c6576657261676560981b6044820152606490fd5b634e487b7160e01b8a52601160045260248afd5b6120b790613cfb565b61144b578738611f8f565b909195846004541691823b156114965760405163e4652f4960e01b81526001600160a01b0392909216600483015233602483015260448201529082908290606490829084905af180156110095761211b575b5050611f92565b61212490613cfb565b61144b578738612114565b61214391503d808a833e6114648183613d0e565b38611f1b565b506020813d821161217b575b8161216260209383613d0e565b8101031261129857612176611ee091613ee5565b611ed5565b3d9150612155565b5034610193576060366003190112610193578061219e613cbb565b6001600160401b0360243581811161260d576121be903690600401613d9f565b939091604435908111611014576121d9903690600401613dcc565b6009546040516306e32f3b60e11b81529392906001600160a01b03168385806122088b8a8c3360048601614372565b0381845afa9485156115665784956125f1575b5061222b6080860151151561439b565b60808501516060860151151590823b156110055761227c928a878b8b948296604051988997889687956305dfed9960e11b875260018060a01b03166004870152608060248701526084860191614351565b916044840152606483015203925af19081156115665784916125dd575b5050600c546001600160a01b0316803b156114965760408051635ff2138760e01b81526001600160a01b0389166004820152602481019190915290849082908183816122e9604482018f8e614351565b03925af19081156115665784916125c9575b5050600f546001600160a01b031691823b1561149657612334928492836040518096819582946382f2d25960e01b8452600484016143d3565b03925af18015611009576125b5575b505060065460405163349f642f60e11b8152602060048201529390869085906001600160a01b0316818061237b602482018b8a614351565b03915afa93841561147357611a97946123b491889161259b575b506101206123a7610140830151615615565b611a918299921515614575565b856123dc6060840151151560e08501516080860151908860c088015193611ac4368d8c613d4a565b5012612566576009548693906001600160a01b0316803b156114925784604051809263e512766b60e01b825281838161241b8d898b3360048601614372565b03925af19081156114e6578591612552575b505060045460a0840180519094916001600160a01b0316803b156112985760405163078d3b7960e01b81526001600160a01b0386166004820152336024820152604481019290925286908290606490829084905af190811561147357869161253e575b50507f5a3ca482b3cc533b228c98d56dbb9e80ed3986e661e13396977a90a594476b8c936060820151159660808301519151906124e460c060e0860151950151956040519b8c6101a08091528d0191614351565b9860208b01528260408b01528160608b015260808a015260a089015260c088015260e08701526101008601528261012086015282610140860152826101608601528261018086015260018060a01b0316938033940390a480f35b61254790613cfb565b611492578438612490565b61255b90613cfb565b61149657833861242d565b60405162461bcd60e51b815260206004820152600d60248201526c21706e6c2d706f73697469766560981b6044820152606490fd5b6125af91503d808a833e611d498183613d0e565b38612395565b6125be90613cfb565b611492578438612343565b6125d290613cfb565b6120615782386122fb565b6125e690613cfb565b612061578238612299565b6126069195503d8086833e6114648183613d0e565b933861221b565b505050fd5b50346101935780600319360112610193576008546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576005546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576003546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576001546040516001600160a01b039091168152602090f35b5034610193576040366003190112610193576126d0613cbb565b6126d8613ca5565b82549160ff8360081c161592838094612802575b80156127eb575b1561278f5760ff19811660011785558361277e575b5060018060a01b0390816bffffffffffffffffffffffff60a01b93168360025416176002551690600154161760015561274033613e2e565b6127475780f35b61ff001981541681557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a180f35b61ffff191661010117845538612708565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b1580156126f35750600160ff8216146126f3565b50600160ff8216106126ec565b50346101935760e036600319011261019357612829613ca5565b6001600160a01b0390604435908282168203611056576064356001600160401b0381116114925761285e903690600401613d81565b9060a4359182151583036110565760c435938585168503611056576020604496600154166040519788809263ac4ab3fb60e01b82523360048301526000805160206157ff83398151915260248301525afa9586156118235787966128d6575b506128ca61022196613ef2565b60843592600435614d8b565b95506020863d821161290e575b816128f060209383613d0e565b81010312611298576128ca61290761022197613ee5565b96506128bd565b3d91506128e3565b50346101935780600319360112610193576002546040516001600160a01b039091168152602090f35b503461019357604461295036613cd1565b60015460405163ac4ab3fb60e01b81523360048201526000805160206157ff8339815191526024820152929492939260209185919082906001600160a01b03165afa9283156114e6578593613371575b506129ac602493613ef2565b600754604051634a83e9cd60e11b81526004810184905293869185919082906001600160a01b03165afa9283156114e6578593613355575b50600a546040840151606085015160a0860151610100870151151593899391926001600160a01b0391821692909116823b1561149257612a3a60405196879586948594636615984360e11b8652600486016140bf565b03915afa801561147357613342575b506009546040840151606085015160a08601516101008701518994901515936001600160a01b0390811693911690813b1561100557858094612aa16040519788968795869463428d156160e01b8652600486016140bf565b03925af180156110095761332e575b50600c54604085015160608601516001600160a01b039283169290911690823b1561149657612af892849283604051809681958294635ff2138760e01b8452600484016140f2565b03925af180156110095761331a575b506009546020850151604080870151606088015191516306e32f3b60e11b815297949388936001600160a01b039182169385938493612b4e939181169116600485016141d2565b03915afa9384156114735786946132fe575b50612b7a610c4c610c38608087015160e0880151906141fb565b8660018060a01b03600a541660018060a01b036040850151169060608501519160a08601519160808a01519361010088015115159260608c0151151594833b1561144b578795612bee956040519889978896879663b525a2df60e01b8852600488015260c0602488015260c487019061409a565b9360448601526064850152608484015260a483015203915afa8015611009576132ea575b50608086015180612f495750506020828101516001600160a01b0390811687526040808501805183168985015260608087018051848c015242610100808d01919091528801511515918b0191909152600c5491519051925163f612620760e01b8152949385939281169284928392612c8f929116600484016140f2565b03915afa908115611063578891612f17575b5060c08601525b612cba60a08301516080870151614224565b6080860152612cd1608083015160a0870151614224565b60a086015260e085015260095486906001600160a01b0316803b15611014578160405180926378eaac7d60e01b8252818381612d108c60048301614290565b03925af1801561100957612f03575b506007546001600160a01b0316803b1561101457818091602460405180948193634cc8221560e01b83528a60048401525af1801561100957612eef575b5050602081810151604080840151606085015160e0860151600154935163ac4ab3fb60e01b81523360048201526000805160206157ff83398151915260248201526001600160a01b0393841698969195929492841693909283916044918391165afa908115610fe6578b91612e8d575b50916000805160206157df83398151915296612df19492610434612e57989795613ef2565b60018060a01b036020820151169460018060a01b036040830151169660608301519261010081015115159260a08201519260808301519060a08301519060808401519260e060c081870151960151960151966040519a8b9a610140808d528c019061409a565b9860208b015260408a01526060890152608088015260a087015260c086015260e08501526101008401526101208301520390a480f35b939195949290506020843d602011612ee7575b81612ead60209383613d0e565b81010312610fda576000805160206157df83398151915296612e5796610434612ed8612df197613ee5565b93959798505092945096612dcc565b3d9150612ea0565b612ef890613cfb565b611005578538612d5c565b612f0c90613cfb565b611005578538612d1f565b90506020813d602011612f41575b81612f3260209383613d0e565b81010312611056575138612ca1565b3d9150612f25565b612f799060018060a01b036020890151169060408901518a60608b0151151560e08c01519260c08d0151956154c5565b80915061300f575b5050600c54602086810151604080890151905163f612620760e01b81529384926001600160a01b039182169284928392612fc0929116600484016140f2565b03915afa908115611063578891612fdd575b5060c0860152612ca8565b90506020813d602011613007575b81612ff860209383613d0e565b81010312611056575138612fd2565b3d9150612feb565b818113156132d357805b60a08801519160608901511584811592836132c9575b83156132ab575b5050506000146131825760a0880151808210613059575b505050505b8638612f81565b8161306391614283565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b15611298578680946130b46040519788968795869463b931db6d60e01b865260048601614251565b03925af19081156112b057839161316e575b50506130df90611204608089015160a08a0151906141fb565b6130ed816080890151614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b1561100557858094613144604051978896879586946305dfed9960e11b8652600486016140bf565b03925af180156110095761315a575b808061304d565b61316390613cfb565b611298578638613153565b61317790613cfb565b6110145781386130c6565b61318c8183614224565b60a0890152600d54885160208a015160408b01516001600160a01b039283169390929081169116813b15611298578680946131dd60405197889687958694632087829b60e11b865260048601614251565b03925af19081156112b0578391613297575b505061320890611204608089015160a08a0151906141fb565b613216608088015182614283565b60808801919091526009546020880151604089015160608a01511515936001600160a01b039283169390921690813b156110055785809461326d6040519788968795869463428d156160e01b8652600486016140bf565b03925af1801561100957613283575b5050613052565b61328c90613cfb565b61129857863861327c565b6132a090613cfb565b6110145781386131ef565b91925090826132bf575b5050388481613036565b12905083386132b5565b818113935061302f565b9050600160ff1b8114611423578088918203613019565b6132f390613cfb565b611298578638612c12565b6133139194503d8088833e6114648183613d0e565b9238612b60565b61332390613cfb565b611492578438612b07565b61333790613cfb565b611492578438612ab0565b61334e90959195613cfb565b9338612a49565b61336a9193503d8087833e6114d78183613d0e565b91386129e4565b92506020833d6020116133a9575b8161338c60209383613d0e565b81010312611492576129ac6133a2602494613ee5565b93506129a0565b3d915061337f565b50346101935780600319360112610193576009546040516001600160a01b039091168152602090f35b50346101935780600319360112610193576007546040516001600160a01b039091168152602090f35b503461019357806003193601126101935760018060a01b0361342c81835460101c163314613dfc565b8060025416906040519163bf40fac160e01b8084526020918260048601526024600a8187015260449269417373657453746f726560b01b8488015260649085888381875afa978815613bcf578998613b98575b50866bffffffffffffffffffffffff60a01b98168860035416176003556040518181528660048201526009848201526846756e6453746f726560b81b8682015286818481885afa80156138ed5788918b91613b60575b5016886004541617600455604051818152866004820152600c848201526b46756e64696e6753746f726560a01b8682015286818481885afa80156138ed5788918b91613b28575b5016886005541617600555604051818152866004820152600b848201526a4d61726b657453746f726560a81b8682015286818481885afa80156138ed5788918b91613af0575b5016886006541617600655604051818152866004820152600a84820152694f7264657253746f726560b01b8682015286818481885afa80156138ed5788918b91613ab8575b501688600754161760075560405181815286600482015260098482015268506f6f6c53746f726560b81b8682015286818481885afa80156138ed5788918b91613a80575b5016886008541617600855604051818152866004820152600d848201526c506f736974696f6e53746f726560981b8682015286818481885afa80156138ed5788918b91613a48575b5016886009541617600955604051818152866004820152600984820152685269736b53746f726560b81b8682015286818481885afa80156138ed5788918b91613a10575b501688600a541617600a55604051818152866004820152600c848201526b4275794261636b53746f726560a01b8682015286818481885afa80156138ed5788918b916139d8575b501688600b541617600b556040518181528660048201526007848201526646756e64696e6760c81b8682015286818481885afa80156138ed5788918b916139a0575b501688600c541617600c5560405181815286600482015260048482015263141bdbdb60e21b8682015286818481885afa80156138ed5788918b91613968575b501688600d541617600d55604051818152866004820152600484820152630a0f2e8d60e31b8682015286818481885afa80156138ed5788918b91613930575b501688600e541617600e55604051818152866004820152600b848201526a283cba342ab83230ba32b960a91b8682015286818481885afa80156138ed5788918b916138f8575b501688600f541617600f5560405193818552866004860152600d848601526c526566657272616c53746f726560981b8686015286858481845afa9485156138ed57879589918c9161389a575b50966a52656261746553746f726560a81b91600b98168b6010541617601055604051978896879586528860048701528501528301525afa9182156114e6578592613864575b50501690601154161760115580f35b90809250813d8311613893575b61387b8183613d0e565b810103126114965761388c90613ed1565b3880613855565b503d613871565b97968092508891503d83116138e6575b6138b48183613d0e565b810103126138e2576a52656261746553746f726560a81b8795896138d9600b99613ed1565b91985091613810565b8980fd5b503d6138aa565b6040513d8c823e3d90fd5b809250888092503d8311613929575b6139118183613d0e565b810103126138e2576139238891613ed1565b386137c4565b503d613907565b809250888092503d8311613961575b6139498183613d0e565b810103126138e25761395b8891613ed1565b3861377e565b503d61393f565b809250888092503d8311613999575b6139818183613d0e565b810103126138e2576139938891613ed1565b3861373f565b503d613977565b809250888092503d83116139d1575b6139b98183613d0e565b810103126138e2576139cb8891613ed1565b38613700565b503d6139af565b809250888092503d8311613a09575b6139f18183613d0e565b810103126138e257613a038891613ed1565b386136be565b503d6139e7565b809250888092503d8311613a41575b613a298183613d0e565b810103126138e257613a3b8891613ed1565b38613677565b503d613a1f565b809250888092503d8311613a79575b613a618183613d0e565b810103126138e257613a738891613ed1565b38613633565b503d613a57565b809250888092503d8311613ab1575b613a998183613d0e565b810103126138e257613aab8891613ed1565b386135eb565b503d613a8f565b809250888092503d8311613ae9575b613ad18183613d0e565b810103126138e257613ae38891613ed1565b386135a7565b503d613ac7565b809250888092503d8311613b21575b613b098183613d0e565b810103126138e257613b1b8891613ed1565b38613562565b503d613aff565b809250888092503d8311613b59575b613b418183613d0e565b810103126138e257613b538891613ed1565b3861351c565b503d613b37565b809250888092503d8311613b91575b613b798183613d0e565b810103126138e257613b8b8891613ed1565b386134d5565b503d613b6f565b9097508581813d8311613bc8575b613bb08183613d0e565b8101031261160157613bc190613ed1565b963861347f565b503d613ba6565b6040513d8b823e3d90fd5b5034610193578060031936011261019357600d546040516001600160a01b039091168152602090f35b50346101935780600319360112610193575460405160109190911c6001600160a01b03168152602090f35b50346101935780600319360112610193576004546040516001600160a01b039091168152602090f35b5034610193578060031936011261019357600b546040516001600160a01b039091168152602090f35b9050346110145781600319360112611014576011546001600160a01b03168152602090f35b602435906001600160a01b038216820361105657565b600435906001600160a01b038216820361105657565b60609060031901126110565760043590602435906044356001600160a01b03811681036110565790565b6001600160401b03811161157157604052565b90601f801991011681019081106001600160401b0382111761157157604052565b6001600160401b03811161157157601f01601f191660200190565b929192613d5682613d2f565b91613d646040519384613d0e565b829481845281830111611056578281602093846000960137010152565b9080601f8301121561105657816020613d9c93359101613d4a565b90565b9181601f84011215611056578235916001600160401b038311611056576020838186019501011161105657565b9181601f84011215611056578235916001600160401b038311611056576020808501948460051b01011161105657565b15613e0357565b606460405162461bcd60e51b815260206004820152600460248201526310b3b7bb60e11b6044820152fd5b6001600160a01b03818116918215613ea0576000805462010000600160b01b03198116601093841b62010000600160b01b031617909155604080519190921c909216825260208201929092527f53351836099c03ffc3b1727d8abd4b0222afa87d4ed76ae3102d51369ef7f7859190a1565b60405162461bcd60e51b815260206004820152600960248201526810bd32b93796b3b7bb60b91b6044820152606490fd5b51906001600160a01b038216820361105657565b5190811515820361105657565b15613ef957565b60405162461bcd60e51b815260206004820152600e60248201526d21636f6e74726163742d726f6c6560901b6044820152606490fd5b60005b838110613f425750506000910152565b8181015183820152602001613f32565b81601f82011215611056578051613f6881613d2f565b92613f766040519485613d0e565b8184526020828401011161105657613d9c9160208085019101613f2f565b6020818303126110565780516001600160401b03918282116110565701906101c092838382031261105657604051938401848110838211176115715760405282518452613fe360208401613ed1565b6020850152613ff460408401613ed1565b6040850152606083015191821161105657614010918301613f52565b60608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e083015261010061404b818301613ee5565b90830152610120808201519060ff8216820361105657830152610140614072818301613ee5565b90830152610160808201519083015261018080820151908301526101a0809101519082015290565b906020916140b381518092818552858086019101613f2f565b601f01601f1916010190565b929493906060926140e59160018060a01b0316855260806020860152608085019061409a565b9460408401521515910152565b6001600160a01b039091168152604060208201819052613d9c9291019061409a565b6020818303126110565780516001600160401b039182821161105657019061012092838382031261105657604051938401848110838211176115715760405261415c83613ed1565b845261416a60208401613ed1565b6020850152604083015191821161105657614186918301613f52565b604083015261419760608201613ee5565b60608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e0830152610100809101519082015290565b6001600160a01b03918216815291166020820152606060408201819052613d9c9291019061409a565b8181029291811591840414171561420e57565b634e487b7160e01b600052601160045260246000fd5b9190820180921161420e57565b811561423b570490565b634e487b7160e01b600052601260045260246000fd5b94939261427e9160609360018060a01b03809216885216602087015260806040870152608086019061409a565b930152565b9190820391821161420e57565b6020815260018060a01b03808351166020830152602083015116604082015260408201516142cc6101209182606085015261014084019061409a565b92606081015115156080840152608081015160a084015260a081015160c084015260c081015160e084015260e0810151906101009182850152015191015290565b60008190039190600160ff1b811460011661420e5760001983050361420e57565b818102929160008212600160ff1b82141661420e57818405149015171561420e57565b908060209392818452848401376000828201840152601f01601f1916010190565b6001600160a01b03918216815291166020820152606060408201819052613d9c93910191614351565b156143a257565b60405162461bcd60e51b815260206004820152600960248201526810b837b9b4ba34b7b760b91b6044820152606490fd5b9160208181850182865252604084019360408360051b82010194846000925b858410614403575050505050505090565b90919293949596603f198282030184528735601e19843603018112156110565783018681019190356001600160401b0381116110565780360383136110565761445188928392600195614351565b9901940194019295949391906143f2565b6020818303126110565780516001600160401b03918282116110565701906101e0928383820312611056576040519384018481108382111761157157604052825182811161105657816144b6918501613f52565b84526020830151918211611056576144cf918301613f52565b60208301526144e060408201613ed1565b6040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e0830152610100808201519083015261012080820151908301526101408082015190830152610160614546818301613ee5565b90830152610180614558818301613ee5565b908301526101a080820151908301526101c0809101519082015290565b1561457c57565b60405162461bcd60e51b815260206004820152600660248201526521707269636560d01b6044820152606490fd5b156145b157565b60405162461bcd60e51b8152602060048201526008602482015267216d61782d61676560c01b6044820152606490fd5b156145e857565b60405162461bcd60e51b8152602060048201526007602482015266085c185d5cd95960ca1b6044820152606490fd5b1561461e57565b60405162461bcd60e51b815260206004820152600760248201526610b6b0b933b4b760c91b6044820152606490fd5b906146679060409396959496606084526060840191614351565b9460208201520152565b929094916000928515614d8257600954604051632bdc62f560e21b81529490602090869060049082906001600160a01b03165afa8015614d75578190614d3a575b600b546040516374d6f48760e11b81529650602090879060049082906001600160a01b03165afa958615611009578296614d06575b506008546040516374d6f48760e11b81526001600160a01b0390911690602081600481855afa908115611566578491614cd4575b5089670de0b6b3a7640000810204670de0b6b3a764000003614cc05783926001600160a01b038616151580614cb7575b614c95575b50601054604051634a9fefc760e01b81526001600160a01b038d8116600483015290911695906020816024818a5afa908115611473578691614c5b575b5085968c60018060a01b0383169182614bb2575b50886147ba88670de0b6b3a76400006147bf9402614283565b614283565b809b8015600014614b995750506147e6879b8c955b80614b8057506147ba899d8e92614283565b94803b1561144b5760405163de900ab960e01b81526001600160a01b038b166004820152670de0b6b3a76400008d0460248201529088908290604490829084905af1801561106357614b6d575b50600b546001600160a01b0316803b1561144b5760405163e7904f1960e01b81526001600160a01b038b166004820152670de0b6b3a7640000860460248201529088908290604490829084905af1801561106357908891614b59575b5050614adc575b506004805460025460405163bf40fac160e01b815260209381018490526008602482015267747265617375727960c01b60448201526001600160a01b03928316939092909183916064918391165afa908115611823578791614aa2575b50813b156112985760405163078d3b7960e01b81526001600160a01b038a81166004830152919091166024820152670de0b6b3a7640000850460448201529086908290606490829084905af1801561147357908691614a8e575b50506004546001600160a01b031690813b156110055760405163078d3b7960e01b81526001600160a01b038981166004830152919091166024820152670de0b6b3a7640000850460448201529085908290606490829084905af180156114e657908591614a7a575b5050604051978897610100808a5289016149ce9161409a565b9a670de0b6b3a764000002670de0b6b3a764000090046020890152670de0b6b3a764000090046040880152670de0b6b3a764000090046060870152670de0b6b3a764000090046080860152670de0b6b3a7640000900460a085015260c0840152670de0b6b3a7640000900460e0830152600160a01b600190031694600160a01b600190031693037fefec25506ec34f1da5d044e02e9e6af1270aadcf8747bb65b34bc283ad1e76e791a4565b614a8390613cfb565b6114965783386149b5565b614a9790613cfb565b61149257843861494d565b90506020813d602011614ad4575b81614abd60209383613d0e565b8101031261129857614ace90613ed1565b386148f3565b3d9150614ab0565b6011546001600160a01b0316803b15611298576040516346f1a43360e11b81526001600160a01b0392831660048201529189166024830152670de0b6b3a76400008804604483015286908290606490829084905af1801561147357908691614b45575b50614896565b614b4e90613cfb565b611492578438614b3f565b614b6290613cfb565b61129857863861488f565b614b7990979197613cfb565b9538614833565b612710614b906147ba92846141fb565b049d8e92614283565b614ba9612710916147e6936141fb565b049b8c956147d4565b6024929394959697989950602091506040519283809263f8374de160e01b82528660048301525afa90811561106357908d918991614c1e575b50816147ba89612710614c136147bf95670de0b6b3a76400009e9d9c9b9a9998978f026141fb565b049b505050906147a1565b9150506020813d602011614c53575b81614c3a60209383613d0e565b8101031261144b57518c90670de0b6b3a7640000614beb565b3d9150614c2d565b90506020813d602011614c8d575b81614c7660209383613d0e565b8101031261100557614c8790613ed1565b3861478d565b3d9150614c69565b612710919350614caf90670de0b6b3a76400008c026141fb565b049138614750565b5080151561474b565b634e487b7160e01b84526011600452602484fd5b90506020813d602011614cfe575b81614cef60209383613d0e565b8101031261149657513861471b565b3d9150614ce2565b9095506020813d602011614d32575b81614d2260209383613d0e565b81010312611014575194386146e7565b3d9150614d15565b50909192936020813d602011614d6d575b81614d5860209383613d0e565b810103126110145790600494939291516146b2565b3d9150614d4b565b50604051903d90823e3d90fd5b50505050505050565b939492919095600093861561548757600954604051632bdc62f560e21b815290602090829060049082906001600160a01b03165afa908115611473578691615455575b50600b546040516374d6f48760e11b808252909791602090899060049082906001600160a01b03165afa978815611009578298615421575b506008546040519182526001600160a01b031691602082600481865afa918215614d755781926153ed575b508a670de0b6b3a7640000810204670de0b6b3a7640000036153d9579283906001600160a01b0387161515806153d0575b6153ae575b50601054604051634a9fefc760e01b81526001600160a01b038e8116600483015290911696906020816024818b5afa9081156112b0578391615374575b5082978d60018060a01b03831691826152c1575b50896147ba89670de0b6b3a7640000614ed19402614283565b809c80156000146152a8575050614ef8849c8d965b8061528f57506147ba869e8f92614283565b95803b156114925760405163de900ab960e01b81526001600160a01b038c166004820152670de0b6b3a76400008e0460248201529085908290604490829084905af180156114e65761527c575b50600b546001600160a01b0316803b156114925760405163e7904f1960e01b81526001600160a01b038c166004820152670de0b6b3a7640000870460248201529085908290604490829084905af180156114e657908591615268575b50506151eb575b506004805460025460405163bf40fac160e01b815260209381018490526008602482015267747265617375727960c01b6044820152926001600160a01b0392831692909184916064918391165afa9182156115665784926151af575b50803b156114965760405163078d3b7960e01b81526001600160a01b038b81166004830152929092166024830152670de0b6b3a76400008604604483015283908290606490829084905af180156112b05790839161519b575b50506004546001600160a01b0316803b156120615760405163078d3b7960e01b81526001600160a01b038a81166004830152929092166024830152670de0b6b3a76400008604604483015282908290606490829084905af1801561100957615187575b5050604051978897610100808a5289016150d99161409a565b9a670de0b6b3a764000002670de0b6b3a764000090046020890152670de0b6b3a764000090046040880152670de0b6b3a764000090046060870152670de0b6b3a764000090046080860152670de0b6b3a7640000900460a0850152151560c0840152670de0b6b3a7640000900460e0830152600160a01b600190031694600160a01b600190031693037fefec25506ec34f1da5d044e02e9e6af1270aadcf8747bb65b34bc283ad1e76e791a4565b6151918291613cfb565b61019357806150c0565b6151a490613cfb565b61101457813861505d565b9091506020813d6020116151e3575b816151cb60209383613d0e565b81010312611496576151dc90613ed1565b9038615004565b3d91506151be565b6011546001600160a01b0316803b15611496576040516346f1a43360e11b81526001600160a01b039283166004820152918a166024830152670de0b6b3a76400008904604483015283908290606490829084905af180156112b057908391615254575b50614fa8565b61525d90613cfb565b61101457813861524e565b61527190613cfb565b611496578338614fa1565b61528890949194613cfb565b9238614f45565b61271061529f6147ba92846141fb565b049e8f92614283565b6152b861271091614ef8936141fb565b049c8d96614ee6565b602492939495969798999a50602091506040519283809263f8374de160e01b82528660048301525afa9081156114e657908e918691615337575b50816147ba8a61271061532c614ed195670de0b6b3a76400009f9e9d9c9b9a999897670de0b6b3a7640000026141fb565b049c50505090614eb8565b9150506020813d60201161536c575b8161535360209383613d0e565b8101031261149257518d90670de0b6b3a76400006152fb565b3d9150615346565b90506020813d6020116153a6575b8161538f60209383613d0e565b81010312612061576153a090613ed1565b38614ea4565b3d9150615382565b6127109194506153c890670de0b6b3a76400008d026141fb565b049238614e67565b50801515614e62565b634e487b7160e01b81526011600452602490fd5b9091506020813d602011615419575b8161540960209383613d0e565b8101031261101457519038614e31565b3d91506153fc565b9097506020813d60201161544d575b8161543d60209383613d0e565b8101031261101457519638614e06565b3d9150615430565b90506020813d60201161547f575b8161547060209383613d0e565b81010312611005575138614dce565b3d9150615463565b5050505050505050565b8181039291600013801582851316918412161761420e57565b811561423b57600160ff1b811460001983141661420e570590565b94939695929091968115801561560d575b8015615605575b6155f5579160209161553b93896000146155df576155076155018261550c94615491565b8861432e565b6154aa565b955b600c5460405163f612620760e01b81529485936001600160a01b03909216928492839291600484016140f2565b03915afa9081156155d3576000916155a0575b509161556861556e9269021e19e0c9bab240000094615491565b9061432e565b0580936000146155855761558191615491565b9190565b8101906000848312911290801582169115161761420e579190565b906020823d82116155cb575b816155b960209383613d0e565b8101031261019357505161556861554e565b3d91506155ac565b6040513d6000823e3d90fd5b6155076155016155ef9383615491565b9561550e565b5050505050509050600090600090565b5084156154dd565b5080156154d6565b600e54604080516396834ad360e01b815260048082019490945293929091602491906080908690849082906001600160a01b03165afa9485156157d357600095615733575b506000855160070b1315615701578285015160030b92836012019384126001166156ed57600084126156bd5750604d83116156aa5750506156a4606091600a0a845160070b6141fb565b92015190565b601190634e487b7160e01b600052526000fd5b6064926020600c92519362461bcd60e51b85528401528201526b021696e76616c69642d6578760a41b6044820152fd5b50601190634e487b7160e01b600052526000fd5b600e606492602085519362461bcd60e51b85528401528201526d21696e76616c69642d707269636560901b6044820152fd5b6080959195813d82116157cb575b8161574e60809383613d0e565b81010312611014578351916001600160401b0360808401818111858210176157b957865282518060070b81036120615784526020830151908116810361101457602084015284820151908160030b82036101935750906060918584015201516060820152933861565a565b634e487b7160e01b8352604189528583fd5b3d9150615741565b83513d6000823e3d90fdfe3a1062142d0d194eaf2928092e53c3f84f5602268f2b82effd44010aff82cb90a66b7a3e6b19d24ccb6f717fc232a1bb0278a7f83f8e2211835fc4ed0fe69f19a264697066735822122081f86476a896ed9a02a87190b3ea3c665bd96982816930959726b11b4ae489f464736f6c63430008110033

Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

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