false
false
100

Contract Address Details

0xa88A72Fb379EC22f92e586229e01F631218CC8c6

Contract Name
OrderBook
Creator
0x2a0791–e05fe1 at 0x46cbf3–ce2bb5
Balance
0 KAVA ( )
Tokens
Fetching tokens...
Transactions
Fetching transactions...
Transfers
Fetching transfers...
Gas Used
Fetching gas used...
Last Balance Update
11603181
Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
Contract name:
OrderBook




Optimization enabled
true
Compiler version
v0.6.12+commit.27d51765




Optimization runs
16
Verified at
2023-07-04T11:16:33.576055Z

contracts/core/OrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

import "../libraries/math/SafeMath.sol";
import "../libraries/token/IERC20.sol";
import "../tokens/interfaces/IWETH.sol";
import "../libraries/token/SafeERC20.sol";
import "../libraries/utils/Address.sol";
import "../libraries/utils/ReentrancyGuard.sol";

import "./interfaces/IRouter.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IOrderBook.sol";
import "./interfaces/IExecutionFee.sol";

contract OrderBook is ReentrancyGuard, IOrderBook, IExecutionFee {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;
    using Address for address payable;

    uint256 public constant PRICE_PRECISION = 1e30;
    uint256 public constant USDK_PRECISION = 1e18;

    struct IncreaseOrder {
        address account;
        address purchaseToken;
        uint256 purchaseTokenAmount;
        address collateralToken;
        address indexToken;
        uint256 sizeDelta;
        bool isLong;
        uint256 triggerPrice;
        bool triggerAboveThreshold;
        uint256 executionFee;
    }
    struct DecreaseOrder {
        address account;
        address collateralToken;
        uint256 collateralDelta;
        address indexToken;
        uint256 sizeDelta;
        bool isLong;
        uint256 triggerPrice;
        bool triggerAboveThreshold;
        uint256 executionFee;
    }
    struct SwapOrder {
        address account;
        address[] path;
        uint256 amountIn;
        uint256 minOut;
        uint256 triggerRatio;
        bool triggerAboveThreshold;
        bool shouldUnwrap;
        uint256 executionFee;
    }

    mapping (address => mapping(uint256 => IncreaseOrder)) public increaseOrders;
    mapping (address => uint256) public increaseOrdersIndex;
    mapping (address => mapping(uint256 => DecreaseOrder)) public decreaseOrders;
    mapping (address => uint256) public decreaseOrdersIndex;
    mapping (address => mapping(uint256 => SwapOrder)) public swapOrders;
    mapping (address => uint256) public swapOrdersIndex;

    address public gov;
    address public weth;
    address public usdk;
    address public router;
    address public vault;
    uint256 public minExecutionFee;
    uint256 public minPurchaseTokenAmountUsd;
    bool public isInitialized = false;

    event CreateIncreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address purchaseToken,
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );
    event CancelIncreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address purchaseToken,
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );
    event ExecuteIncreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address purchaseToken,
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee,
        uint256 executionPrice
    );
    event UpdateIncreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address collateralToken,
        address indexToken,
        bool isLong,
        uint256 sizeDelta,
        uint256 triggerPrice,
        bool triggerAboveThreshold
    );
    event CreateDecreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );
    event CancelDecreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );
    event ExecuteDecreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee,
        uint256 executionPrice
    );
    event UpdateDecreaseOrder(
        address indexed account,
        uint256 orderIndex,
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold
    );
    event CreateSwapOrder(
        address indexed account,
        uint256 orderIndex,
        address[] path,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );
    event CancelSwapOrder(
        address indexed account,
        uint256 orderIndex,
        address[] path,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );
    event UpdateSwapOrder(
        address indexed account,
        uint256 ordexIndex,
        address[] path,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );
    event ExecuteSwapOrder(
        address indexed account,
        uint256 orderIndex,
        address[] path,
        uint256 amountIn,
        uint256 minOut,
        uint256 amountOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    event Initialize(
        address router,
        address vault,
        address weth,
        address usdk,
        uint256 minExecutionFee,
        uint256 minPurchaseTokenAmountUsd
    );
    event UpdateMinExecutionFee(uint256 minExecutionFee);
    event UpdateMinPurchaseTokenAmountUsd(uint256 minPurchaseTokenAmountUsd);
    event UpdateGov(address gov);

    modifier onlyGov() {
        require(msg.sender == gov, "OrderBook: forbidden");
        _;
    }

    constructor() public {
        gov = msg.sender;
    }

    function initialize(
        address _router,
        address _vault,
        address _weth,
        address _usdk,
        uint256 _minExecutionFee,
        uint256 _minPurchaseTokenAmountUsd
    ) external onlyGov {
        require(!isInitialized, "OrderBook: already initialized");
        isInitialized = true;

        router = _router;
        vault = _vault;
        weth = _weth;
        usdk = _usdk;
        minExecutionFee = _minExecutionFee;
        minPurchaseTokenAmountUsd = _minPurchaseTokenAmountUsd;

        emit Initialize(_router, _vault, _weth, _usdk, _minExecutionFee, _minPurchaseTokenAmountUsd);
    }

    receive() external payable {
        require(msg.sender == weth, "OrderBook: invalid sender");
    }

    function setMinExecutionFee(uint256 _minExecutionFee) override external onlyGov {
        minExecutionFee = _minExecutionFee;

        emit UpdateMinExecutionFee(_minExecutionFee);
    }

    function setMinPurchaseTokenAmountUsd(uint256 _minPurchaseTokenAmountUsd) external onlyGov {
        minPurchaseTokenAmountUsd = _minPurchaseTokenAmountUsd;

        emit UpdateMinPurchaseTokenAmountUsd(_minPurchaseTokenAmountUsd);
    }

    function setGov(address _gov) external onlyGov {
        gov = _gov;

        emit UpdateGov(_gov);
    }

    function getSwapOrder(address _account, uint256 _orderIndex) override public view returns (
        address path0,
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    ) {
        SwapOrder memory order = swapOrders[_account][_orderIndex];
        return (
            order.path.length > 0 ? order.path[0] : address(0),
            order.path.length > 1 ? order.path[1] : address(0),
            order.path.length > 2 ? order.path[2] : address(0),
            order.amountIn,
            order.minOut,
            order.triggerRatio,
            order.triggerAboveThreshold,
            order.shouldUnwrap,
            order.executionFee
        );
    }

    function createSwapOrder(
        address[] memory _path,
        uint256 _amountIn,
        uint256 _minOut,
        uint256 _triggerRatio, // tokenB / tokenA
        bool _triggerAboveThreshold,
        uint256 _executionFee,
        bool _shouldWrap,
        bool _shouldUnwrap
    ) external payable nonReentrant {
        require(_path.length == 2 || _path.length == 3, "OrderBook: invalid _path.length");
        require(_path[0] != _path[_path.length - 1], "OrderBook: invalid _path");
        require(_amountIn > 0, "OrderBook: invalid _amountIn");
        require(_executionFee >= minExecutionFee, "OrderBook: insufficient execution fee");

        // always need this call because of mandatory executionFee user has to transfer in ETH
        _transferInETH();

        if (_shouldWrap) {
            require(_path[0] == weth, "OrderBook: only weth could be wrapped");
            require(msg.value == _executionFee.add(_amountIn), "OrderBook: incorrect value transferred");
        } else {
            require(msg.value == _executionFee, "OrderBook: incorrect execution fee transferred");
            IRouter(router).pluginTransfer(_path[0], msg.sender, address(this), _amountIn);
        }

        _createSwapOrder(msg.sender, _path, _amountIn, _minOut, _triggerRatio, _triggerAboveThreshold, _shouldUnwrap, _executionFee);
    }

    function _createSwapOrder(
        address _account,
        address[] memory _path,
        uint256 _amountIn,
        uint256 _minOut,
        uint256 _triggerRatio,
        bool _triggerAboveThreshold,
        bool _shouldUnwrap,
        uint256 _executionFee
    ) private {
        uint256 _orderIndex = swapOrdersIndex[_account];
        SwapOrder memory order = SwapOrder(
            _account,
            _path,
            _amountIn,
            _minOut,
            _triggerRatio,
            _triggerAboveThreshold,
            _shouldUnwrap,
            _executionFee
        );
        swapOrdersIndex[_account] = _orderIndex.add(1);
        swapOrders[_account][_orderIndex] = order;

        emit CreateSwapOrder(
            _account,
            _orderIndex,
            _path,
            _amountIn,
            _minOut,
            _triggerRatio,
            _triggerAboveThreshold,
            _shouldUnwrap,
            _executionFee
        );
    }

    function cancelMultiple(
        uint256[] memory _swapOrderIndexes,
        uint256[] memory _increaseOrderIndexes,
        uint256[] memory _decreaseOrderIndexes
    ) external {
        for (uint256 i = 0; i < _swapOrderIndexes.length; i++) {
            cancelSwapOrder(_swapOrderIndexes[i]);
        }
        for (uint256 i = 0; i < _increaseOrderIndexes.length; i++) {
            cancelIncreaseOrder(_increaseOrderIndexes[i]);
        }
        for (uint256 i = 0; i < _decreaseOrderIndexes.length; i++) {
            cancelDecreaseOrder(_decreaseOrderIndexes[i]);
        }
    }

    function cancelSwapOrder(uint256 _orderIndex) public nonReentrant {
        SwapOrder memory order = swapOrders[msg.sender][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        delete swapOrders[msg.sender][_orderIndex];

        if (order.path[0] == weth) {
            _transferOutETH(order.executionFee.add(order.amountIn), msg.sender);
        } else {
            IERC20(order.path[0]).safeTransfer(msg.sender, order.amountIn);
            _transferOutETH(order.executionFee, msg.sender);
        }

        emit CancelSwapOrder(
            msg.sender,
            _orderIndex,
            order.path,
            order.amountIn,
            order.minOut,
            order.triggerRatio,
            order.triggerAboveThreshold,
            order.shouldUnwrap,
            order.executionFee
        );
    }

    function getUsdkMinPrice(address _otherToken) public view returns (uint256) {
        // USDK_PRECISION is the same as 1 USDK
        uint256 redemptionAmount = IVault(vault).getRedemptionAmount(_otherToken, USDK_PRECISION);
        uint256 otherTokenPrice = IVault(vault).getMinPrice(_otherToken);

        uint256 otherTokenDecimals = IVault(vault).tokenDecimals(_otherToken);
        return redemptionAmount.mul(otherTokenPrice).div(10 ** otherTokenDecimals);
    }

    function validateSwapOrderPriceWithTriggerAboveThreshold(
        address[] memory _path,
        uint256 _triggerRatio
    ) public view returns (bool) {
        require(_path.length == 2 || _path.length == 3, "OrderBook: invalid _path.length");

        // limit orders don't need this validation because minOut is enough
        // so this validation handles scenarios for stop orders only
        // when a user wants to swap when a price of tokenB increases relative to tokenA
        address tokenA = _path[0];
        address tokenB = _path[_path.length - 1];
        uint256 tokenAPrice;
        uint256 tokenBPrice;

        // 1. USDK doesn't have a price feed so we need to calculate it based on redepmtion amount of a specific token
        // That's why USDK price in USD can vary depending on the redepmtion token
        // 2. In complex scenarios with path=[USDK, BNB, BTC] we need to know how much BNB we'll get for provided USDK
        // to know how much BTC will be received
        // That's why in such scenario BNB should be used to determine price of USDK
        if (tokenA == usdk) {
            // with both _path.length == 2 or 3 we need usdk price against _path[1]
            tokenAPrice = getUsdkMinPrice(_path[1]);
        } else {
            tokenAPrice = IVault(vault).getMinPrice(tokenA);
        }

        if (tokenB == usdk) {
            tokenBPrice = PRICE_PRECISION;
        } else {
            tokenBPrice = IVault(vault).getMaxPrice(tokenB);
        }

        uint256 currentRatio = tokenBPrice.mul(PRICE_PRECISION).div(tokenAPrice);

        bool isValid = currentRatio > _triggerRatio;
        return isValid;
    }

    function updateSwapOrder(uint256 _orderIndex, uint256 _minOut, uint256 _triggerRatio, bool _triggerAboveThreshold) external nonReentrant {
        SwapOrder storage order = swapOrders[msg.sender][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        order.minOut = _minOut;
        order.triggerRatio = _triggerRatio;
        order.triggerAboveThreshold = _triggerAboveThreshold;

        emit UpdateSwapOrder(
            msg.sender,
            _orderIndex,
            order.path,
            order.amountIn,
            _minOut,
            _triggerRatio,
            _triggerAboveThreshold,
            order.shouldUnwrap,
            order.executionFee
        );
    }

    function executeSwapOrder(address _account, uint256 _orderIndex, address payable _feeReceiver) override external nonReentrant {
        SwapOrder memory order = swapOrders[_account][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        if (order.triggerAboveThreshold) {
            // gas optimisation
            // order.minAmount should prevent wrong price execution in case of simple limit order
            require(
                validateSwapOrderPriceWithTriggerAboveThreshold(order.path, order.triggerRatio),
                "OrderBook: invalid price for execution"
            );
        }

        delete swapOrders[_account][_orderIndex];

        IERC20(order.path[0]).safeTransfer(vault, order.amountIn);

        uint256 _amountOut;
        if (order.path[order.path.length - 1] == weth && order.shouldUnwrap) {
            _amountOut = _swap(order.path, order.minOut, address(this));
            _transferOutETH(_amountOut, payable(order.account));
        } else {
            _amountOut = _swap(order.path, order.minOut, order.account);
        }

        // pay executor
        _transferOutETH(order.executionFee, _feeReceiver);

        emit ExecuteSwapOrder(
            _account,
            _orderIndex,
            order.path,
            order.amountIn,
            order.minOut,
            _amountOut,
            order.triggerRatio,
            order.triggerAboveThreshold,
            order.shouldUnwrap,
            order.executionFee
        );
    }

    function validatePositionOrderPrice(
        bool _triggerAboveThreshold,
        uint256 _triggerPrice,
        address _indexToken,
        bool _maximizePrice,
        bool _raise
    ) public view returns (uint256, bool) {
        uint256 currentPrice = _maximizePrice
            ? IVault(vault).getMaxPrice(_indexToken) : IVault(vault).getMinPrice(_indexToken);
        bool isPriceValid = _triggerAboveThreshold ? currentPrice > _triggerPrice : currentPrice < _triggerPrice;
        if (_raise) {
            require(isPriceValid, "OrderBook: invalid price for execution");
        }
        return (currentPrice, isPriceValid);
    }

    function getDecreaseOrder(address _account, uint256 _orderIndex) override public view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    ) {
        DecreaseOrder memory order = decreaseOrders[_account][_orderIndex];
        return (
            order.collateralToken,
            order.collateralDelta,
            order.indexToken,
            order.sizeDelta,
            order.isLong,
            order.triggerPrice,
            order.triggerAboveThreshold,
            order.executionFee
        );
    }

    function getIncreaseOrder(address _account, uint256 _orderIndex) override public view returns (
        address purchaseToken,
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    ) {
        IncreaseOrder memory order = increaseOrders[_account][_orderIndex];
        return (
            order.purchaseToken,
            order.purchaseTokenAmount,
            order.collateralToken,
            order.indexToken,
            order.sizeDelta,
            order.isLong,
            order.triggerPrice,
            order.triggerAboveThreshold,
            order.executionFee
        );
    }

    function createIncreaseOrder(
        address[] memory _path,
        uint256 _amountIn,
        address _indexToken,
        uint256 _minOut,
        uint256 _sizeDelta,
        address _collateralToken,
        bool _isLong,
        uint256 _triggerPrice,
        bool _triggerAboveThreshold,
        uint256 _executionFee,
        bool _shouldWrap
    ) external payable nonReentrant {
        // always need this call because of mandatory executionFee user has to transfer in ETH
        _transferInETH();

        require(_executionFee >= minExecutionFee, "OrderBook: insufficient execution fee");
        if (_shouldWrap) {
            require(_path[0] == weth, "OrderBook: only weth could be wrapped");
            require(msg.value == _executionFee.add(_amountIn), "OrderBook: incorrect value transferred");
        } else {
            require(msg.value == _executionFee, "OrderBook: incorrect execution fee transferred");
            IRouter(router).pluginTransfer(_path[0], msg.sender, address(this), _amountIn);
        }

        address _purchaseToken = _path[_path.length - 1];
        uint256 _purchaseTokenAmount;
        if (_path.length > 1) {
            require(_path[0] != _purchaseToken, "OrderBook: invalid _path");
            IERC20(_path[0]).safeTransfer(vault, _amountIn);
            _purchaseTokenAmount = _swap(_path, _minOut, address(this));
        } else {
            _purchaseTokenAmount = _amountIn;
        }

        {
            uint256 _purchaseTokenAmountUsd = IVault(vault).tokenToUsdMin(_purchaseToken, _purchaseTokenAmount);
            require(_purchaseTokenAmountUsd >= minPurchaseTokenAmountUsd, "OrderBook: insufficient collateral");
        }

        _createIncreaseOrder(
            msg.sender,
            _purchaseToken,
            _purchaseTokenAmount,
            _collateralToken,
            _indexToken,
            _sizeDelta,
            _isLong,
            _triggerPrice,
            _triggerAboveThreshold,
            _executionFee
        );
    }

    function _createIncreaseOrder(
        address _account,
        address _purchaseToken,
        uint256 _purchaseTokenAmount,
        address _collateralToken,
        address _indexToken,
        uint256 _sizeDelta,
        bool _isLong,
        uint256 _triggerPrice,
        bool _triggerAboveThreshold,
        uint256 _executionFee
    ) private {
        uint256 _orderIndex = increaseOrdersIndex[msg.sender];
        IncreaseOrder memory order = IncreaseOrder(
            _account,
            _purchaseToken,
            _purchaseTokenAmount,
            _collateralToken,
            _indexToken,
            _sizeDelta,
            _isLong,
            _triggerPrice,
            _triggerAboveThreshold,
            _executionFee
        );
        increaseOrdersIndex[_account] = _orderIndex.add(1);
        increaseOrders[_account][_orderIndex] = order;

        emit CreateIncreaseOrder(
            _account,
            _orderIndex,
            _purchaseToken,
            _purchaseTokenAmount,
            _collateralToken,
            _indexToken,
            _sizeDelta,
            _isLong,
            _triggerPrice,
            _triggerAboveThreshold,
            _executionFee
        );
    }

    function updateIncreaseOrder(uint256 _orderIndex, uint256 _sizeDelta, uint256 _triggerPrice, bool _triggerAboveThreshold) external nonReentrant {
        IncreaseOrder storage order = increaseOrders[msg.sender][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        order.triggerPrice = _triggerPrice;
        order.triggerAboveThreshold = _triggerAboveThreshold;
        order.sizeDelta = _sizeDelta;

        emit UpdateIncreaseOrder(
            msg.sender,
            _orderIndex,
            order.collateralToken,
            order.indexToken,
            order.isLong,
            _sizeDelta,
            _triggerPrice,
            _triggerAboveThreshold
        );
    }

    function cancelIncreaseOrder(uint256 _orderIndex) public nonReentrant {
        IncreaseOrder memory order = increaseOrders[msg.sender][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        delete increaseOrders[msg.sender][_orderIndex];

        if (order.purchaseToken == weth) {
            _transferOutETH(order.executionFee.add(order.purchaseTokenAmount), msg.sender);
        } else {
            IERC20(order.purchaseToken).safeTransfer(msg.sender, order.purchaseTokenAmount);
            _transferOutETH(order.executionFee, msg.sender);
        }

        emit CancelIncreaseOrder(
            order.account,
            _orderIndex,
            order.purchaseToken,
            order.purchaseTokenAmount,
            order.collateralToken,
            order.indexToken,
            order.sizeDelta,
            order.isLong,
            order.triggerPrice,
            order.triggerAboveThreshold,
            order.executionFee
        );
    }

    function executeIncreaseOrder(address _address, uint256 _orderIndex, address payable _feeReceiver) override external nonReentrant {
        IncreaseOrder memory order = increaseOrders[_address][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        // increase long should use max price
        // increase short should use min price
        (uint256 currentPrice, ) = validatePositionOrderPrice(
            order.triggerAboveThreshold,
            order.triggerPrice,
            order.indexToken,
            order.isLong,
            true
        );

        delete increaseOrders[_address][_orderIndex];

        IERC20(order.purchaseToken).safeTransfer(vault, order.purchaseTokenAmount);

        if (order.purchaseToken != order.collateralToken) {
            address[] memory path = new address[](2);
            path[0] = order.purchaseToken;
            path[1] = order.collateralToken;

            uint256 amountOut = _swap(path, 0, address(this));
            IERC20(order.collateralToken).safeTransfer(vault, amountOut);
        }

        IRouter(router).pluginIncreasePosition(order.account, order.collateralToken, order.indexToken, order.sizeDelta, order.isLong);

        // pay executor
        _transferOutETH(order.executionFee, _feeReceiver);

        emit ExecuteIncreaseOrder(
            order.account,
            _orderIndex,
            order.purchaseToken,
            order.purchaseTokenAmount,
            order.collateralToken,
            order.indexToken,
            order.sizeDelta,
            order.isLong,
            order.triggerPrice,
            order.triggerAboveThreshold,
            order.executionFee,
            currentPrice
        );
    }

    function createDecreaseOrder(
        address _indexToken,
        uint256 _sizeDelta,
        address _collateralToken,
        uint256 _collateralDelta,
        bool _isLong,
        uint256 _triggerPrice,
        bool _triggerAboveThreshold
    ) external payable nonReentrant {
        _transferInETH();

        require(msg.value > minExecutionFee, "OrderBook: insufficient execution fee");

        _createDecreaseOrder(
            msg.sender,
            _collateralToken,
            _collateralDelta,
            _indexToken,
            _sizeDelta,
            _isLong,
            _triggerPrice,
            _triggerAboveThreshold
        );
    }

    function _createDecreaseOrder(
        address _account,
        address _collateralToken,
        uint256 _collateralDelta,
        address _indexToken,
        uint256 _sizeDelta,
        bool _isLong,
        uint256 _triggerPrice,
        bool _triggerAboveThreshold
    ) private {
        uint256 _orderIndex = decreaseOrdersIndex[_account];
        DecreaseOrder memory order = DecreaseOrder(
            _account,
            _collateralToken,
            _collateralDelta,
            _indexToken,
            _sizeDelta,
            _isLong,
            _triggerPrice,
            _triggerAboveThreshold,
            msg.value
        );
        decreaseOrdersIndex[_account] = _orderIndex.add(1);
        decreaseOrders[_account][_orderIndex] = order;

        emit CreateDecreaseOrder(
            _account,
            _orderIndex,
            _collateralToken,
            _collateralDelta,
            _indexToken,
            _sizeDelta,
            _isLong,
            _triggerPrice,
            _triggerAboveThreshold,
            msg.value
        );
    }

    function executeDecreaseOrder(address _address, uint256 _orderIndex, address payable _feeReceiver) override external nonReentrant {
        DecreaseOrder memory order = decreaseOrders[_address][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        // decrease long should use min price
        // decrease short should use max price
        (uint256 currentPrice, ) = validatePositionOrderPrice(
            order.triggerAboveThreshold,
            order.triggerPrice,
            order.indexToken,
            !order.isLong,
            true
        );

        delete decreaseOrders[_address][_orderIndex];

        uint256 amountOut = IRouter(router).pluginDecreasePosition(
            order.account,
            order.collateralToken,
            order.indexToken,
            order.collateralDelta,
            order.sizeDelta,
            order.isLong,
            address(this)
        );

        // transfer released collateral to user
        if (order.collateralToken == weth) {
            _transferOutETH(amountOut, payable(order.account));
        } else {
            IERC20(order.collateralToken).safeTransfer(order.account, amountOut);
        }

        // pay executor
        _transferOutETH(order.executionFee, _feeReceiver);

        emit ExecuteDecreaseOrder(
            order.account,
            _orderIndex,
            order.collateralToken,
            order.collateralDelta,
            order.indexToken,
            order.sizeDelta,
            order.isLong,
            order.triggerPrice,
            order.triggerAboveThreshold,
            order.executionFee,
            currentPrice
        );
    }

    function cancelDecreaseOrder(uint256 _orderIndex) public nonReentrant {
        DecreaseOrder memory order = decreaseOrders[msg.sender][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        delete decreaseOrders[msg.sender][_orderIndex];
        _transferOutETH(order.executionFee, msg.sender);

        emit CancelDecreaseOrder(
            order.account,
            _orderIndex,
            order.collateralToken,
            order.collateralDelta,
            order.indexToken,
            order.sizeDelta,
            order.isLong,
            order.triggerPrice,
            order.triggerAboveThreshold,
            order.executionFee
        );
    }

    function updateDecreaseOrder(
        uint256 _orderIndex,
        uint256 _collateralDelta,
        uint256 _sizeDelta,
        uint256 _triggerPrice,
        bool _triggerAboveThreshold
    ) external nonReentrant {
        DecreaseOrder storage order = decreaseOrders[msg.sender][_orderIndex];
        require(order.account != address(0), "OrderBook: non-existent order");

        order.triggerPrice = _triggerPrice;
        order.triggerAboveThreshold = _triggerAboveThreshold;
        order.sizeDelta = _sizeDelta;
        order.collateralDelta = _collateralDelta;

        emit UpdateDecreaseOrder(
            msg.sender,
            _orderIndex,
            order.collateralToken,
            _collateralDelta,
            order.indexToken,
            _sizeDelta,
            order.isLong,
            _triggerPrice,
            _triggerAboveThreshold
        );
    }

    function _transferInETH() private {
        if (msg.value != 0) {
            IWETH(weth).deposit{value: msg.value}();
        }
    }

    function _transferOutETH(uint256 _amountOut, address payable _receiver) private {
        IWETH(weth).withdraw(_amountOut);
        _receiver.sendValue(_amountOut);
    }

    function _swap(address[] memory _path, uint256 _minOut, address _receiver) private returns (uint256) {
        if (_path.length == 2) {
            return _vaultSwap(_path[0], _path[1], _minOut, _receiver);
        }
        if (_path.length == 3) {
            uint256 midOut = _vaultSwap(_path[0], _path[1], 0, address(this));
            IERC20(_path[1]).safeTransfer(vault, midOut);
            return _vaultSwap(_path[1], _path[2], _minOut, _receiver);
        }

        revert("OrderBook: invalid _path.length");
    }

    function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) private returns (uint256) {
        uint256 amountOut;

        if (_tokenOut == usdk) { // buyUSDK
            amountOut = IVault(vault).buyUSDK(_tokenIn, _receiver);
        } else if (_tokenIn == usdk) { // sellUSDK
            amountOut = IVault(vault).sellUSDK(_tokenOut, _receiver);
        } else { // swap
            amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver);
        }

        require(amountOut >= _minOut, "OrderBook: insufficient amountOut");
        return amountOut;
    }
}
        

contracts/core/interfaces/IExecutionFee.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IExecutionFee {
    function setMinExecutionFee(uint256 _minExecutionFee) external;
}

          

contracts/libraries/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

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

contracts/core/interfaces/IOrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IOrderBook {
	function getSwapOrder(address _account, uint256 _orderIndex) external view returns (
        address path0, 
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address purchaseToken, 
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function executeSwapOrder(address, uint256, address payable) external;
    function executeDecreaseOrder(address, uint256, address payable) external;
    function executeIncreaseOrder(address, uint256, address payable) external;
}
          

contracts/core/interfaces/IRouter.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IRouter {
    function addPlugin(address _plugin) external;
    function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external;
    function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external;
}
          

contracts/core/interfaces/IVault.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IVaultUtils.sol";

interface IVault {
    function isInitialized() external view returns (bool);
    function isSwapEnabled() external view returns (bool);
    function isLeverageEnabled() external view returns (bool);

    function setVaultUtils(IVaultUtils _vaultUtils) external;
    function setError(uint256 _errorCode, string calldata _error) external;

    function router() external view returns (address);
    function usdk() external view returns (address);
    function gov() external view returns (address);

    function whitelistedTokenCount() external view returns (uint256);
    function maxLeverage() external view returns (uint256);

    function minProfitTime() external view returns (uint256);
    function hasDynamicFees() external view returns (bool);
    function fundingInterval() external view returns (uint256);
    function totalTokenWeights() external view returns (uint256);
    function getTargetUsdkAmount(address _token) external view returns (uint256);

    function inManagerMode() external view returns (bool);
    function inPrivateLiquidationMode() external view returns (bool);

    function maxGasPrice() external view returns (uint256);

    function approvedRouters(address _account, address _router) external view returns (bool);
    function isLiquidator(address _account) external view returns (bool);
    function isManager(address _account) external view returns (bool);

    function minProfitBasisPoints(address _token) external view returns (uint256);
    function tokenBalances(address _token) external view returns (uint256);
    function lastFundingTimes(address _token) external view returns (uint256);

    function setMaxLeverage(uint256 _maxLeverage) external;
    function setInManagerMode(bool _inManagerMode) external;
    function setManager(address _manager, bool _isManager) external;
    function setIsSwapEnabled(bool _isSwapEnabled) external;
    function setIsLeverageEnabled(bool _isLeverageEnabled) external;
    function setMaxGasPrice(uint256 _maxGasPrice) external;
    function setUsdkAmount(address _token, uint256 _amount) external;
    function setBufferAmount(address _token, uint256 _amount) external;
    function setMaxGlobalShortSize(address _token, uint256 _amount) external;
    function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
    function setLiquidator(address _liquidator, bool _isActive) external;

    function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;

    function setFees(
        uint256 _taxBasisPoints,
        uint256 _stableTaxBasisPoints,
        uint256 _mintBurnFeeBasisPoints,
        uint256 _swapFeeBasisPoints,
        uint256 _stableSwapFeeBasisPoints,
        uint256 _marginFeeBasisPoints,
        uint256 _liquidationFeeUsd,
        uint256 _minProfitTime,
        bool _hasDynamicFees
    ) external;

    function setTokenConfig(
        address _token,
        uint256 _tokenDecimals,
        uint256 _redemptionBps,
        uint256 _minProfitBps,
        uint256 _maxUsdkAmount,
        bool _isStable,
        bool _isShortable
    ) external;

    function setPriceFeed(address _priceFeed) external;
    function withdrawFees(address _token, address _receiver) external returns (uint256);

    function directPoolDeposit(address _token) external;
    function buyUSDK(address _token, address _receiver) external returns (uint256);
    function sellUSDK(address _token, address _receiver) external returns (uint256);
    function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
    function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
    function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);

    function priceFeed() external view returns (address);
    function fundingRateFactor() external view returns (uint256);
    function stableFundingRateFactor() external view returns (uint256);
    function cumulativeFundingRates(address _token) external view returns (uint256);
    function getNextFundingRate(address _token) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);

    function liquidationFeeUsd() external view returns (uint256);
    function taxBasisPoints() external view returns (uint256);
    function stableTaxBasisPoints() external view returns (uint256);
    function mintBurnFeeBasisPoints() external view returns (uint256);
    function swapFeeBasisPoints() external view returns (uint256);
    function stableSwapFeeBasisPoints() external view returns (uint256);
    function marginFeeBasisPoints() external view returns (uint256);

    function allWhitelistedTokensLength() external view returns (uint256);
    function allWhitelistedTokens(uint256) external view returns (address);
    function whitelistedTokens(address _token) external view returns (bool);
    function stableTokens(address _token) external view returns (bool);
    function shortableTokens(address _token) external view returns (bool);
    function feeReserves(address _token) external view returns (uint256);
    function globalShortSizes(address _token) external view returns (uint256);
    function globalShortAveragePrices(address _token) external view returns (uint256);
    function maxGlobalShortSizes(address _token) external view returns (uint256);
    function tokenDecimals(address _token) external view returns (uint256);
    function tokenWeights(address _token) external view returns (uint256);
    function guaranteedUsd(address _token) external view returns (uint256);
    function poolAmounts(address _token) external view returns (uint256);
    function bufferAmounts(address _token) external view returns (uint256);
    function reservedAmounts(address _token) external view returns (uint256);
    function usdkAmounts(address _token) external view returns (uint256);
    function maxUsdkAmounts(address _token) external view returns (uint256);
    function getRedemptionAmount(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getMaxPrice(address _token) external view returns (uint256);
    function getMinPrice(address _token) external view returns (uint256);

    function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
    function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
          

contracts/core/interfaces/IVaultUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IVaultUtils {
    function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
    function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
    function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
    function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
    function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
    function getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
          

contracts/libraries/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
          

contracts/libraries/token/SafeERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20.sol";
import "../math/SafeMath.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 SafeMath for uint256;
    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'
        // solhint-disable-next-line max-line-length
        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).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(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
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
          

contracts/libraries/utils/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
          

contracts/libraries/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @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].
 */
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 () internal {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

contracts/tokens/interfaces/IWETH.sol

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
          

contracts/core/interfaces/IExecutionFee.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IExecutionFee {
    function setMinExecutionFee(uint256 _minExecutionFee) external;
}

          

contracts/libraries/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

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

contracts/core/interfaces/IOrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IOrderBook {
	function getSwapOrder(address _account, uint256 _orderIndex) external view returns (
        address path0, 
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address purchaseToken, 
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function executeSwapOrder(address, uint256, address payable) external;
    function executeDecreaseOrder(address, uint256, address payable) external;
    function executeIncreaseOrder(address, uint256, address payable) external;
}
          

contracts/core/interfaces/IRouter.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IRouter {
    function addPlugin(address _plugin) external;
    function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external;
    function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external;
}
          

contracts/core/interfaces/IVault.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IVaultUtils.sol";

interface IVault {
    function isInitialized() external view returns (bool);
    function isSwapEnabled() external view returns (bool);
    function isLeverageEnabled() external view returns (bool);

    function setVaultUtils(IVaultUtils _vaultUtils) external;
    function setError(uint256 _errorCode, string calldata _error) external;

    function router() external view returns (address);
    function usdk() external view returns (address);
    function gov() external view returns (address);

    function whitelistedTokenCount() external view returns (uint256);
    function maxLeverage() external view returns (uint256);

    function minProfitTime() external view returns (uint256);
    function hasDynamicFees() external view returns (bool);
    function fundingInterval() external view returns (uint256);
    function totalTokenWeights() external view returns (uint256);
    function getTargetUsdkAmount(address _token) external view returns (uint256);

    function inManagerMode() external view returns (bool);
    function inPrivateLiquidationMode() external view returns (bool);

    function maxGasPrice() external view returns (uint256);

    function approvedRouters(address _account, address _router) external view returns (bool);
    function isLiquidator(address _account) external view returns (bool);
    function isManager(address _account) external view returns (bool);

    function minProfitBasisPoints(address _token) external view returns (uint256);
    function tokenBalances(address _token) external view returns (uint256);
    function lastFundingTimes(address _token) external view returns (uint256);

    function setMaxLeverage(uint256 _maxLeverage) external;
    function setInManagerMode(bool _inManagerMode) external;
    function setManager(address _manager, bool _isManager) external;
    function setIsSwapEnabled(bool _isSwapEnabled) external;
    function setIsLeverageEnabled(bool _isLeverageEnabled) external;
    function setMaxGasPrice(uint256 _maxGasPrice) external;
    function setUsdkAmount(address _token, uint256 _amount) external;
    function setBufferAmount(address _token, uint256 _amount) external;
    function setMaxGlobalShortSize(address _token, uint256 _amount) external;
    function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
    function setLiquidator(address _liquidator, bool _isActive) external;

    function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;

    function setFees(
        uint256 _taxBasisPoints,
        uint256 _stableTaxBasisPoints,
        uint256 _mintBurnFeeBasisPoints,
        uint256 _swapFeeBasisPoints,
        uint256 _stableSwapFeeBasisPoints,
        uint256 _marginFeeBasisPoints,
        uint256 _liquidationFeeUsd,
        uint256 _minProfitTime,
        bool _hasDynamicFees
    ) external;

    function setTokenConfig(
        address _token,
        uint256 _tokenDecimals,
        uint256 _redemptionBps,
        uint256 _minProfitBps,
        uint256 _maxUsdkAmount,
        bool _isStable,
        bool _isShortable
    ) external;

    function setPriceFeed(address _priceFeed) external;
    function withdrawFees(address _token, address _receiver) external returns (uint256);

    function directPoolDeposit(address _token) external;
    function buyUSDK(address _token, address _receiver) external returns (uint256);
    function sellUSDK(address _token, address _receiver) external returns (uint256);
    function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
    function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
    function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);

    function priceFeed() external view returns (address);
    function fundingRateFactor() external view returns (uint256);
    function stableFundingRateFactor() external view returns (uint256);
    function cumulativeFundingRates(address _token) external view returns (uint256);
    function getNextFundingRate(address _token) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);

    function liquidationFeeUsd() external view returns (uint256);
    function taxBasisPoints() external view returns (uint256);
    function stableTaxBasisPoints() external view returns (uint256);
    function mintBurnFeeBasisPoints() external view returns (uint256);
    function swapFeeBasisPoints() external view returns (uint256);
    function stableSwapFeeBasisPoints() external view returns (uint256);
    function marginFeeBasisPoints() external view returns (uint256);

    function allWhitelistedTokensLength() external view returns (uint256);
    function allWhitelistedTokens(uint256) external view returns (address);
    function whitelistedTokens(address _token) external view returns (bool);
    function stableTokens(address _token) external view returns (bool);
    function shortableTokens(address _token) external view returns (bool);
    function feeReserves(address _token) external view returns (uint256);
    function globalShortSizes(address _token) external view returns (uint256);
    function globalShortAveragePrices(address _token) external view returns (uint256);
    function maxGlobalShortSizes(address _token) external view returns (uint256);
    function tokenDecimals(address _token) external view returns (uint256);
    function tokenWeights(address _token) external view returns (uint256);
    function guaranteedUsd(address _token) external view returns (uint256);
    function poolAmounts(address _token) external view returns (uint256);
    function bufferAmounts(address _token) external view returns (uint256);
    function reservedAmounts(address _token) external view returns (uint256);
    function usdkAmounts(address _token) external view returns (uint256);
    function maxUsdkAmounts(address _token) external view returns (uint256);
    function getRedemptionAmount(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getMaxPrice(address _token) external view returns (uint256);
    function getMinPrice(address _token) external view returns (uint256);

    function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
    function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
          

contracts/core/interfaces/IVaultUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IVaultUtils {
    function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
    function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
    function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
    function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
    function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
    function getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
          

contracts/libraries/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
          

contracts/libraries/token/SafeERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20.sol";
import "../math/SafeMath.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 SafeMath for uint256;
    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'
        // solhint-disable-next-line max-line-length
        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).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(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
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
          

contracts/libraries/utils/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
          

contracts/libraries/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @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].
 */
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 () internal {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

contracts/tokens/interfaces/IWETH.sol

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
          

contracts/core/interfaces/IExecutionFee.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IExecutionFee {
    function setMinExecutionFee(uint256 _minExecutionFee) external;
}

          

contracts/core/interfaces/IOrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IOrderBook {
	function getSwapOrder(address _account, uint256 _orderIndex) external view returns (
        address path0, 
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address purchaseToken, 
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function executeSwapOrder(address, uint256, address payable) external;
    function executeDecreaseOrder(address, uint256, address payable) external;
    function executeIncreaseOrder(address, uint256, address payable) external;
}
          

contracts/core/interfaces/IRouter.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IRouter {
    function addPlugin(address _plugin) external;
    function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external;
    function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external;
}
          

contracts/core/interfaces/IVault.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IVaultUtils.sol";

interface IVault {
    function isInitialized() external view returns (bool);
    function isSwapEnabled() external view returns (bool);
    function isLeverageEnabled() external view returns (bool);

    function setVaultUtils(IVaultUtils _vaultUtils) external;
    function setError(uint256 _errorCode, string calldata _error) external;

    function router() external view returns (address);
    function usdk() external view returns (address);
    function gov() external view returns (address);

    function whitelistedTokenCount() external view returns (uint256);
    function maxLeverage() external view returns (uint256);

    function minProfitTime() external view returns (uint256);
    function hasDynamicFees() external view returns (bool);
    function fundingInterval() external view returns (uint256);
    function totalTokenWeights() external view returns (uint256);
    function getTargetUsdkAmount(address _token) external view returns (uint256);

    function inManagerMode() external view returns (bool);
    function inPrivateLiquidationMode() external view returns (bool);

    function maxGasPrice() external view returns (uint256);

    function approvedRouters(address _account, address _router) external view returns (bool);
    function isLiquidator(address _account) external view returns (bool);
    function isManager(address _account) external view returns (bool);

    function minProfitBasisPoints(address _token) external view returns (uint256);
    function tokenBalances(address _token) external view returns (uint256);
    function lastFundingTimes(address _token) external view returns (uint256);

    function setMaxLeverage(uint256 _maxLeverage) external;
    function setInManagerMode(bool _inManagerMode) external;
    function setManager(address _manager, bool _isManager) external;
    function setIsSwapEnabled(bool _isSwapEnabled) external;
    function setIsLeverageEnabled(bool _isLeverageEnabled) external;
    function setMaxGasPrice(uint256 _maxGasPrice) external;
    function setUsdkAmount(address _token, uint256 _amount) external;
    function setBufferAmount(address _token, uint256 _amount) external;
    function setMaxGlobalShortSize(address _token, uint256 _amount) external;
    function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
    function setLiquidator(address _liquidator, bool _isActive) external;

    function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;

    function setFees(
        uint256 _taxBasisPoints,
        uint256 _stableTaxBasisPoints,
        uint256 _mintBurnFeeBasisPoints,
        uint256 _swapFeeBasisPoints,
        uint256 _stableSwapFeeBasisPoints,
        uint256 _marginFeeBasisPoints,
        uint256 _liquidationFeeUsd,
        uint256 _minProfitTime,
        bool _hasDynamicFees
    ) external;

    function setTokenConfig(
        address _token,
        uint256 _tokenDecimals,
        uint256 _redemptionBps,
        uint256 _minProfitBps,
        uint256 _maxUsdkAmount,
        bool _isStable,
        bool _isShortable
    ) external;

    function setPriceFeed(address _priceFeed) external;
    function withdrawFees(address _token, address _receiver) external returns (uint256);

    function directPoolDeposit(address _token) external;
    function buyUSDK(address _token, address _receiver) external returns (uint256);
    function sellUSDK(address _token, address _receiver) external returns (uint256);
    function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
    function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
    function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);

    function priceFeed() external view returns (address);
    function fundingRateFactor() external view returns (uint256);
    function stableFundingRateFactor() external view returns (uint256);
    function cumulativeFundingRates(address _token) external view returns (uint256);
    function getNextFundingRate(address _token) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);

    function liquidationFeeUsd() external view returns (uint256);
    function taxBasisPoints() external view returns (uint256);
    function stableTaxBasisPoints() external view returns (uint256);
    function mintBurnFeeBasisPoints() external view returns (uint256);
    function swapFeeBasisPoints() external view returns (uint256);
    function stableSwapFeeBasisPoints() external view returns (uint256);
    function marginFeeBasisPoints() external view returns (uint256);

    function allWhitelistedTokensLength() external view returns (uint256);
    function allWhitelistedTokens(uint256) external view returns (address);
    function whitelistedTokens(address _token) external view returns (bool);
    function stableTokens(address _token) external view returns (bool);
    function shortableTokens(address _token) external view returns (bool);
    function feeReserves(address _token) external view returns (uint256);
    function globalShortSizes(address _token) external view returns (uint256);
    function globalShortAveragePrices(address _token) external view returns (uint256);
    function maxGlobalShortSizes(address _token) external view returns (uint256);
    function tokenDecimals(address _token) external view returns (uint256);
    function tokenWeights(address _token) external view returns (uint256);
    function guaranteedUsd(address _token) external view returns (uint256);
    function poolAmounts(address _token) external view returns (uint256);
    function bufferAmounts(address _token) external view returns (uint256);
    function reservedAmounts(address _token) external view returns (uint256);
    function usdkAmounts(address _token) external view returns (uint256);
    function maxUsdkAmounts(address _token) external view returns (uint256);
    function getRedemptionAmount(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getMaxPrice(address _token) external view returns (uint256);
    function getMinPrice(address _token) external view returns (uint256);

    function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
    function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
          

contracts/core/interfaces/IVaultUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IVaultUtils {
    function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
    function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
    function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
    function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
    function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
    function getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
          

contracts/libraries/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
          

contracts/libraries/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

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

contracts/libraries/token/SafeERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20.sol";
import "../math/SafeMath.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 SafeMath for uint256;
    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'
        // solhint-disable-next-line max-line-length
        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).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(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
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
          

contracts/libraries/utils/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
          

contracts/libraries/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @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].
 */
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 () internal {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

contracts/tokens/interfaces/IWETH.sol

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
          

contracts/core/interfaces/IExecutionFee.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IExecutionFee {
    function setMinExecutionFee(uint256 _minExecutionFee) external;
}

          

contracts/libraries/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

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

contracts/core/interfaces/IOrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IOrderBook {
	function getSwapOrder(address _account, uint256 _orderIndex) external view returns (
        address path0, 
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address purchaseToken, 
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function executeSwapOrder(address, uint256, address payable) external;
    function executeDecreaseOrder(address, uint256, address payable) external;
    function executeIncreaseOrder(address, uint256, address payable) external;
}
          

contracts/core/interfaces/IRouter.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IRouter {
    function addPlugin(address _plugin) external;
    function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external;
    function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external;
}
          

contracts/core/interfaces/IVault.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IVaultUtils.sol";

interface IVault {
    function isInitialized() external view returns (bool);
    function isSwapEnabled() external view returns (bool);
    function isLeverageEnabled() external view returns (bool);

    function setVaultUtils(IVaultUtils _vaultUtils) external;
    function setError(uint256 _errorCode, string calldata _error) external;

    function router() external view returns (address);
    function usdk() external view returns (address);
    function gov() external view returns (address);

    function whitelistedTokenCount() external view returns (uint256);
    function maxLeverage() external view returns (uint256);

    function minProfitTime() external view returns (uint256);
    function hasDynamicFees() external view returns (bool);
    function fundingInterval() external view returns (uint256);
    function totalTokenWeights() external view returns (uint256);
    function getTargetUsdkAmount(address _token) external view returns (uint256);

    function inManagerMode() external view returns (bool);
    function inPrivateLiquidationMode() external view returns (bool);

    function maxGasPrice() external view returns (uint256);

    function approvedRouters(address _account, address _router) external view returns (bool);
    function isLiquidator(address _account) external view returns (bool);
    function isManager(address _account) external view returns (bool);

    function minProfitBasisPoints(address _token) external view returns (uint256);
    function tokenBalances(address _token) external view returns (uint256);
    function lastFundingTimes(address _token) external view returns (uint256);

    function setMaxLeverage(uint256 _maxLeverage) external;
    function setInManagerMode(bool _inManagerMode) external;
    function setManager(address _manager, bool _isManager) external;
    function setIsSwapEnabled(bool _isSwapEnabled) external;
    function setIsLeverageEnabled(bool _isLeverageEnabled) external;
    function setMaxGasPrice(uint256 _maxGasPrice) external;
    function setUsdkAmount(address _token, uint256 _amount) external;
    function setBufferAmount(address _token, uint256 _amount) external;
    function setMaxGlobalShortSize(address _token, uint256 _amount) external;
    function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
    function setLiquidator(address _liquidator, bool _isActive) external;

    function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;

    function setFees(
        uint256 _taxBasisPoints,
        uint256 _stableTaxBasisPoints,
        uint256 _mintBurnFeeBasisPoints,
        uint256 _swapFeeBasisPoints,
        uint256 _stableSwapFeeBasisPoints,
        uint256 _marginFeeBasisPoints,
        uint256 _liquidationFeeUsd,
        uint256 _minProfitTime,
        bool _hasDynamicFees
    ) external;

    function setTokenConfig(
        address _token,
        uint256 _tokenDecimals,
        uint256 _redemptionBps,
        uint256 _minProfitBps,
        uint256 _maxUsdkAmount,
        bool _isStable,
        bool _isShortable
    ) external;

    function setPriceFeed(address _priceFeed) external;
    function withdrawFees(address _token, address _receiver) external returns (uint256);

    function directPoolDeposit(address _token) external;
    function buyUSDK(address _token, address _receiver) external returns (uint256);
    function sellUSDK(address _token, address _receiver) external returns (uint256);
    function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
    function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
    function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);

    function priceFeed() external view returns (address);
    function fundingRateFactor() external view returns (uint256);
    function stableFundingRateFactor() external view returns (uint256);
    function cumulativeFundingRates(address _token) external view returns (uint256);
    function getNextFundingRate(address _token) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);

    function liquidationFeeUsd() external view returns (uint256);
    function taxBasisPoints() external view returns (uint256);
    function stableTaxBasisPoints() external view returns (uint256);
    function mintBurnFeeBasisPoints() external view returns (uint256);
    function swapFeeBasisPoints() external view returns (uint256);
    function stableSwapFeeBasisPoints() external view returns (uint256);
    function marginFeeBasisPoints() external view returns (uint256);

    function allWhitelistedTokensLength() external view returns (uint256);
    function allWhitelistedTokens(uint256) external view returns (address);
    function whitelistedTokens(address _token) external view returns (bool);
    function stableTokens(address _token) external view returns (bool);
    function shortableTokens(address _token) external view returns (bool);
    function feeReserves(address _token) external view returns (uint256);
    function globalShortSizes(address _token) external view returns (uint256);
    function globalShortAveragePrices(address _token) external view returns (uint256);
    function maxGlobalShortSizes(address _token) external view returns (uint256);
    function tokenDecimals(address _token) external view returns (uint256);
    function tokenWeights(address _token) external view returns (uint256);
    function guaranteedUsd(address _token) external view returns (uint256);
    function poolAmounts(address _token) external view returns (uint256);
    function bufferAmounts(address _token) external view returns (uint256);
    function reservedAmounts(address _token) external view returns (uint256);
    function usdkAmounts(address _token) external view returns (uint256);
    function maxUsdkAmounts(address _token) external view returns (uint256);
    function getRedemptionAmount(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getMaxPrice(address _token) external view returns (uint256);
    function getMinPrice(address _token) external view returns (uint256);

    function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
    function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
          

contracts/core/interfaces/IVaultUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IVaultUtils {
    function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
    function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
    function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
    function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
    function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
    function getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
          

contracts/libraries/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
          

contracts/libraries/token/SafeERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20.sol";
import "../math/SafeMath.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 SafeMath for uint256;
    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'
        // solhint-disable-next-line max-line-length
        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).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(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
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
          

contracts/libraries/utils/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
          

contracts/libraries/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @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].
 */
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 () internal {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

contracts/tokens/interfaces/IWETH.sol

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
          

contracts/core/interfaces/IExecutionFee.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IExecutionFee {
    function setMinExecutionFee(uint256 _minExecutionFee) external;
}

          

contracts/libraries/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

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

contracts/core/interfaces/IOrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IOrderBook {
	function getSwapOrder(address _account, uint256 _orderIndex) external view returns (
        address path0, 
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address purchaseToken, 
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function executeSwapOrder(address, uint256, address payable) external;
    function executeDecreaseOrder(address, uint256, address payable) external;
    function executeIncreaseOrder(address, uint256, address payable) external;
}
          

contracts/core/interfaces/IRouter.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IRouter {
    function addPlugin(address _plugin) external;
    function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external;
    function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external;
}
          

contracts/core/interfaces/IVault.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IVaultUtils.sol";

interface IVault {
    function isInitialized() external view returns (bool);
    function isSwapEnabled() external view returns (bool);
    function isLeverageEnabled() external view returns (bool);

    function setVaultUtils(IVaultUtils _vaultUtils) external;
    function setError(uint256 _errorCode, string calldata _error) external;

    function router() external view returns (address);
    function usdk() external view returns (address);
    function gov() external view returns (address);

    function whitelistedTokenCount() external view returns (uint256);
    function maxLeverage() external view returns (uint256);

    function minProfitTime() external view returns (uint256);
    function hasDynamicFees() external view returns (bool);
    function fundingInterval() external view returns (uint256);
    function totalTokenWeights() external view returns (uint256);
    function getTargetUsdkAmount(address _token) external view returns (uint256);

    function inManagerMode() external view returns (bool);
    function inPrivateLiquidationMode() external view returns (bool);

    function maxGasPrice() external view returns (uint256);

    function approvedRouters(address _account, address _router) external view returns (bool);
    function isLiquidator(address _account) external view returns (bool);
    function isManager(address _account) external view returns (bool);

    function minProfitBasisPoints(address _token) external view returns (uint256);
    function tokenBalances(address _token) external view returns (uint256);
    function lastFundingTimes(address _token) external view returns (uint256);

    function setMaxLeverage(uint256 _maxLeverage) external;
    function setInManagerMode(bool _inManagerMode) external;
    function setManager(address _manager, bool _isManager) external;
    function setIsSwapEnabled(bool _isSwapEnabled) external;
    function setIsLeverageEnabled(bool _isLeverageEnabled) external;
    function setMaxGasPrice(uint256 _maxGasPrice) external;
    function setUsdkAmount(address _token, uint256 _amount) external;
    function setBufferAmount(address _token, uint256 _amount) external;
    function setMaxGlobalShortSize(address _token, uint256 _amount) external;
    function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
    function setLiquidator(address _liquidator, bool _isActive) external;

    function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;

    function setFees(
        uint256 _taxBasisPoints,
        uint256 _stableTaxBasisPoints,
        uint256 _mintBurnFeeBasisPoints,
        uint256 _swapFeeBasisPoints,
        uint256 _stableSwapFeeBasisPoints,
        uint256 _marginFeeBasisPoints,
        uint256 _liquidationFeeUsd,
        uint256 _minProfitTime,
        bool _hasDynamicFees
    ) external;

    function setTokenConfig(
        address _token,
        uint256 _tokenDecimals,
        uint256 _redemptionBps,
        uint256 _minProfitBps,
        uint256 _maxUsdkAmount,
        bool _isStable,
        bool _isShortable
    ) external;

    function setPriceFeed(address _priceFeed) external;
    function withdrawFees(address _token, address _receiver) external returns (uint256);

    function directPoolDeposit(address _token) external;
    function buyUSDK(address _token, address _receiver) external returns (uint256);
    function sellUSDK(address _token, address _receiver) external returns (uint256);
    function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
    function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
    function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);

    function priceFeed() external view returns (address);
    function fundingRateFactor() external view returns (uint256);
    function stableFundingRateFactor() external view returns (uint256);
    function cumulativeFundingRates(address _token) external view returns (uint256);
    function getNextFundingRate(address _token) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);

    function liquidationFeeUsd() external view returns (uint256);
    function taxBasisPoints() external view returns (uint256);
    function stableTaxBasisPoints() external view returns (uint256);
    function mintBurnFeeBasisPoints() external view returns (uint256);
    function swapFeeBasisPoints() external view returns (uint256);
    function stableSwapFeeBasisPoints() external view returns (uint256);
    function marginFeeBasisPoints() external view returns (uint256);

    function allWhitelistedTokensLength() external view returns (uint256);
    function allWhitelistedTokens(uint256) external view returns (address);
    function whitelistedTokens(address _token) external view returns (bool);
    function stableTokens(address _token) external view returns (bool);
    function shortableTokens(address _token) external view returns (bool);
    function feeReserves(address _token) external view returns (uint256);
    function globalShortSizes(address _token) external view returns (uint256);
    function globalShortAveragePrices(address _token) external view returns (uint256);
    function maxGlobalShortSizes(address _token) external view returns (uint256);
    function tokenDecimals(address _token) external view returns (uint256);
    function tokenWeights(address _token) external view returns (uint256);
    function guaranteedUsd(address _token) external view returns (uint256);
    function poolAmounts(address _token) external view returns (uint256);
    function bufferAmounts(address _token) external view returns (uint256);
    function reservedAmounts(address _token) external view returns (uint256);
    function usdkAmounts(address _token) external view returns (uint256);
    function maxUsdkAmounts(address _token) external view returns (uint256);
    function getRedemptionAmount(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getMaxPrice(address _token) external view returns (uint256);
    function getMinPrice(address _token) external view returns (uint256);

    function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
    function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
          

contracts/core/interfaces/IVaultUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IVaultUtils {
    function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
    function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
    function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
    function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
    function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
    function getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
          

contracts/libraries/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
          

contracts/libraries/token/SafeERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20.sol";
import "../math/SafeMath.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 SafeMath for uint256;
    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'
        // solhint-disable-next-line max-line-length
        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).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(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
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
          

contracts/libraries/utils/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
          

contracts/libraries/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @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].
 */
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 () internal {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

contracts/tokens/interfaces/IWETH.sol

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
          

contracts/core/interfaces/IExecutionFee.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IExecutionFee {
    function setMinExecutionFee(uint256 _minExecutionFee) external;
}

          

contracts/core/interfaces/IOrderBook.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IOrderBook {
	function getSwapOrder(address _account, uint256 _orderIndex) external view returns (
        address path0, 
        address path1,
        address path2,
        uint256 amountIn,
        uint256 minOut,
        uint256 triggerRatio,
        bool triggerAboveThreshold,
        bool shouldUnwrap,
        uint256 executionFee
    );

    function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address purchaseToken, 
        uint256 purchaseTokenAmount,
        address collateralToken,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns (
        address collateralToken,
        uint256 collateralDelta,
        address indexToken,
        uint256 sizeDelta,
        bool isLong,
        uint256 triggerPrice,
        bool triggerAboveThreshold,
        uint256 executionFee
    );

    function executeSwapOrder(address, uint256, address payable) external;
    function executeDecreaseOrder(address, uint256, address payable) external;
    function executeIncreaseOrder(address, uint256, address payable) external;
}
          

contracts/core/interfaces/IRouter.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IRouter {
    function addPlugin(address _plugin) external;
    function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external;
    function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external;
}
          

contracts/core/interfaces/IVault.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IVaultUtils.sol";

interface IVault {
    function isInitialized() external view returns (bool);
    function isSwapEnabled() external view returns (bool);
    function isLeverageEnabled() external view returns (bool);

    function setVaultUtils(IVaultUtils _vaultUtils) external;
    function setError(uint256 _errorCode, string calldata _error) external;

    function router() external view returns (address);
    function usdk() external view returns (address);
    function gov() external view returns (address);

    function whitelistedTokenCount() external view returns (uint256);
    function maxLeverage() external view returns (uint256);

    function minProfitTime() external view returns (uint256);
    function hasDynamicFees() external view returns (bool);
    function fundingInterval() external view returns (uint256);
    function totalTokenWeights() external view returns (uint256);
    function getTargetUsdkAmount(address _token) external view returns (uint256);

    function inManagerMode() external view returns (bool);
    function inPrivateLiquidationMode() external view returns (bool);

    function maxGasPrice() external view returns (uint256);

    function approvedRouters(address _account, address _router) external view returns (bool);
    function isLiquidator(address _account) external view returns (bool);
    function isManager(address _account) external view returns (bool);

    function minProfitBasisPoints(address _token) external view returns (uint256);
    function tokenBalances(address _token) external view returns (uint256);
    function lastFundingTimes(address _token) external view returns (uint256);

    function setMaxLeverage(uint256 _maxLeverage) external;
    function setInManagerMode(bool _inManagerMode) external;
    function setManager(address _manager, bool _isManager) external;
    function setIsSwapEnabled(bool _isSwapEnabled) external;
    function setIsLeverageEnabled(bool _isLeverageEnabled) external;
    function setMaxGasPrice(uint256 _maxGasPrice) external;
    function setUsdkAmount(address _token, uint256 _amount) external;
    function setBufferAmount(address _token, uint256 _amount) external;
    function setMaxGlobalShortSize(address _token, uint256 _amount) external;
    function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
    function setLiquidator(address _liquidator, bool _isActive) external;

    function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;

    function setFees(
        uint256 _taxBasisPoints,
        uint256 _stableTaxBasisPoints,
        uint256 _mintBurnFeeBasisPoints,
        uint256 _swapFeeBasisPoints,
        uint256 _stableSwapFeeBasisPoints,
        uint256 _marginFeeBasisPoints,
        uint256 _liquidationFeeUsd,
        uint256 _minProfitTime,
        bool _hasDynamicFees
    ) external;

    function setTokenConfig(
        address _token,
        uint256 _tokenDecimals,
        uint256 _redemptionBps,
        uint256 _minProfitBps,
        uint256 _maxUsdkAmount,
        bool _isStable,
        bool _isShortable
    ) external;

    function setPriceFeed(address _priceFeed) external;
    function withdrawFees(address _token, address _receiver) external returns (uint256);

    function directPoolDeposit(address _token) external;
    function buyUSDK(address _token, address _receiver) external returns (uint256);
    function sellUSDK(address _token, address _receiver) external returns (uint256);
    function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
    function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
    function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
    function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);

    function priceFeed() external view returns (address);
    function fundingRateFactor() external view returns (uint256);
    function stableFundingRateFactor() external view returns (uint256);
    function cumulativeFundingRates(address _token) external view returns (uint256);
    function getNextFundingRate(address _token) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);

    function liquidationFeeUsd() external view returns (uint256);
    function taxBasisPoints() external view returns (uint256);
    function stableTaxBasisPoints() external view returns (uint256);
    function mintBurnFeeBasisPoints() external view returns (uint256);
    function swapFeeBasisPoints() external view returns (uint256);
    function stableSwapFeeBasisPoints() external view returns (uint256);
    function marginFeeBasisPoints() external view returns (uint256);

    function allWhitelistedTokensLength() external view returns (uint256);
    function allWhitelistedTokens(uint256) external view returns (address);
    function whitelistedTokens(address _token) external view returns (bool);
    function stableTokens(address _token) external view returns (bool);
    function shortableTokens(address _token) external view returns (bool);
    function feeReserves(address _token) external view returns (uint256);
    function globalShortSizes(address _token) external view returns (uint256);
    function globalShortAveragePrices(address _token) external view returns (uint256);
    function maxGlobalShortSizes(address _token) external view returns (uint256);
    function tokenDecimals(address _token) external view returns (uint256);
    function tokenWeights(address _token) external view returns (uint256);
    function guaranteedUsd(address _token) external view returns (uint256);
    function poolAmounts(address _token) external view returns (uint256);
    function bufferAmounts(address _token) external view returns (uint256);
    function reservedAmounts(address _token) external view returns (uint256);
    function usdkAmounts(address _token) external view returns (uint256);
    function maxUsdkAmounts(address _token) external view returns (uint256);
    function getRedemptionAmount(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getMaxPrice(address _token) external view returns (uint256);
    function getMinPrice(address _token) external view returns (uint256);

    function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
    function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
          

contracts/core/interfaces/IVaultUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IVaultUtils {
    function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
    function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
    function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
    function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
    function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
    function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
    function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
    function getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256);
    function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256);
    function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
          

contracts/libraries/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
          

contracts/libraries/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

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

contracts/libraries/token/SafeERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20.sol";
import "../math/SafeMath.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 SafeMath for uint256;
    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'
        // solhint-disable-next-line max-line-length
        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).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(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
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
          

contracts/libraries/utils/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
          

contracts/libraries/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @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].
 */
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 () internal {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

contracts/tokens/interfaces/IWETH.sol

//SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
          

Contract ABI

[{"type":"constructor","stateMutability":"nonpayable","inputs":[]},{"type":"event","name":"CancelDecreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"uint256","name":"collateralDelta","internalType":"uint256","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CancelIncreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"purchaseToken","internalType":"address","indexed":false},{"type":"uint256","name":"purchaseTokenAmount","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CancelSwapOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address[]","name":"path","internalType":"address[]","indexed":false},{"type":"uint256","name":"amountIn","internalType":"uint256","indexed":false},{"type":"uint256","name":"minOut","internalType":"uint256","indexed":false},{"type":"uint256","name":"triggerRatio","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"bool","name":"shouldUnwrap","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CreateDecreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"uint256","name":"collateralDelta","internalType":"uint256","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CreateIncreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"purchaseToken","internalType":"address","indexed":false},{"type":"uint256","name":"purchaseTokenAmount","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CreateSwapOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address[]","name":"path","internalType":"address[]","indexed":false},{"type":"uint256","name":"amountIn","internalType":"uint256","indexed":false},{"type":"uint256","name":"minOut","internalType":"uint256","indexed":false},{"type":"uint256","name":"triggerRatio","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"bool","name":"shouldUnwrap","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ExecuteDecreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"uint256","name":"collateralDelta","internalType":"uint256","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false},{"type":"uint256","name":"executionPrice","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ExecuteIncreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"purchaseToken","internalType":"address","indexed":false},{"type":"uint256","name":"purchaseTokenAmount","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false},{"type":"uint256","name":"executionPrice","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ExecuteSwapOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address[]","name":"path","internalType":"address[]","indexed":false},{"type":"uint256","name":"amountIn","internalType":"uint256","indexed":false},{"type":"uint256","name":"minOut","internalType":"uint256","indexed":false},{"type":"uint256","name":"amountOut","internalType":"uint256","indexed":false},{"type":"uint256","name":"triggerRatio","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"bool","name":"shouldUnwrap","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Initialize","inputs":[{"type":"address","name":"router","internalType":"address","indexed":false},{"type":"address","name":"vault","internalType":"address","indexed":false},{"type":"address","name":"weth","internalType":"address","indexed":false},{"type":"address","name":"usdk","internalType":"address","indexed":false},{"type":"uint256","name":"minExecutionFee","internalType":"uint256","indexed":false},{"type":"uint256","name":"minPurchaseTokenAmountUsd","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"UpdateDecreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"uint256","name":"collateralDelta","internalType":"uint256","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"UpdateGov","inputs":[{"type":"address","name":"gov","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"UpdateIncreaseOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"orderIndex","internalType":"uint256","indexed":false},{"type":"address","name":"collateralToken","internalType":"address","indexed":false},{"type":"address","name":"indexToken","internalType":"address","indexed":false},{"type":"bool","name":"isLong","internalType":"bool","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"uint256","name":"triggerPrice","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"UpdateMinExecutionFee","inputs":[{"type":"uint256","name":"minExecutionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"UpdateMinPurchaseTokenAmountUsd","inputs":[{"type":"uint256","name":"minPurchaseTokenAmountUsd","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"UpdateSwapOrder","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"uint256","name":"ordexIndex","internalType":"uint256","indexed":false},{"type":"address[]","name":"path","internalType":"address[]","indexed":false},{"type":"uint256","name":"amountIn","internalType":"uint256","indexed":false},{"type":"uint256","name":"minOut","internalType":"uint256","indexed":false},{"type":"uint256","name":"triggerRatio","internalType":"uint256","indexed":false},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool","indexed":false},{"type":"bool","name":"shouldUnwrap","internalType":"bool","indexed":false},{"type":"uint256","name":"executionFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"PRICE_PRECISION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"USDK_PRECISION","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"cancelDecreaseOrder","inputs":[{"type":"uint256","name":"_orderIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"cancelIncreaseOrder","inputs":[{"type":"uint256","name":"_orderIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"cancelMultiple","inputs":[{"type":"uint256[]","name":"_swapOrderIndexes","internalType":"uint256[]"},{"type":"uint256[]","name":"_increaseOrderIndexes","internalType":"uint256[]"},{"type":"uint256[]","name":"_decreaseOrderIndexes","internalType":"uint256[]"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"cancelSwapOrder","inputs":[{"type":"uint256","name":"_orderIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"createDecreaseOrder","inputs":[{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"address","name":"_collateralToken","internalType":"address"},{"type":"uint256","name":"_collateralDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"uint256","name":"_triggerPrice","internalType":"uint256"},{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"createIncreaseOrder","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"uint256","name":"_amountIn","internalType":"uint256"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_minOut","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"address","name":"_collateralToken","internalType":"address"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"uint256","name":"_triggerPrice","internalType":"uint256"},{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"_executionFee","internalType":"uint256"},{"type":"bool","name":"_shouldWrap","internalType":"bool"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"createSwapOrder","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"uint256","name":"_amountIn","internalType":"uint256"},{"type":"uint256","name":"_minOut","internalType":"uint256"},{"type":"uint256","name":"_triggerRatio","internalType":"uint256"},{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"_executionFee","internalType":"uint256"},{"type":"bool","name":"_shouldWrap","internalType":"bool"},{"type":"bool","name":"_shouldUnwrap","internalType":"bool"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"account","internalType":"address"},{"type":"address","name":"collateralToken","internalType":"address"},{"type":"uint256","name":"collateralDelta","internalType":"uint256"},{"type":"address","name":"indexToken","internalType":"address"},{"type":"uint256","name":"sizeDelta","internalType":"uint256"},{"type":"bool","name":"isLong","internalType":"bool"},{"type":"uint256","name":"triggerPrice","internalType":"uint256"},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"executionFee","internalType":"uint256"}],"name":"decreaseOrders","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"decreaseOrdersIndex","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeDecreaseOrder","inputs":[{"type":"address","name":"_address","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"address","name":"_feeReceiver","internalType":"address payable"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeIncreaseOrder","inputs":[{"type":"address","name":"_address","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"address","name":"_feeReceiver","internalType":"address payable"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeSwapOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"address","name":"_feeReceiver","internalType":"address payable"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"collateralToken","internalType":"address"},{"type":"uint256","name":"collateralDelta","internalType":"uint256"},{"type":"address","name":"indexToken","internalType":"address"},{"type":"uint256","name":"sizeDelta","internalType":"uint256"},{"type":"bool","name":"isLong","internalType":"bool"},{"type":"uint256","name":"triggerPrice","internalType":"uint256"},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"executionFee","internalType":"uint256"}],"name":"getDecreaseOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"purchaseToken","internalType":"address"},{"type":"uint256","name":"purchaseTokenAmount","internalType":"uint256"},{"type":"address","name":"collateralToken","internalType":"address"},{"type":"address","name":"indexToken","internalType":"address"},{"type":"uint256","name":"sizeDelta","internalType":"uint256"},{"type":"bool","name":"isLong","internalType":"bool"},{"type":"uint256","name":"triggerPrice","internalType":"uint256"},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"executionFee","internalType":"uint256"}],"name":"getIncreaseOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"path0","internalType":"address"},{"type":"address","name":"path1","internalType":"address"},{"type":"address","name":"path2","internalType":"address"},{"type":"uint256","name":"amountIn","internalType":"uint256"},{"type":"uint256","name":"minOut","internalType":"uint256"},{"type":"uint256","name":"triggerRatio","internalType":"uint256"},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool"},{"type":"bool","name":"shouldUnwrap","internalType":"bool"},{"type":"uint256","name":"executionFee","internalType":"uint256"}],"name":"getSwapOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getUsdkMinPrice","inputs":[{"type":"address","name":"_otherToken","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"gov","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"account","internalType":"address"},{"type":"address","name":"purchaseToken","internalType":"address"},{"type":"uint256","name":"purchaseTokenAmount","internalType":"uint256"},{"type":"address","name":"collateralToken","internalType":"address"},{"type":"address","name":"indexToken","internalType":"address"},{"type":"uint256","name":"sizeDelta","internalType":"uint256"},{"type":"bool","name":"isLong","internalType":"bool"},{"type":"uint256","name":"triggerPrice","internalType":"uint256"},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"executionFee","internalType":"uint256"}],"name":"increaseOrders","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"increaseOrdersIndex","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"_router","internalType":"address"},{"type":"address","name":"_vault","internalType":"address"},{"type":"address","name":"_weth","internalType":"address"},{"type":"address","name":"_usdk","internalType":"address"},{"type":"uint256","name":"_minExecutionFee","internalType":"uint256"},{"type":"uint256","name":"_minPurchaseTokenAmountUsd","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isInitialized","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"minExecutionFee","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"minPurchaseTokenAmountUsd","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"router","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setGov","inputs":[{"type":"address","name":"_gov","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setMinExecutionFee","inputs":[{"type":"uint256","name":"_minExecutionFee","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setMinPurchaseTokenAmountUsd","inputs":[{"type":"uint256","name":"_minPurchaseTokenAmountUsd","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"account","internalType":"address"},{"type":"uint256","name":"amountIn","internalType":"uint256"},{"type":"uint256","name":"minOut","internalType":"uint256"},{"type":"uint256","name":"triggerRatio","internalType":"uint256"},{"type":"bool","name":"triggerAboveThreshold","internalType":"bool"},{"type":"bool","name":"shouldUnwrap","internalType":"bool"},{"type":"uint256","name":"executionFee","internalType":"uint256"}],"name":"swapOrders","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"swapOrdersIndex","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updateDecreaseOrder","inputs":[{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"uint256","name":"_collateralDelta","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"uint256","name":"_triggerPrice","internalType":"uint256"},{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updateIncreaseOrder","inputs":[{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"uint256","name":"_triggerPrice","internalType":"uint256"},{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updateSwapOrder","inputs":[{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"uint256","name":"_minOut","internalType":"uint256"},{"type":"uint256","name":"_triggerRatio","internalType":"uint256"},{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"usdk","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"},{"type":"bool","name":"","internalType":"bool"}],"name":"validatePositionOrderPrice","inputs":[{"type":"bool","name":"_triggerAboveThreshold","internalType":"bool"},{"type":"uint256","name":"_triggerPrice","internalType":"uint256"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"bool","name":"_maximizePrice","internalType":"bool"},{"type":"bool","name":"_raise","internalType":"bool"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"validateSwapOrderPriceWithTriggerAboveThreshold","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"uint256","name":"_triggerRatio","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"vault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"weth","inputs":[]},{"type":"receive","stateMutability":"payable"}]
              

Contract Creation Code

0x6080604052600e805460ff1916905534801561001a57600080fd5b506001600055600780546001600160a01b031916331790556153c4806100416000396000f3fe6080604052600436106101c35760003560e01c8062cf066b1461022a578063026032ee1461026f57806307c7edc3146102fa5780630d5cc9381461033d57806311d9444a1461036757806312d43a51146103aa578063269ae6c2146103db5780632b7d6290146104a6578063392e53cd146105465780633fc8cef31461056f57806347e0bbd0146105845780634c54f0b0146105ae57806363ae21031461061857806379221fa21461062d578063807c5600146106ac5780638de10c2e1461085e57806395082d25146108735780639983ee1b146108885780639e71b0f0146108c6578063a397ea54146108f0578063aec2245514610934578063b142a4b014610967578063bf73afc114610a51578063c16cde8a14610a84578063c4a1821b14610ad4578063c86b0f7d14610b84578063ced8f6c414610bc2578063cfad57a214610bd7578063d0d40cd614610c0a578063d38ab51914610c9d578063d3bab1d114610ce0578063d566d0ca14610d74578063d7c41c7914610da7578063d858b24514610e00578063f2d2e01b14610e15578063f882ac0714610ea9578063f887ea4014610ed3578063fbfa77cf14610ee8578063fc2cee6214610efd57610225565b36610225576008546001600160a01b03163314610223576040805162461bcd60e51b815260206004820152601960248201527827b93232b92137b7b59d1034b73b30b634b21039b2b73232b960391b604482015290519081900360640190fd5b005b600080fd5b34801561023657600080fd5b5061025d6004803603602081101561024d57600080fd5b50356001600160a01b0316610f27565b60408051918252519081900360200190f35b34801561027b57600080fd5b506102a86004803603604081101561029257600080fd5b506001600160a01b038135169060200135610f39565b604080516001600160a01b03998a168152602081019890985295909716868601526060860193909352901515608085015260a0840152151560c083015260e08201929092529051908190036101000190f35b34801561030657600080fd5b506102236004803603606081101561031d57600080fd5b506001600160a01b0381358116916020810135916040909101351661100c565b34801561034957600080fd5b506102236004803603602081101561036057600080fd5b5035611417565b34801561037357600080fd5b506102236004803603606081101561038a57600080fd5b506001600160a01b038135811691602081013591604090910135166114a8565b3480156103b657600080fd5b506103bf611857565b604080516001600160a01b039092168252519081900360200190f35b61022360048036036101008110156103f257600080fd5b810190602081018135600160201b81111561040c57600080fd5b82018360208201111561041e57600080fd5b803590602001918460208302840111600160201b8311171561043f57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955050823593505050602081013590604081013590606081013515159060808101359060a081013515159060c001351515611866565b3480156104b257600080fd5b506104df600480360360408110156104c957600080fd5b506001600160a01b038135169060200135611bef565b604080516001600160a01b039b8c168152998b1660208b015289810198909852958916606089015293909716608087015260a0860191909152151560c085015260e08401949094529215156101008301526101208201929092529051908190036101400190f35b34801561055257600080fd5b5061055b611c61565b604080519115158252519081900360200190f35b34801561057b57600080fd5b506103bf611c6a565b34801561059057600080fd5b50610223600480360360208110156105a757600080fd5b5035611c79565b3480156105ba57600080fd5b506105ff600480360360a08110156105d157600080fd5b5080351515906020810135906001600160a01b03604082013516906060810135151590608001351515611f83565b6040805192835290151560208301528051918290030190f35b34801561062457600080fd5b5061025d6120ec565b34801561063957600080fd5b506106666004803603604081101561065057600080fd5b506001600160a01b0381351690602001356120f2565b604080516001600160a01b039098168852602088019690965286860194909452606086019290925215156080850152151560a084015260c0830152519081900360e00190f35b3480156106b857600080fd5b50610223600480360360608110156106cf57600080fd5b810190602081018135600160201b8111156106e957600080fd5b8201836020820111156106fb57600080fd5b803590602001918460208302840111600160201b8311171561071c57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b81111561076b57600080fd5b82018360208201111561077d57600080fd5b803590602001918460208302840111600160201b8311171561079e57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b8111156107ed57600080fd5b8201836020820111156107ff57600080fd5b803590602001918460208302840111600160201b8311171561082057600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612146945050505050565b34801561086a57600080fd5b5061025d6121de565b34801561087f57600080fd5b5061025d6121e4565b34801561089457600080fd5b50610223600480360360808110156108ab57600080fd5b508035906020810135906040810135906060013515156121f4565b3480156108d257600080fd5b50610223600480360360208110156108e957600080fd5b503561234c565b3480156108fc57600080fd5b50610223600480360360a081101561091357600080fd5b508035906020810135906040810135906060810135906080013515156125be565b34801561094057600080fd5b5061025d6004803603602081101561095757600080fd5b50356001600160a01b0316612726565b610223600480360361016081101561097e57600080fd5b810190602081018135600160201b81111561099857600080fd5b8201836020820111156109aa57600080fd5b803590602001918460208302840111600160201b831117156109cb57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295505082359350506001600160a01b036020830135811692604081013592506060810135916080820135169060a081013515159060c08101359060e08101351515906101008101359061012001351515612738565b348015610a5d57600080fd5b5061025d60048036036020811015610a7457600080fd5b50356001600160a01b0316612b3a565b610223600480360360e0811015610a9a57600080fd5b506001600160a01b03813581169160208101359160408201351690606081013590608081013515159060a08101359060c001351515612ce4565b348015610ae057600080fd5b5061055b60048036036040811015610af757600080fd5b810190602081018135600160201b811115610b1157600080fd5b820183602082011115610b2357600080fd5b803590602001918460208302840111600160201b83111715610b4457600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295505091359250612d95915050565b348015610b9057600080fd5b5061022360048036036080811015610ba757600080fd5b50803590602081013590604081013590606001351515612fac565b348015610bce57600080fd5b5061025d613175565b348015610be357600080fd5b5061022360048036036020811015610bfa57600080fd5b50356001600160a01b0316613181565b348015610c1657600080fd5b50610c4360048036036040811015610c2d57600080fd5b506001600160a01b03813516906020013561322b565b604080516001600160a01b039a8b168152988a1660208a015296909816878701526060870194909452608086019290925260a0850152151560c0840152151560e08301526101008201929092529051908190036101200190f35b348015610ca957600080fd5b5061022360048036036060811015610cc057600080fd5b506001600160a01b038135811691602081013591604090910135166133e8565b348015610cec57600080fd5b50610d1960048036036040811015610d0357600080fd5b506001600160a01b038135169060200135613851565b604080516001600160a01b039a8b1681526020810199909952968916888801529490971660608701526080860192909252151560a085015260c084015292151560e08301526101008201929092529051908190036101200190f35b348015610d8057600080fd5b5061025d60048036036020811015610d9757600080fd5b50356001600160a01b0316613937565b348015610db357600080fd5b50610223600480360360c0811015610dca57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060808101359060a00135613949565b348015610e0c57600080fd5b506103bf613ab8565b348015610e2157600080fd5b50610e4e60048036036040811015610e3857600080fd5b506001600160a01b038135169060200135613ac7565b604080516001600160a01b039a8b168152988a1660208a0152888101979097529490971660608701526080860192909252151560a085015260c084015292151560e08301526101008201929092529051908190036101200190f35b348015610eb557600080fd5b5061022360048036036020811015610ecc57600080fd5b5035613b31565b348015610edf57600080fd5b506103bf613e6e565b348015610ef457600080fd5b506103bf613e7d565b348015610f0957600080fd5b5061022360048036036020811015610f2057600080fd5b5035613e8c565b60066020526000908152604090205481565b600080600080600080600080610f4d614fd0565b505050506001600160a01b03968716600090815260036020818152604080842099845298815291889020885161012081018a5281548b16815260018201548b1693810184905260028201549981018a9052918101549099166060820181905260048a01546080830181905260058b015460ff908116151560a0850181905260068d015460c0860181905260078e0154909216151560e086018190526008909d0154610100909501859052949c9a9b929a91995093975092955093509150565b60026000541415611052576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561105f61501c565b6001600160a01b038085166000908152600560209081526040808320878452825291829020825161010081018452815490941684526001810180548451818502810185019095528085529193858401939092908301828280156110eb57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116110cd575b5050509183525050600282015460208201526003820154604082015260048201546060820152600582015460ff8082161515608084015261010090910416151560a082015260069091015460c09091015280519091506001600160a01b0316611189576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b8060a00151156111e0576111a581602001518260800151612d95565b6111e05760405162461bcd60e51b81526004018080602001828103825260268152602001806152f16026913960400191505060405180910390fd5b6001600160a01b0384166000908152600560209081526040808320868452909152812080546001600160a01b03191681559061121f600183018261506e565b50600060028201819055600382018190556004820181905560058201805461ffff191690556006909101819055600b54604083015160208401518051611292946001600160a01b03909416939061127257fe5b60200260200101516001600160a01b0316613f1d9092919063ffffffff16565b600854602082015180516000926001600160a01b0316919060001981019081106112b857fe5b60200260200101516001600160a01b03161480156112d757508160c001515b15611304576112ef8260200151836060015130613f74565b90506112ff8183600001516140a3565b61131e565b61131b826020015183606001518460000151613f74565b90505b61132c8260e00151846140a3565b846001600160a01b03167f7e1fe496989eea92b738a562dbf9c0ae6aa6fcf3f1ef09e95ee4f7603721706b858460200151856040015186606001518688608001518960a001518a60c001518b60e00151604051808a8152602001806020018981526020018881526020018781526020018681526020018515158152602001841515815260200183815260200182810382528a818151815260200191508051906020019060200280838360005b838110156113f05781810151838201526020016113d8565b505050509050019a505050505050505050505060405180910390a250506001600055505050565b6007546001600160a01b0316331461146d576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600d8190556040805182815290517fe46d9daf6d25f7615efa1d0183b90ac6759d85014b598e409aadf0fd918d59a69181900360200190a150565b600260005414156114ee576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000556114fb614fd0565b506001600160a01b03808416600090815260036020818152604080842087855282529283902083516101208101855281548616808252600183015487169382019390935260028201549481019490945291820154909316606083015260048101546080830152600581015460ff908116151560a0840152600682015460c0840152600782015416151560e083015260080154610100820152906115d3576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b60006115f48260e001518360c0015184606001518560a00151156001611f83565b506001600160a01b0380871660009081526003602081815260408084208a8552825280842080546001600160a01b0319908116825560018201805482169055600282018690559381018054909416909355600480840185905560058401805460ff199081169091556006850186905560078501805490911690556008909301849055600a5488518984015160608b01518b85015160808d015160a08e01518751632662166b60e01b8152958c1699860199909952928a16602485015290891660448401526064830152608482015293151560a48501523060c4850152905195965092949290931692632662166b9260e48084019382900301818787803b1580156116fd57600080fd5b505af1158015611711573d6000803e3d6000fd5b505050506040513d602081101561172757600080fd5b505160085460208501519192506001600160a01b039182169116141561175a576117558184600001516140a3565b611777565b82516020840151611777916001600160a01b039091169083613f1d565b611786836101000151856140a3565b82600001516001600160a01b03167f9a382661d6573da86db000471303be6f0b2b1bb66089b08e3c16a85d7b6e94f88685602001518660400151876060015188608001518960a001518a60c001518b60e001518c61010001518c604051808b81526020018a6001600160a01b03168152602001898152602001886001600160a01b03168152602001878152602001861515815260200185815260200184151581526020018381526020018281526020019a505050505050505050505060405180910390a25050600160005550505050565b6007546001600160a01b031681565b600260005414156118ac576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000819055885114806118c2575087516003145b611901576040805162461bcd60e51b815260206004820152601f6024820152600080516020615317833981519152604482015290519081900360640190fd5b8760018951038151811061191157fe5b60200260200101516001600160a01b03168860008151811061192f57fe5b60200260200101516001600160a01b0316141561198e576040805162461bcd60e51b815260206004820152601860248201527709ee4c8cae484deded67440d2dcecc2d8d2c840bee0c2e8d60431b604482015290519081900360640190fd5b600087116119e2576040805162461bcd60e51b815260206004820152601c60248201527b27b93232b92137b7b59d1034b73b30b634b2102fb0b6b7bab73a24b760211b604482015290519081900360640190fd5b600c54831015611a235760405162461bcd60e51b81526004018080602001828103825260258152602001806152856025913960400191505060405180910390fd5b611a2b614120565b8115611ae65760085488516001600160a01b03909116908990600090611a4d57fe5b60200260200101516001600160a01b031614611a9a5760405162461bcd60e51b81526004018080602001828103825260258152602001806152606025913960400191505060405180910390fd5b611aa48388614192565b3414611ae15760405162461bcd60e51b81526004018080602001828103825260268152602001806152cb6026913960400191505060405180910390fd5b611bd0565b823414611b245760405162461bcd60e51b815260040180806020018281038252602e815260200180615361602e913960400191505060405180910390fd5b600a5488516001600160a01b0390911690631b827878908a90600090611b4657fe5b602002602001015133308b6040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846001600160a01b03168152602001836001600160a01b03168152602001828152602001945050505050600060405180830381600087803b158015611bb757600080fd5b505af1158015611bcb573d6000803e3d6000fd5b505050505b611be0338989898989878a6141ea565b50506001600055505050505050565b6001602081815260009384526040808520909152918352912080549181015460028201546003830154600484015460058501546006860154600787015460088801546009909801546001600160a01b03998a1699978816989697958616969490951694929360ff92831693919216908a565b600e5460ff1681565b6008546001600160a01b031681565b60026000541415611cbf576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b6002600055611ccc61508f565b5033600090815260016020818152604080842085855282529283902083516101408101855281546001600160a01b039081168083529483015481169382019390935260028201549481019490945260038101548216606085015260048101549091166080840152600581015460a0840152600681015460ff908116151560c0850152600782015460e0850152600882015416151561010084015260090154610120830152611daf576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b3360009081526001602081815260408084208685528252832080546001600160a01b0319908116825592810180548416905560028101849055600381018054841690556004810180549093169092556005820183905560068201805460ff19908116909155600783018490556008808401805490921690915560099092019290925554908201516001600160a01b0390811691161415611e7357611e6e611e68826040015183610120015161419290919063ffffffff16565b336140a3565b611ea8565b611e9933826040015183602001516001600160a01b0316613f1d9092919063ffffffff16565b611ea8816101200151336140a3565b80600001516001600160a01b03167fd500f34e0ec655b7614ae42e1d9c666d5e4dde909a1297829f8c5ecf00805d328383602001518460400151856060015186608001518760a001518860c001518960e001518a61010001518b6101200151604051808b81526020018a6001600160a01b03168152602001898152602001886001600160a01b03168152602001876001600160a01b03168152602001868152602001851515815260200184815260200183151581526020018281526020019a505050505050505050505060405180910390a250506001600055565b60008060008461200b57600b54604080516340d3096b60e11b81526001600160a01b038981166004830152915191909216916381a612d6916024808301926020929190829003018186803b158015611fda57600080fd5b505afa158015611fee573d6000803e3d6000fd5b505050506040513d602081101561200457600080fd5b5051612085565b600b5460408051637092736960e11b81526001600160a01b0389811660048301529151919092169163e124e6d2916024808301926020929190829003018186803b15801561205857600080fd5b505afa15801561206c573d6000803e3d6000fd5b505050506040513d602081101561208257600080fd5b50515b90506000886120965787821061209a565b8782115b905084156120de57806120de5760405162461bcd60e51b81526004018080602001828103825260268152602001806152f16026913960400191505060405180910390fd5b909890975095505050505050565b600c5481565b600560208181526000938452604080852090915291835291208054600282015460038301546004840154948401546006909401546001600160a01b03909316949193909260ff808316926101009004169087565b60005b83518110156121765761216e84828151811061216157fe5b6020026020010151613b31565b600101612149565b5060005b82518110156121a75761219f83828151811061219257fe5b6020026020010151611c79565b60010161217a565b5060005b81518110156121d8576121d08282815181106121c357fe5b602002602001015161234c565b6001016121ab565b50505050565b600d5481565b68327cb2734119d3b7a9601e1b81565b6002600054141561223a576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000908155338152600160209081526040808320878452909152902080546001600160a01b03166122a2576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b6007810183905560088101805483151560ff19909116811790915560058201859055600382015460048301546006840154604080518a81526001600160a01b039485166020820152929093168284015260ff16151560608201526080810187905260a0810186905260c08101929092525133917f0a0360dd5c354235bbf8d386ba3b24ef8134088e0785677de1504df219d9149a919081900360e00190a250506001600055505050565b60026000541415612392576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561239f614fd0565b5033600090815260036020818152604080842085855282529283902083516101208101855281546001600160a01b03908116808352600184015482169483019490945260028301549582019590955292810154909316606083015260048301546080830152600583015460ff908116151560a0840152600684015460c0840152600784015416151560e083015260089092015461010082015290612478576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b336000818152600360208181526040808420878552909152822080546001600160a01b03199081168255600182018054821690556002820184905591810180549092169091556004810182905560058101805460ff19908116909155600682018390556007820180549091169055600801556101008201516124f9916140a3565b80600001516001600160a01b03167f1154174c82984656b028c8021671988f60a346497e56fe02554761184f82a0758383602001518460400151856060015186608001518760a001518860c001518960e001518a6101000151604051808a8152602001896001600160a01b03168152602001888152602001876001600160a01b0316815260200186815260200185151581526020018481526020018315158152602001828152602001995050505050505050505060405180910390a250506001600055565b60026000541415612604576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000908155338152600360209081526040808320888452909152902080546001600160a01b031661266c576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b6006810183905560078101805483151560ff1990911681179091556004820185905560028201869055600182015460038301546005840154604080518b81526001600160a01b0394851660208201528082018b90529290931660608301526080820188905260ff16151560a082015260c0810186905260e08101929092525133917f75781255bc71c83f89f29e5a2599f2c174a562d2cd8f2e818a47f132e728049891908190036101000190a25050600160005550505050565b60026020526000908152604090205481565b6002600054141561277e576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561278b614120565b600c548210156127cc5760405162461bcd60e51b81526004018080602001828103825260258152602001806152856025913960400191505060405180910390fd5b8015612887576008548b516001600160a01b03909116908c906000906127ee57fe5b60200260200101516001600160a01b03161461283b5760405162461bcd60e51b81526004018080602001828103825260258152602001806152606025913960400191505060405180910390fd5b612845828b614192565b34146128825760405162461bcd60e51b81526004018080602001828103825260268152602001806152cb6026913960400191505060405180910390fd5b612971565b8134146128c55760405162461bcd60e51b815260040180806020018281038252602e815260200180615361602e913960400191505060405180910390fd5b600a548b516001600160a01b0390911690631b827878908d906000906128e757fe5b602002602001015133308e6040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846001600160a01b03168152602001836001600160a01b03168152602001828152602001945050505050600060405180830381600087803b15801561295857600080fd5b505af115801561296c573d6000803e3d6000fd5b505050505b60008b60018d51038151811061298357fe5b60200260200101519050600060018d511115612a4857816001600160a01b03168d6000815181106129b057fe5b60200260200101516001600160a01b03161415612a0f576040805162461bcd60e51b815260206004820152601860248201527709ee4c8cae484deded67440d2dcecc2d8d2c840bee0c2e8d60431b604482015290519081900360640190fd5b612a36600b60009054906101000a90046001600160a01b03168d8f60008151811061127257fe5b612a418d8b30613f74565b9050612a4b565b508a5b600b5460408051630a48d5a960e01b81526001600160a01b0385811660048301526024820185905291516000939290921691630a48d5a991604480820192602092909190829003018186803b158015612aa357600080fd5b505afa158015612ab7573d6000803e3d6000fd5b505050506040513d6020811015612acd57600080fd5b5051600d54909150811015612b135760405162461bcd60e51b81526004018080602001828103825260228152602001806151bd6022913960400191505060405180910390fd5b50612b263383838b8f8e8d8d8d8d6143f9565b505060016000555050505050505050505050565b600b5460408051632c668ec160e01b81526001600160a01b038481166004830152670de0b6b3a76400006024830152915160009384931691632c668ec1916044808301926020929190829003018186803b158015612b9757600080fd5b505afa158015612bab573d6000803e3d6000fd5b505050506040513d6020811015612bc157600080fd5b5051600b54604080516340d3096b60e11b81526001600160a01b038781166004830152915193945060009391909216916381a612d6916024808301926020929190829003018186803b158015612c1657600080fd5b505afa158015612c2a573d6000803e3d6000fd5b505050506040513d6020811015612c4057600080fd5b5051600b54604080516323b95ceb60e21b81526001600160a01b03888116600483015291519394506000939190921691638ee573ac916024808301926020929190829003018186803b158015612c9557600080fd5b505afa158015612ca9573d6000803e3d6000fd5b505050506040513d6020811015612cbf57600080fd5b50519050612cdb600a82900a612cd585856146cc565b90614725565b95945050505050565b60026000541415612d2a576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b6002600055612d37614120565b600c543411612d775760405162461bcd60e51b81526004018080602001828103825260258152602001806152856025913960400191505060405180910390fd5b612d873386868a8a888888614764565b505060016000555050505050565b6000825160021480612da8575082516003145b612de7576040805162461bcd60e51b815260206004820152601f6024820152600080516020615317833981519152604482015290519081900360640190fd5b600083600081518110612df657fe5b60200260200101519050600084600186510381518110612e1257fe5b602090810291909101015160095490915060009081906001600160a01b0385811691161415612e5f57612e5887600181518110612e4b57fe5b6020026020010151612b3a565b9150612edb565b600b54604080516340d3096b60e11b81526001600160a01b038781166004830152915191909216916381a612d6916024808301926020929190829003018186803b158015612eac57600080fd5b505afa158015612ec0573d6000803e3d6000fd5b505050506040513d6020811015612ed657600080fd5b505191505b6009546001600160a01b0384811691161415612f04575068327cb2734119d3b7a9601e1b612f80565b600b5460408051637092736960e11b81526001600160a01b0386811660048301529151919092169163e124e6d2916024808301926020929190829003018186803b158015612f5157600080fd5b505afa158015612f65573d6000803e3d6000fd5b505050506040513d6020811015612f7b57600080fd5b505190505b6000612f9c83612cd58468327cb2734119d3b7a9601e1b6146cc565b8710955050505050505b92915050565b60026000541415612ff2576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000908155338152600560209081526040808320878452909152902080546001600160a01b031661305a576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b838160030181905550828160040181905550818160050160006101000a81548160ff021916908315150217905550336001600160a01b03167fa7f9f4a25eb76f5ec01b1a429d95d6a00833f0f137c88827c58799a1c1ff0dfe868360010184600201548888888860050160019054906101000a900460ff168960060154604051808981526020018060200188815260200187815260200186815260200185151581526020018415158152602001838152602001828103825289818154815260200191508054801561315457602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613136575b5050995050505050505050505060405180910390a250506001600055505050565b670de0b6b3a764000081565b6007546001600160a01b031633146131d7576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600780546001600160a01b0383166001600160a01b0319909116811790915560408051918252517fe24c39186e9137521953beaa8446e71f55b8f12296984f9d4273ceb1af728d909181900360200190a150565b600080600080600080600080600061324161501c565b6001600160a01b03808d1660009081526005602090815260408083208f8452825291829020825161010081018452815490941684526001810180548451818502810185019095528085529193858401939092908301828280156132cd57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116132af575b505050918352505060028201546020808301919091526003830154604083015260048301546060830152600583015460ff8082161515608085015261010090910416151560a083015260069092015460c0909101528101515190915061333457600061334e565b806020015160008151811061334557fe5b60200260200101515b60018260200151511161336257600061337c565b816020015160018151811061337357fe5b60200260200101515b6002836020015151116133905760006133aa565b82602001516002815181106133a157fe5b60200260200101515b8360400151846060015185608001518660a001518760c001518860e00151995099509950995099509950995099509950509295985092959850929598565b6002600054141561342e576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561343b61508f565b506001600160a01b038084166000908152600160208181526040808420878552825292839020835161014081018552815486168082529382015486169281019290925260028101549382019390935260038301548416606082015260048301549093166080840152600582015460a0840152600682015460ff908116151560c0850152600783015460e08501526008830154161515610100840152600990910154610120830152613521576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b60006135428261010001518360e0015184608001518560c001516001611f83565b506001600160a01b0380871660009081526001602081815260408084208a8552825280842080546001600160a01b0319908116825593810180548516905560028101859055600381018054851690556004810180549094169093556005830184905560068301805460ff19908116909155600784018590556008840180549091169055600990920192909255600b5490860151918601519394506135ea938316921690613f1d565b81606001516001600160a01b031682602001516001600160a01b0316146136c257604080516002808252606080830184529260208301908036833701905050905082602001518160008151811061363d57fe5b60200260200101906001600160a01b031690816001600160a01b03168152505082606001518160018151811061366f57fe5b60200260200101906001600160a01b031690816001600160a01b031681525050600061369d82600030613f74565b600b5460608601519192506136bf916001600160a01b03908116911683613f1d565b50505b600a5482516060840151608085015160a086015160c087015160408051630f8ee8bb60e11b81526001600160a01b03968716600482015294861660248601529285166044850152606484019190915215156084830152519190921691631f1dd1769160a480830192600092919082900301818387803b15801561374457600080fd5b505af1158015613758573d6000803e3d6000fd5b5050505061376b826101200151846140a3565b81600001516001600160a01b03167f7fb1c74d1ea6aa1c9c585e17ce8274c8ff98745e85e7459b73f87d784494f58e8584602001518560400151866060015187608001518860a001518960c001518a60e001518b61010001518c61012001518c604051808c81526020018b6001600160a01b031681526020018a8152602001896001600160a01b03168152602001886001600160a01b03168152602001878152602001861515815260200185815260200184151581526020018381526020018281526020019b50505050505050505050505060405180910390a250506001600055505050565b600080600080600080600080600061386761508f565b505050506001600160a01b0397881660009081526001602081815260408084209a845299815291899020895161014081018b5281548c168152918101548b1692820183905260028101549982018a905260038101548b16606083018190526004820154909b1660808301819052600582015460a08401819052600683015460ff908116151560c08601819052600785015460e08701819052600886015490921615156101008701819052600990950154610120909601869052959e9c9d9c929b5090995093975092955093509150565b60046020526000908152604090205481565b6007546001600160a01b0316331461399f576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600e5460ff16156139f7576040805162461bcd60e51b815260206004820152601e60248201527f4f72646572426f6f6b3a20616c726561647920696e697469616c697a65640000604482015290519081900360640190fd5b600e805460ff19166001179055600a80546001600160a01b038089166001600160a01b03199283168117909355600b8054898316908416811790915560088054898416908516811790915560098054938916939094168317909355600c869055600d8590556040805194855260208501919091528381019290925260608301526080820184905260a08201839052517fcfb7ef8749fafc8da2af1ba3d025479ffc4e58f7dc420113e112512a3bda59639181900360c00190a1505050505050565b6009546001600160a01b031681565b600360208181526000938452604080852090915291835291208054600182015460028301549383015460048401546005850154600686015460078701546008909701546001600160a01b039687169895871697959690941694929360ff9283169391929091169089565b60026000541415613b77576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b6002600055613b8461501c565b33600090815260056020908152604080832085845282529182902082516101008101845281546001600160a01b0316815260018201805485518186028101860190965280865291949293858101939290830182828015613c0d57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613bef575b5050509183525050600282015460208201526003820154604082015260048201546060820152600582015460ff8082161515608084015261010090910416151560a082015260069091015460c09091015280519091506001600160a01b0316613cab576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b336000908152600560209081526040808320858452909152812080546001600160a01b031916815590613ce1600183018261506e565b50600060028201819055600382018190556004820181905560058201805461ffff191690556006909101819055600854602083015180516001600160a01b03909216929091613d2c57fe5b60200260200101516001600160a01b03161415613d6657613d61611e6882604001518360e0015161419290919063ffffffff16565b613d8e565b613d80338260400151836020015160008151811061127257fe5b613d8e8160e00151336140a3565b336001600160a01b03167fefd66d4f9c2f880c70aedeb5b26a44fb474cea07e5d6c533f2d27c303d5d94538383602001518460400151856060015186608001518760a001518860c001518960e00151604051808981526020018060200188815260200187815260200186815260200185151581526020018415158152602001838152602001828103825289818151815260200191508051906020019060200280838360005b83811015613e4b578181015183820152602001613e33565b50505050905001995050505050505050505060405180910390a250506001600055565b600a546001600160a01b031681565b600b546001600160a01b031681565b6007546001600160a01b03163314613ee2576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600c8190556040805182815290517fbde5eafdc37b81830d70124cddccaaa6d034e71dda3c8fc18a959ca76a7cbcfc9181900360200190a150565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052613f6f9084906149da565b505050565b6000835160021415613fbb57613fb484600081518110613f9057fe5b602002602001015185600181518110613fa557fe5b60200260200101518585614a8b565b905061409c565b835160031415614061576000613ffc85600081518110613fd757fe5b602002602001015186600181518110613fec57fe5b6020026020010151600030614a8b565b9050614025600b60009054906101000a90046001600160a01b0316828760018151811061127257fe5b6140598560018151811061403557fe5b60200260200101518660028151811061404a57fe5b60200260200101518686614a8b565b91505061409c565b6040805162461bcd60e51b815260206004820152601f6024820152600080516020615317833981519152604482015290519081900360640190fd5b9392505050565b60085460408051632e1a7d4d60e01b81526004810185905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b1580156140f057600080fd5b505af1158015614104573d6000803e3d6000fd5b5061411c925050506001600160a01b03821683614c6a565b5050565b341561419057600860009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561417657600080fd5b505af115801561418a573d6000803e3d6000fd5b50505050505b565b60008282018381101561409c576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b6001600160a01b03881660009081526006602052604090205461420b61501c565b6040518061010001604052808b6001600160a01b031681526020018a81526020018981526020018881526020018781526020018615158152602001851515815260200184815250905061426860018361419290919063ffffffff16565b6001600160a01b038b8116600090815260066020908152604080832094909455600581528382208683528152929020835181546001600160a01b031916921691909117815582820151805184936142c69260018501929101906150e3565b5060408201518160020155606082015181600301556080820151816004015560a08201518160050160006101000a81548160ff02191690831515021790555060c08201518160050160016101000a81548160ff02191690831515021790555060e08201518160060155905050896001600160a01b03167fdf06bb56ffc4029dc0b62b68bb5bbadea93a38b530cefc9b81afb742a6555d88838b8b8b8b8b8b8b604051808981526020018060200188815260200187815260200186815260200185151581526020018415158152602001838152602001828103825289818151815260200191508051906020019060200280838360005b838110156143d35781810151838201526020016143bb565b50505050905001995050505050505050505060405180910390a250505050505050505050565b3360009081526002602052604090205461441161508f565b6040518061014001604052808d6001600160a01b031681526020018c6001600160a01b031681526020018b81526020018a6001600160a01b03168152602001896001600160a01b031681526020018881526020018715158152602001868152602001851515815260200184815250905061449560018361419290919063ffffffff16565b600260008e6001600160a01b03166001600160a01b031681526020019081526020016000208190555080600160008e6001600160a01b03166001600160a01b03168152602001908152602001600020600084815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160010160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816002015560608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060808201518160040160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060a0820151816005015560c08201518160060160006101000a81548160ff02191690831515021790555060e082015181600701556101008201518160080160006101000a81548160ff02191690831515021790555061012082015181600901559050508b6001600160a01b03167fb27b9afe3043b93788c40cfc3cc73f5d928a2e40f3ba01820b246426de8fa1b9838d8d8d8d8d8d8d8d8d604051808b81526020018a6001600160a01b03168152602001898152602001886001600160a01b03168152602001876001600160a01b03168152602001868152602001851515815260200184815260200183151581526020018281526020019a505050505050505050505060405180910390a2505050505050505050505050565b6000826146db57506000612fa6565b828202828482816146e857fe5b041461409c5760405162461bcd60e51b81526004018080602001828103825260218152602001806152aa6021913960400191505060405180910390fd5b600061409c83836040518060400160405280601a815260200179536166654d6174683a206469766973696f6e206279207a65726f60301b815250614d4f565b6001600160a01b038816600090815260046020526040902054614785614fd0565b5060408051610120810182526001600160a01b03808c1682528a8116602083015291810189905290871660608201526080810186905284151560a082015260c0810184905282151560e0820152346101008201526147e4826001614192565b600460008c6001600160a01b03166001600160a01b031681526020019081526020016000208190555080600360008c6001600160a01b03166001600160a01b03168152602001908152602001600020600084815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160010160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816002015560608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816004015560a08201518160050160006101000a81548160ff02191690831515021790555060c0820151816006015560e08201518160070160006101000a81548160ff0219169083151502179055506101008201518160080155905050896001600160a01b03167f48ee333d2a65cc45fdb83bc012920d89181c3377390cd239d2b63f2bef67a02d838b8b8b8b8b8b8b34604051808a8152602001896001600160a01b03168152602001888152602001876001600160a01b0316815260200186815260200185151581526020018481526020018315158152602001828152602001995050505050505050505060405180910390a250505050505050505050565b6060614a2f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614df19092919063ffffffff16565b805190915015613f6f57808060200190516020811015614a4e57600080fd5b5051613f6f5760405162461bcd60e51b815260040180806020018281038252602a815260200180615337602a913960400191505060405180910390fd5b60095460009081906001600160a01b0386811691161415614b3057600b54604080516306cb8bd960e31b81526001600160a01b03898116600483015286811660248301529151919092169163365c5ec89160448083019260209291908290030181600087803b158015614afd57600080fd5b505af1158015614b11573d6000803e3d6000fd5b505050506040513d6020811015614b2757600080fd5b50519050614c2b565b6009546001600160a01b0387811691161415614b9d57600b546040805163a1155c4960e01b81526001600160a01b03888116600483015286811660248301529151919092169163a1155c499160448083019260209291908290030181600087803b158015614afd57600080fd5b600b5460408051634998b10960e11b81526001600160a01b038981166004830152888116602483015286811660448301529151919092169163933162129160648083019260209291908290030181600087803b158015614bfc57600080fd5b505af1158015614c10573d6000803e3d6000fd5b505050506040513d6020811015614c2657600080fd5b505190505b83811015612cdb5760405162461bcd60e51b815260040180806020018281038252602181526020018061523f6021913960400191505060405180910390fd5b80471015614cbf576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e6365000000604482015290519081900360640190fd5b6040516000906001600160a01b0384169083908381818185875af1925050503d8060008114614d0a576040519150601f19603f3d011682016040523d82523d6000602084013e614d0f565b606091505b5050905080613f6f5760405162461bcd60e51b815260040180806020018281038252603a8152602001806151df603a913960400191505060405180910390fd5b60008183614ddb5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015614da0578181015183820152602001614d88565b50505050905090810190601f168015614dcd5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581614de757fe5b0495945050505050565b6060614e008484600085614e08565b949350505050565b606082471015614e495760405162461bcd60e51b81526004018080602001828103825260268152602001806152196026913960400191505060405180910390fd5b614e5285614f64565b614ea3576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310614ee25780518252601f199092019160209182019101614ec3565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114614f44576040519150601f19603f3d011682016040523d82523d6000602084013e614f49565b606091505b5091509150614f59828286614f6a565b979650505050505050565b3b151590565b60608315614f7957508161409c565b825115614f895782518084602001fd5b60405162461bcd60e51b8152602060048201818152845160248401528451859391928392604401919085019080838360008315614da0578181015183820152602001614d88565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b60405180610100016040528060006001600160a01b0316815260200160608152602001600081526020016000815260200160008152602001600015158152602001600015158152602001600081525090565b508054600082559060005260206000209081019061508c9190615148565b50565b6040805161014081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081019190915290565b828054828255906000526020600020908101928215615138579160200282015b8281111561513857825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190615103565b5061514492915061515d565b5090565b5b808211156151445760008155600101615149565b5b808211156151445780546001600160a01b031916815560010161515e56fe4f72646572426f6f6b3a206e6f6e2d6578697374656e74206f726465720000005265656e7472616e637947756172643a207265656e7472616e742063616c6c004f72646572426f6f6b3a20696e73756666696369656e7420636f6c6c61746572616c416464726573733a20756e61626c6520746f2073656e642076616c75652c20726563697069656e74206d61792068617665207265766572746564416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c4f72646572426f6f6b3a20696e73756666696369656e7420616d6f756e744f75744f72646572426f6f6b3a206f6e6c79207765746820636f756c6420626520777261707065644f72646572426f6f6b3a20696e73756666696369656e7420657865637574696f6e20666565536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f774f72646572426f6f6b3a20696e636f72726563742076616c7565207472616e736665727265644f72646572426f6f6b3a20696e76616c696420707269636520666f7220657865637574696f6e4f72646572426f6f6b3a20696e76616c6964205f706174682e6c656e677468005361666545524332303a204552433230206f7065726174696f6e20646964206e6f7420737563636565644f72646572426f6f6b3a20696e636f727265637420657865637574696f6e20666565207472616e73666572726564a2646970667358221220eb733ef03b253d6d90eafa87014672fde0e5a555bc379f04bf3248d7deb47dc564736f6c634300060c0033

Deployed ByteCode

0x6080604052600436106101c35760003560e01c8062cf066b1461022a578063026032ee1461026f57806307c7edc3146102fa5780630d5cc9381461033d57806311d9444a1461036757806312d43a51146103aa578063269ae6c2146103db5780632b7d6290146104a6578063392e53cd146105465780633fc8cef31461056f57806347e0bbd0146105845780634c54f0b0146105ae57806363ae21031461061857806379221fa21461062d578063807c5600146106ac5780638de10c2e1461085e57806395082d25146108735780639983ee1b146108885780639e71b0f0146108c6578063a397ea54146108f0578063aec2245514610934578063b142a4b014610967578063bf73afc114610a51578063c16cde8a14610a84578063c4a1821b14610ad4578063c86b0f7d14610b84578063ced8f6c414610bc2578063cfad57a214610bd7578063d0d40cd614610c0a578063d38ab51914610c9d578063d3bab1d114610ce0578063d566d0ca14610d74578063d7c41c7914610da7578063d858b24514610e00578063f2d2e01b14610e15578063f882ac0714610ea9578063f887ea4014610ed3578063fbfa77cf14610ee8578063fc2cee6214610efd57610225565b36610225576008546001600160a01b03163314610223576040805162461bcd60e51b815260206004820152601960248201527827b93232b92137b7b59d1034b73b30b634b21039b2b73232b960391b604482015290519081900360640190fd5b005b600080fd5b34801561023657600080fd5b5061025d6004803603602081101561024d57600080fd5b50356001600160a01b0316610f27565b60408051918252519081900360200190f35b34801561027b57600080fd5b506102a86004803603604081101561029257600080fd5b506001600160a01b038135169060200135610f39565b604080516001600160a01b03998a168152602081019890985295909716868601526060860193909352901515608085015260a0840152151560c083015260e08201929092529051908190036101000190f35b34801561030657600080fd5b506102236004803603606081101561031d57600080fd5b506001600160a01b0381358116916020810135916040909101351661100c565b34801561034957600080fd5b506102236004803603602081101561036057600080fd5b5035611417565b34801561037357600080fd5b506102236004803603606081101561038a57600080fd5b506001600160a01b038135811691602081013591604090910135166114a8565b3480156103b657600080fd5b506103bf611857565b604080516001600160a01b039092168252519081900360200190f35b61022360048036036101008110156103f257600080fd5b810190602081018135600160201b81111561040c57600080fd5b82018360208201111561041e57600080fd5b803590602001918460208302840111600160201b8311171561043f57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955050823593505050602081013590604081013590606081013515159060808101359060a081013515159060c001351515611866565b3480156104b257600080fd5b506104df600480360360408110156104c957600080fd5b506001600160a01b038135169060200135611bef565b604080516001600160a01b039b8c168152998b1660208b015289810198909852958916606089015293909716608087015260a0860191909152151560c085015260e08401949094529215156101008301526101208201929092529051908190036101400190f35b34801561055257600080fd5b5061055b611c61565b604080519115158252519081900360200190f35b34801561057b57600080fd5b506103bf611c6a565b34801561059057600080fd5b50610223600480360360208110156105a757600080fd5b5035611c79565b3480156105ba57600080fd5b506105ff600480360360a08110156105d157600080fd5b5080351515906020810135906001600160a01b03604082013516906060810135151590608001351515611f83565b6040805192835290151560208301528051918290030190f35b34801561062457600080fd5b5061025d6120ec565b34801561063957600080fd5b506106666004803603604081101561065057600080fd5b506001600160a01b0381351690602001356120f2565b604080516001600160a01b039098168852602088019690965286860194909452606086019290925215156080850152151560a084015260c0830152519081900360e00190f35b3480156106b857600080fd5b50610223600480360360608110156106cf57600080fd5b810190602081018135600160201b8111156106e957600080fd5b8201836020820111156106fb57600080fd5b803590602001918460208302840111600160201b8311171561071c57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b81111561076b57600080fd5b82018360208201111561077d57600080fd5b803590602001918460208302840111600160201b8311171561079e57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b8111156107ed57600080fd5b8201836020820111156107ff57600080fd5b803590602001918460208302840111600160201b8311171561082057600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612146945050505050565b34801561086a57600080fd5b5061025d6121de565b34801561087f57600080fd5b5061025d6121e4565b34801561089457600080fd5b50610223600480360360808110156108ab57600080fd5b508035906020810135906040810135906060013515156121f4565b3480156108d257600080fd5b50610223600480360360208110156108e957600080fd5b503561234c565b3480156108fc57600080fd5b50610223600480360360a081101561091357600080fd5b508035906020810135906040810135906060810135906080013515156125be565b34801561094057600080fd5b5061025d6004803603602081101561095757600080fd5b50356001600160a01b0316612726565b610223600480360361016081101561097e57600080fd5b810190602081018135600160201b81111561099857600080fd5b8201836020820111156109aa57600080fd5b803590602001918460208302840111600160201b831117156109cb57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295505082359350506001600160a01b036020830135811692604081013592506060810135916080820135169060a081013515159060c08101359060e08101351515906101008101359061012001351515612738565b348015610a5d57600080fd5b5061025d60048036036020811015610a7457600080fd5b50356001600160a01b0316612b3a565b610223600480360360e0811015610a9a57600080fd5b506001600160a01b03813581169160208101359160408201351690606081013590608081013515159060a08101359060c001351515612ce4565b348015610ae057600080fd5b5061055b60048036036040811015610af757600080fd5b810190602081018135600160201b811115610b1157600080fd5b820183602082011115610b2357600080fd5b803590602001918460208302840111600160201b83111715610b4457600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295505091359250612d95915050565b348015610b9057600080fd5b5061022360048036036080811015610ba757600080fd5b50803590602081013590604081013590606001351515612fac565b348015610bce57600080fd5b5061025d613175565b348015610be357600080fd5b5061022360048036036020811015610bfa57600080fd5b50356001600160a01b0316613181565b348015610c1657600080fd5b50610c4360048036036040811015610c2d57600080fd5b506001600160a01b03813516906020013561322b565b604080516001600160a01b039a8b168152988a1660208a015296909816878701526060870194909452608086019290925260a0850152151560c0840152151560e08301526101008201929092529051908190036101200190f35b348015610ca957600080fd5b5061022360048036036060811015610cc057600080fd5b506001600160a01b038135811691602081013591604090910135166133e8565b348015610cec57600080fd5b50610d1960048036036040811015610d0357600080fd5b506001600160a01b038135169060200135613851565b604080516001600160a01b039a8b1681526020810199909952968916888801529490971660608701526080860192909252151560a085015260c084015292151560e08301526101008201929092529051908190036101200190f35b348015610d8057600080fd5b5061025d60048036036020811015610d9757600080fd5b50356001600160a01b0316613937565b348015610db357600080fd5b50610223600480360360c0811015610dca57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060808101359060a00135613949565b348015610e0c57600080fd5b506103bf613ab8565b348015610e2157600080fd5b50610e4e60048036036040811015610e3857600080fd5b506001600160a01b038135169060200135613ac7565b604080516001600160a01b039a8b168152988a1660208a0152888101979097529490971660608701526080860192909252151560a085015260c084015292151560e08301526101008201929092529051908190036101200190f35b348015610eb557600080fd5b5061022360048036036020811015610ecc57600080fd5b5035613b31565b348015610edf57600080fd5b506103bf613e6e565b348015610ef457600080fd5b506103bf613e7d565b348015610f0957600080fd5b5061022360048036036020811015610f2057600080fd5b5035613e8c565b60066020526000908152604090205481565b600080600080600080600080610f4d614fd0565b505050506001600160a01b03968716600090815260036020818152604080842099845298815291889020885161012081018a5281548b16815260018201548b1693810184905260028201549981018a9052918101549099166060820181905260048a01546080830181905260058b015460ff908116151560a0850181905260068d015460c0860181905260078e0154909216151560e086018190526008909d0154610100909501859052949c9a9b929a91995093975092955093509150565b60026000541415611052576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561105f61501c565b6001600160a01b038085166000908152600560209081526040808320878452825291829020825161010081018452815490941684526001810180548451818502810185019095528085529193858401939092908301828280156110eb57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116110cd575b5050509183525050600282015460208201526003820154604082015260048201546060820152600582015460ff8082161515608084015261010090910416151560a082015260069091015460c09091015280519091506001600160a01b0316611189576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b8060a00151156111e0576111a581602001518260800151612d95565b6111e05760405162461bcd60e51b81526004018080602001828103825260268152602001806152f16026913960400191505060405180910390fd5b6001600160a01b0384166000908152600560209081526040808320868452909152812080546001600160a01b03191681559061121f600183018261506e565b50600060028201819055600382018190556004820181905560058201805461ffff191690556006909101819055600b54604083015160208401518051611292946001600160a01b03909416939061127257fe5b60200260200101516001600160a01b0316613f1d9092919063ffffffff16565b600854602082015180516000926001600160a01b0316919060001981019081106112b857fe5b60200260200101516001600160a01b03161480156112d757508160c001515b15611304576112ef8260200151836060015130613f74565b90506112ff8183600001516140a3565b61131e565b61131b826020015183606001518460000151613f74565b90505b61132c8260e00151846140a3565b846001600160a01b03167f7e1fe496989eea92b738a562dbf9c0ae6aa6fcf3f1ef09e95ee4f7603721706b858460200151856040015186606001518688608001518960a001518a60c001518b60e00151604051808a8152602001806020018981526020018881526020018781526020018681526020018515158152602001841515815260200183815260200182810382528a818151815260200191508051906020019060200280838360005b838110156113f05781810151838201526020016113d8565b505050509050019a505050505050505050505060405180910390a250506001600055505050565b6007546001600160a01b0316331461146d576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600d8190556040805182815290517fe46d9daf6d25f7615efa1d0183b90ac6759d85014b598e409aadf0fd918d59a69181900360200190a150565b600260005414156114ee576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000556114fb614fd0565b506001600160a01b03808416600090815260036020818152604080842087855282529283902083516101208101855281548616808252600183015487169382019390935260028201549481019490945291820154909316606083015260048101546080830152600581015460ff908116151560a0840152600682015460c0840152600782015416151560e083015260080154610100820152906115d3576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b60006115f48260e001518360c0015184606001518560a00151156001611f83565b506001600160a01b0380871660009081526003602081815260408084208a8552825280842080546001600160a01b0319908116825560018201805482169055600282018690559381018054909416909355600480840185905560058401805460ff199081169091556006850186905560078501805490911690556008909301849055600a5488518984015160608b01518b85015160808d015160a08e01518751632662166b60e01b8152958c1699860199909952928a16602485015290891660448401526064830152608482015293151560a48501523060c4850152905195965092949290931692632662166b9260e48084019382900301818787803b1580156116fd57600080fd5b505af1158015611711573d6000803e3d6000fd5b505050506040513d602081101561172757600080fd5b505160085460208501519192506001600160a01b039182169116141561175a576117558184600001516140a3565b611777565b82516020840151611777916001600160a01b039091169083613f1d565b611786836101000151856140a3565b82600001516001600160a01b03167f9a382661d6573da86db000471303be6f0b2b1bb66089b08e3c16a85d7b6e94f88685602001518660400151876060015188608001518960a001518a60c001518b60e001518c61010001518c604051808b81526020018a6001600160a01b03168152602001898152602001886001600160a01b03168152602001878152602001861515815260200185815260200184151581526020018381526020018281526020019a505050505050505050505060405180910390a25050600160005550505050565b6007546001600160a01b031681565b600260005414156118ac576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000819055885114806118c2575087516003145b611901576040805162461bcd60e51b815260206004820152601f6024820152600080516020615317833981519152604482015290519081900360640190fd5b8760018951038151811061191157fe5b60200260200101516001600160a01b03168860008151811061192f57fe5b60200260200101516001600160a01b0316141561198e576040805162461bcd60e51b815260206004820152601860248201527709ee4c8cae484deded67440d2dcecc2d8d2c840bee0c2e8d60431b604482015290519081900360640190fd5b600087116119e2576040805162461bcd60e51b815260206004820152601c60248201527b27b93232b92137b7b59d1034b73b30b634b2102fb0b6b7bab73a24b760211b604482015290519081900360640190fd5b600c54831015611a235760405162461bcd60e51b81526004018080602001828103825260258152602001806152856025913960400191505060405180910390fd5b611a2b614120565b8115611ae65760085488516001600160a01b03909116908990600090611a4d57fe5b60200260200101516001600160a01b031614611a9a5760405162461bcd60e51b81526004018080602001828103825260258152602001806152606025913960400191505060405180910390fd5b611aa48388614192565b3414611ae15760405162461bcd60e51b81526004018080602001828103825260268152602001806152cb6026913960400191505060405180910390fd5b611bd0565b823414611b245760405162461bcd60e51b815260040180806020018281038252602e815260200180615361602e913960400191505060405180910390fd5b600a5488516001600160a01b0390911690631b827878908a90600090611b4657fe5b602002602001015133308b6040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846001600160a01b03168152602001836001600160a01b03168152602001828152602001945050505050600060405180830381600087803b158015611bb757600080fd5b505af1158015611bcb573d6000803e3d6000fd5b505050505b611be0338989898989878a6141ea565b50506001600055505050505050565b6001602081815260009384526040808520909152918352912080549181015460028201546003830154600484015460058501546006860154600787015460088801546009909801546001600160a01b03998a1699978816989697958616969490951694929360ff92831693919216908a565b600e5460ff1681565b6008546001600160a01b031681565b60026000541415611cbf576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b6002600055611ccc61508f565b5033600090815260016020818152604080842085855282529283902083516101408101855281546001600160a01b039081168083529483015481169382019390935260028201549481019490945260038101548216606085015260048101549091166080840152600581015460a0840152600681015460ff908116151560c0850152600782015460e0850152600882015416151561010084015260090154610120830152611daf576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b3360009081526001602081815260408084208685528252832080546001600160a01b0319908116825592810180548416905560028101849055600381018054841690556004810180549093169092556005820183905560068201805460ff19908116909155600783018490556008808401805490921690915560099092019290925554908201516001600160a01b0390811691161415611e7357611e6e611e68826040015183610120015161419290919063ffffffff16565b336140a3565b611ea8565b611e9933826040015183602001516001600160a01b0316613f1d9092919063ffffffff16565b611ea8816101200151336140a3565b80600001516001600160a01b03167fd500f34e0ec655b7614ae42e1d9c666d5e4dde909a1297829f8c5ecf00805d328383602001518460400151856060015186608001518760a001518860c001518960e001518a61010001518b6101200151604051808b81526020018a6001600160a01b03168152602001898152602001886001600160a01b03168152602001876001600160a01b03168152602001868152602001851515815260200184815260200183151581526020018281526020019a505050505050505050505060405180910390a250506001600055565b60008060008461200b57600b54604080516340d3096b60e11b81526001600160a01b038981166004830152915191909216916381a612d6916024808301926020929190829003018186803b158015611fda57600080fd5b505afa158015611fee573d6000803e3d6000fd5b505050506040513d602081101561200457600080fd5b5051612085565b600b5460408051637092736960e11b81526001600160a01b0389811660048301529151919092169163e124e6d2916024808301926020929190829003018186803b15801561205857600080fd5b505afa15801561206c573d6000803e3d6000fd5b505050506040513d602081101561208257600080fd5b50515b90506000886120965787821061209a565b8782115b905084156120de57806120de5760405162461bcd60e51b81526004018080602001828103825260268152602001806152f16026913960400191505060405180910390fd5b909890975095505050505050565b600c5481565b600560208181526000938452604080852090915291835291208054600282015460038301546004840154948401546006909401546001600160a01b03909316949193909260ff808316926101009004169087565b60005b83518110156121765761216e84828151811061216157fe5b6020026020010151613b31565b600101612149565b5060005b82518110156121a75761219f83828151811061219257fe5b6020026020010151611c79565b60010161217a565b5060005b81518110156121d8576121d08282815181106121c357fe5b602002602001015161234c565b6001016121ab565b50505050565b600d5481565b68327cb2734119d3b7a9601e1b81565b6002600054141561223a576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000908155338152600160209081526040808320878452909152902080546001600160a01b03166122a2576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b6007810183905560088101805483151560ff19909116811790915560058201859055600382015460048301546006840154604080518a81526001600160a01b039485166020820152929093168284015260ff16151560608201526080810187905260a0810186905260c08101929092525133917f0a0360dd5c354235bbf8d386ba3b24ef8134088e0785677de1504df219d9149a919081900360e00190a250506001600055505050565b60026000541415612392576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561239f614fd0565b5033600090815260036020818152604080842085855282529283902083516101208101855281546001600160a01b03908116808352600184015482169483019490945260028301549582019590955292810154909316606083015260048301546080830152600583015460ff908116151560a0840152600684015460c0840152600784015416151560e083015260089092015461010082015290612478576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b336000818152600360208181526040808420878552909152822080546001600160a01b03199081168255600182018054821690556002820184905591810180549092169091556004810182905560058101805460ff19908116909155600682018390556007820180549091169055600801556101008201516124f9916140a3565b80600001516001600160a01b03167f1154174c82984656b028c8021671988f60a346497e56fe02554761184f82a0758383602001518460400151856060015186608001518760a001518860c001518960e001518a6101000151604051808a8152602001896001600160a01b03168152602001888152602001876001600160a01b0316815260200186815260200185151581526020018481526020018315158152602001828152602001995050505050505050505060405180910390a250506001600055565b60026000541415612604576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000908155338152600360209081526040808320888452909152902080546001600160a01b031661266c576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b6006810183905560078101805483151560ff1990911681179091556004820185905560028201869055600182015460038301546005840154604080518b81526001600160a01b0394851660208201528082018b90529290931660608301526080820188905260ff16151560a082015260c0810186905260e08101929092525133917f75781255bc71c83f89f29e5a2599f2c174a562d2cd8f2e818a47f132e728049891908190036101000190a25050600160005550505050565b60026020526000908152604090205481565b6002600054141561277e576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561278b614120565b600c548210156127cc5760405162461bcd60e51b81526004018080602001828103825260258152602001806152856025913960400191505060405180910390fd5b8015612887576008548b516001600160a01b03909116908c906000906127ee57fe5b60200260200101516001600160a01b03161461283b5760405162461bcd60e51b81526004018080602001828103825260258152602001806152606025913960400191505060405180910390fd5b612845828b614192565b34146128825760405162461bcd60e51b81526004018080602001828103825260268152602001806152cb6026913960400191505060405180910390fd5b612971565b8134146128c55760405162461bcd60e51b815260040180806020018281038252602e815260200180615361602e913960400191505060405180910390fd5b600a548b516001600160a01b0390911690631b827878908d906000906128e757fe5b602002602001015133308e6040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846001600160a01b03168152602001836001600160a01b03168152602001828152602001945050505050600060405180830381600087803b15801561295857600080fd5b505af115801561296c573d6000803e3d6000fd5b505050505b60008b60018d51038151811061298357fe5b60200260200101519050600060018d511115612a4857816001600160a01b03168d6000815181106129b057fe5b60200260200101516001600160a01b03161415612a0f576040805162461bcd60e51b815260206004820152601860248201527709ee4c8cae484deded67440d2dcecc2d8d2c840bee0c2e8d60431b604482015290519081900360640190fd5b612a36600b60009054906101000a90046001600160a01b03168d8f60008151811061127257fe5b612a418d8b30613f74565b9050612a4b565b508a5b600b5460408051630a48d5a960e01b81526001600160a01b0385811660048301526024820185905291516000939290921691630a48d5a991604480820192602092909190829003018186803b158015612aa357600080fd5b505afa158015612ab7573d6000803e3d6000fd5b505050506040513d6020811015612acd57600080fd5b5051600d54909150811015612b135760405162461bcd60e51b81526004018080602001828103825260228152602001806151bd6022913960400191505060405180910390fd5b50612b263383838b8f8e8d8d8d8d6143f9565b505060016000555050505050505050505050565b600b5460408051632c668ec160e01b81526001600160a01b038481166004830152670de0b6b3a76400006024830152915160009384931691632c668ec1916044808301926020929190829003018186803b158015612b9757600080fd5b505afa158015612bab573d6000803e3d6000fd5b505050506040513d6020811015612bc157600080fd5b5051600b54604080516340d3096b60e11b81526001600160a01b038781166004830152915193945060009391909216916381a612d6916024808301926020929190829003018186803b158015612c1657600080fd5b505afa158015612c2a573d6000803e3d6000fd5b505050506040513d6020811015612c4057600080fd5b5051600b54604080516323b95ceb60e21b81526001600160a01b03888116600483015291519394506000939190921691638ee573ac916024808301926020929190829003018186803b158015612c9557600080fd5b505afa158015612ca9573d6000803e3d6000fd5b505050506040513d6020811015612cbf57600080fd5b50519050612cdb600a82900a612cd585856146cc565b90614725565b95945050505050565b60026000541415612d2a576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b6002600055612d37614120565b600c543411612d775760405162461bcd60e51b81526004018080602001828103825260258152602001806152856025913960400191505060405180910390fd5b612d873386868a8a888888614764565b505060016000555050505050565b6000825160021480612da8575082516003145b612de7576040805162461bcd60e51b815260206004820152601f6024820152600080516020615317833981519152604482015290519081900360640190fd5b600083600081518110612df657fe5b60200260200101519050600084600186510381518110612e1257fe5b602090810291909101015160095490915060009081906001600160a01b0385811691161415612e5f57612e5887600181518110612e4b57fe5b6020026020010151612b3a565b9150612edb565b600b54604080516340d3096b60e11b81526001600160a01b038781166004830152915191909216916381a612d6916024808301926020929190829003018186803b158015612eac57600080fd5b505afa158015612ec0573d6000803e3d6000fd5b505050506040513d6020811015612ed657600080fd5b505191505b6009546001600160a01b0384811691161415612f04575068327cb2734119d3b7a9601e1b612f80565b600b5460408051637092736960e11b81526001600160a01b0386811660048301529151919092169163e124e6d2916024808301926020929190829003018186803b158015612f5157600080fd5b505afa158015612f65573d6000803e3d6000fd5b505050506040513d6020811015612f7b57600080fd5b505190505b6000612f9c83612cd58468327cb2734119d3b7a9601e1b6146cc565b8710955050505050505b92915050565b60026000541415612ff2576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b60026000908155338152600560209081526040808320878452909152902080546001600160a01b031661305a576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b838160030181905550828160040181905550818160050160006101000a81548160ff021916908315150217905550336001600160a01b03167fa7f9f4a25eb76f5ec01b1a429d95d6a00833f0f137c88827c58799a1c1ff0dfe868360010184600201548888888860050160019054906101000a900460ff168960060154604051808981526020018060200188815260200187815260200186815260200185151581526020018415158152602001838152602001828103825289818154815260200191508054801561315457602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613136575b5050995050505050505050505060405180910390a250506001600055505050565b670de0b6b3a764000081565b6007546001600160a01b031633146131d7576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600780546001600160a01b0383166001600160a01b0319909116811790915560408051918252517fe24c39186e9137521953beaa8446e71f55b8f12296984f9d4273ceb1af728d909181900360200190a150565b600080600080600080600080600061324161501c565b6001600160a01b03808d1660009081526005602090815260408083208f8452825291829020825161010081018452815490941684526001810180548451818502810185019095528085529193858401939092908301828280156132cd57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116132af575b505050918352505060028201546020808301919091526003830154604083015260048301546060830152600583015460ff8082161515608085015261010090910416151560a083015260069092015460c0909101528101515190915061333457600061334e565b806020015160008151811061334557fe5b60200260200101515b60018260200151511161336257600061337c565b816020015160018151811061337357fe5b60200260200101515b6002836020015151116133905760006133aa565b82602001516002815181106133a157fe5b60200260200101515b8360400151846060015185608001518660a001518760c001518860e00151995099509950995099509950995099509950509295985092959850929598565b6002600054141561342e576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b600260005561343b61508f565b506001600160a01b038084166000908152600160208181526040808420878552825292839020835161014081018552815486168082529382015486169281019290925260028101549382019390935260038301548416606082015260048301549093166080840152600582015460a0840152600682015460ff908116151560c0850152600783015460e08501526008830154161515610100840152600990910154610120830152613521576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b60006135428261010001518360e0015184608001518560c001516001611f83565b506001600160a01b0380871660009081526001602081815260408084208a8552825280842080546001600160a01b0319908116825593810180548516905560028101859055600381018054851690556004810180549094169093556005830184905560068301805460ff19908116909155600784018590556008840180549091169055600990920192909255600b5490860151918601519394506135ea938316921690613f1d565b81606001516001600160a01b031682602001516001600160a01b0316146136c257604080516002808252606080830184529260208301908036833701905050905082602001518160008151811061363d57fe5b60200260200101906001600160a01b031690816001600160a01b03168152505082606001518160018151811061366f57fe5b60200260200101906001600160a01b031690816001600160a01b031681525050600061369d82600030613f74565b600b5460608601519192506136bf916001600160a01b03908116911683613f1d565b50505b600a5482516060840151608085015160a086015160c087015160408051630f8ee8bb60e11b81526001600160a01b03968716600482015294861660248601529285166044850152606484019190915215156084830152519190921691631f1dd1769160a480830192600092919082900301818387803b15801561374457600080fd5b505af1158015613758573d6000803e3d6000fd5b5050505061376b826101200151846140a3565b81600001516001600160a01b03167f7fb1c74d1ea6aa1c9c585e17ce8274c8ff98745e85e7459b73f87d784494f58e8584602001518560400151866060015187608001518860a001518960c001518a60e001518b61010001518c61012001518c604051808c81526020018b6001600160a01b031681526020018a8152602001896001600160a01b03168152602001886001600160a01b03168152602001878152602001861515815260200185815260200184151581526020018381526020018281526020019b50505050505050505050505060405180910390a250506001600055505050565b600080600080600080600080600061386761508f565b505050506001600160a01b0397881660009081526001602081815260408084209a845299815291899020895161014081018b5281548c168152918101548b1692820183905260028101549982018a905260038101548b16606083018190526004820154909b1660808301819052600582015460a08401819052600683015460ff908116151560c08601819052600785015460e08701819052600886015490921615156101008701819052600990950154610120909601869052959e9c9d9c929b5090995093975092955093509150565b60046020526000908152604090205481565b6007546001600160a01b0316331461399f576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600e5460ff16156139f7576040805162461bcd60e51b815260206004820152601e60248201527f4f72646572426f6f6b3a20616c726561647920696e697469616c697a65640000604482015290519081900360640190fd5b600e805460ff19166001179055600a80546001600160a01b038089166001600160a01b03199283168117909355600b8054898316908416811790915560088054898416908516811790915560098054938916939094168317909355600c869055600d8590556040805194855260208501919091528381019290925260608301526080820184905260a08201839052517fcfb7ef8749fafc8da2af1ba3d025479ffc4e58f7dc420113e112512a3bda59639181900360c00190a1505050505050565b6009546001600160a01b031681565b600360208181526000938452604080852090915291835291208054600182015460028301549383015460048401546005850154600686015460078701546008909701546001600160a01b039687169895871697959690941694929360ff9283169391929091169089565b60026000541415613b77576040805162461bcd60e51b815260206004820152601f602482015260008051602061519d833981519152604482015290519081900360640190fd5b6002600055613b8461501c565b33600090815260056020908152604080832085845282529182902082516101008101845281546001600160a01b0316815260018201805485518186028101860190965280865291949293858101939290830182828015613c0d57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613bef575b5050509183525050600282015460208201526003820154604082015260048201546060820152600582015460ff8082161515608084015261010090910416151560a082015260069091015460c09091015280519091506001600160a01b0316613cab576040805162461bcd60e51b815260206004820152601d602482015260008051602061517d833981519152604482015290519081900360640190fd5b336000908152600560209081526040808320858452909152812080546001600160a01b031916815590613ce1600183018261506e565b50600060028201819055600382018190556004820181905560058201805461ffff191690556006909101819055600854602083015180516001600160a01b03909216929091613d2c57fe5b60200260200101516001600160a01b03161415613d6657613d61611e6882604001518360e0015161419290919063ffffffff16565b613d8e565b613d80338260400151836020015160008151811061127257fe5b613d8e8160e00151336140a3565b336001600160a01b03167fefd66d4f9c2f880c70aedeb5b26a44fb474cea07e5d6c533f2d27c303d5d94538383602001518460400151856060015186608001518760a001518860c001518960e00151604051808981526020018060200188815260200187815260200186815260200185151581526020018415158152602001838152602001828103825289818151815260200191508051906020019060200280838360005b83811015613e4b578181015183820152602001613e33565b50505050905001995050505050505050505060405180910390a250506001600055565b600a546001600160a01b031681565b600b546001600160a01b031681565b6007546001600160a01b03163314613ee2576040805162461bcd60e51b815260206004820152601460248201527327b93232b92137b7b59d103337b93134b23232b760611b604482015290519081900360640190fd5b600c8190556040805182815290517fbde5eafdc37b81830d70124cddccaaa6d034e71dda3c8fc18a959ca76a7cbcfc9181900360200190a150565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052613f6f9084906149da565b505050565b6000835160021415613fbb57613fb484600081518110613f9057fe5b602002602001015185600181518110613fa557fe5b60200260200101518585614a8b565b905061409c565b835160031415614061576000613ffc85600081518110613fd757fe5b602002602001015186600181518110613fec57fe5b6020026020010151600030614a8b565b9050614025600b60009054906101000a90046001600160a01b0316828760018151811061127257fe5b6140598560018151811061403557fe5b60200260200101518660028151811061404a57fe5b60200260200101518686614a8b565b91505061409c565b6040805162461bcd60e51b815260206004820152601f6024820152600080516020615317833981519152604482015290519081900360640190fd5b9392505050565b60085460408051632e1a7d4d60e01b81526004810185905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b1580156140f057600080fd5b505af1158015614104573d6000803e3d6000fd5b5061411c925050506001600160a01b03821683614c6a565b5050565b341561419057600860009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561417657600080fd5b505af115801561418a573d6000803e3d6000fd5b50505050505b565b60008282018381101561409c576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b6001600160a01b03881660009081526006602052604090205461420b61501c565b6040518061010001604052808b6001600160a01b031681526020018a81526020018981526020018881526020018781526020018615158152602001851515815260200184815250905061426860018361419290919063ffffffff16565b6001600160a01b038b8116600090815260066020908152604080832094909455600581528382208683528152929020835181546001600160a01b031916921691909117815582820151805184936142c69260018501929101906150e3565b5060408201518160020155606082015181600301556080820151816004015560a08201518160050160006101000a81548160ff02191690831515021790555060c08201518160050160016101000a81548160ff02191690831515021790555060e08201518160060155905050896001600160a01b03167fdf06bb56ffc4029dc0b62b68bb5bbadea93a38b530cefc9b81afb742a6555d88838b8b8b8b8b8b8b604051808981526020018060200188815260200187815260200186815260200185151581526020018415158152602001838152602001828103825289818151815260200191508051906020019060200280838360005b838110156143d35781810151838201526020016143bb565b50505050905001995050505050505050505060405180910390a250505050505050505050565b3360009081526002602052604090205461441161508f565b6040518061014001604052808d6001600160a01b031681526020018c6001600160a01b031681526020018b81526020018a6001600160a01b03168152602001896001600160a01b031681526020018881526020018715158152602001868152602001851515815260200184815250905061449560018361419290919063ffffffff16565b600260008e6001600160a01b03166001600160a01b031681526020019081526020016000208190555080600160008e6001600160a01b03166001600160a01b03168152602001908152602001600020600084815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160010160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816002015560608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060808201518160040160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060a0820151816005015560c08201518160060160006101000a81548160ff02191690831515021790555060e082015181600701556101008201518160080160006101000a81548160ff02191690831515021790555061012082015181600901559050508b6001600160a01b03167fb27b9afe3043b93788c40cfc3cc73f5d928a2e40f3ba01820b246426de8fa1b9838d8d8d8d8d8d8d8d8d604051808b81526020018a6001600160a01b03168152602001898152602001886001600160a01b03168152602001876001600160a01b03168152602001868152602001851515815260200184815260200183151581526020018281526020019a505050505050505050505060405180910390a2505050505050505050505050565b6000826146db57506000612fa6565b828202828482816146e857fe5b041461409c5760405162461bcd60e51b81526004018080602001828103825260218152602001806152aa6021913960400191505060405180910390fd5b600061409c83836040518060400160405280601a815260200179536166654d6174683a206469766973696f6e206279207a65726f60301b815250614d4f565b6001600160a01b038816600090815260046020526040902054614785614fd0565b5060408051610120810182526001600160a01b03808c1682528a8116602083015291810189905290871660608201526080810186905284151560a082015260c0810184905282151560e0820152346101008201526147e4826001614192565b600460008c6001600160a01b03166001600160a01b031681526020019081526020016000208190555080600360008c6001600160a01b03166001600160a01b03168152602001908152602001600020600084815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160010160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816002015560608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816004015560a08201518160050160006101000a81548160ff02191690831515021790555060c0820151816006015560e08201518160070160006101000a81548160ff0219169083151502179055506101008201518160080155905050896001600160a01b03167f48ee333d2a65cc45fdb83bc012920d89181c3377390cd239d2b63f2bef67a02d838b8b8b8b8b8b8b34604051808a8152602001896001600160a01b03168152602001888152602001876001600160a01b0316815260200186815260200185151581526020018481526020018315158152602001828152602001995050505050505050505060405180910390a250505050505050505050565b6060614a2f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614df19092919063ffffffff16565b805190915015613f6f57808060200190516020811015614a4e57600080fd5b5051613f6f5760405162461bcd60e51b815260040180806020018281038252602a815260200180615337602a913960400191505060405180910390fd5b60095460009081906001600160a01b0386811691161415614b3057600b54604080516306cb8bd960e31b81526001600160a01b03898116600483015286811660248301529151919092169163365c5ec89160448083019260209291908290030181600087803b158015614afd57600080fd5b505af1158015614b11573d6000803e3d6000fd5b505050506040513d6020811015614b2757600080fd5b50519050614c2b565b6009546001600160a01b0387811691161415614b9d57600b546040805163a1155c4960e01b81526001600160a01b03888116600483015286811660248301529151919092169163a1155c499160448083019260209291908290030181600087803b158015614afd57600080fd5b600b5460408051634998b10960e11b81526001600160a01b038981166004830152888116602483015286811660448301529151919092169163933162129160648083019260209291908290030181600087803b158015614bfc57600080fd5b505af1158015614c10573d6000803e3d6000fd5b505050506040513d6020811015614c2657600080fd5b505190505b83811015612cdb5760405162461bcd60e51b815260040180806020018281038252602181526020018061523f6021913960400191505060405180910390fd5b80471015614cbf576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e6365000000604482015290519081900360640190fd5b6040516000906001600160a01b0384169083908381818185875af1925050503d8060008114614d0a576040519150601f19603f3d011682016040523d82523d6000602084013e614d0f565b606091505b5050905080613f6f5760405162461bcd60e51b815260040180806020018281038252603a8152602001806151df603a913960400191505060405180910390fd5b60008183614ddb5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015614da0578181015183820152602001614d88565b50505050905090810190601f168015614dcd5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581614de757fe5b0495945050505050565b6060614e008484600085614e08565b949350505050565b606082471015614e495760405162461bcd60e51b81526004018080602001828103825260268152602001806152196026913960400191505060405180910390fd5b614e5285614f64565b614ea3576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310614ee25780518252601f199092019160209182019101614ec3565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114614f44576040519150601f19603f3d011682016040523d82523d6000602084013e614f49565b606091505b5091509150614f59828286614f6a565b979650505050505050565b3b151590565b60608315614f7957508161409c565b825115614f895782518084602001fd5b60405162461bcd60e51b8152602060048201818152845160248401528451859391928392604401919085019080838360008315614da0578181015183820152602001614d88565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b60405180610100016040528060006001600160a01b0316815260200160608152602001600081526020016000815260200160008152602001600015158152602001600015158152602001600081525090565b508054600082559060005260206000209081019061508c9190615148565b50565b6040805161014081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081019190915290565b828054828255906000526020600020908101928215615138579160200282015b8281111561513857825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190615103565b5061514492915061515d565b5090565b5b808211156151445760008155600101615149565b5b808211156151445780546001600160a01b031916815560010161515e56fe4f72646572426f6f6b3a206e6f6e2d6578697374656e74206f726465720000005265656e7472616e637947756172643a207265656e7472616e742063616c6c004f72646572426f6f6b3a20696e73756666696369656e7420636f6c6c61746572616c416464726573733a20756e61626c6520746f2073656e642076616c75652c20726563697069656e74206d61792068617665207265766572746564416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c4f72646572426f6f6b3a20696e73756666696369656e7420616d6f756e744f75744f72646572426f6f6b3a206f6e6c79207765746820636f756c6420626520777261707065644f72646572426f6f6b3a20696e73756666696369656e7420657865637574696f6e20666565536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f774f72646572426f6f6b3a20696e636f72726563742076616c7565207472616e736665727265644f72646572426f6f6b3a20696e76616c696420707269636520666f7220657865637574696f6e4f72646572426f6f6b3a20696e76616c6964205f706174682e6c656e677468005361666545524332303a204552433230206f7065726174696f6e20646964206e6f7420737563636565644f72646572426f6f6b3a20696e636f727265637420657865637574696f6e20666565207472616e73666572726564a2646970667358221220eb733ef03b253d6d90eafa87014672fde0e5a555bc379f04bf3248d7deb47dc564736f6c634300060c0033