Skip to content
Verified contractExact

Trading

Address0xbe2c35ab7d01acf8747a8f76446e9209129ffaed
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.7.3

 

Same code

Only this contract

 

Details

Compiler
solc 0.7.3+commit.9bfce1f6
Language
solidity
Optimization
Yes, 200 runs
EVM version
istanbul
License
Not stated
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
11,681,960
Creation transaction
0x8bb3def82c…680c43ced3

contracts/Trading.sol

pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;

import '@openzeppelin/contracts/math/SafeMath.sol';

import './interfaces/IProducts.sol';
import './interfaces/IQueue.sol';
import './interfaces/IToken.sol';
import './interfaces/ITreasury.sol';

import './libraries/Permit.sol';
import './libraries/SafeMathExt.sol';
import './libraries/UintSet.sol';

contract Trading {

    /* Libraries */

    using SafeMath for uint256;
    using SafeMathExt for uint256;
    using UintSet for UintSet.Set;

    /* Structs */

    struct Position {
        address sender; // 20 bytes
        bytes12 symbol; // 12 bytes
        uint64 margin; // 8 bytes
        uint64 leverage; // 8 bytes
        uint64 price; // 8 bytes
        uint48 block; // 7 bytes
        bool isBuy; // 1 byte
        uint256 id; // not stored
    }

    /* Variables */

    address private products;
    address private queue;
    address private treasury;

    // DAI
    address public currency;

    // minimum margin to open a position
    uint256 public minimumMargin;

    // 10^18 for DAI
    uint256 public currencyUnit;

    // user => balance
    mapping(address => uint256) public freeMargins;

    // id => Position
    mapping(uint256 => Position) public positions;

    // user => position ids
    mapping(address => UintSet.Set) private userPositionIds;

    // positions being liquidated
    mapping(uint256 => bool) public liquidatingIds;

    // user => bool
    mapping(address => uint256) public pausedUsers;

    // liquidator reward %
    uint256 public liquidatorReward;

    address public owner;
    bool private initialized;
    bool public paused;

    /* Events */
    event NewContracts(address products, address queue, address treasury);
    event NewMinimum(uint256 amount);
    event NewLiquidatorReward(uint256 amount);
    event Deposited(uint256 amount);
    event Withdrew(uint256 amount);

    event OrderSubmitted(
        uint256 id,
        address indexed sender,
        bool isBuy,
        bytes32 symbol,
        uint256 margin,
        uint256 leverage,
        uint256 positionId
    );

    event OrderCancelled(
        uint256 id,
        uint256 positionId,
        address indexed sender,
        string reason
    );

    event PositionOpened(
        uint256 positionId,
        address indexed sender,
        bool isBuy,
        bytes32 symbol,
        uint256 margin,
        uint256 leverage,
        uint256 price
    );

    event PositionLiquidated(
        uint256 positionId,
        address indexed sender,
        address indexed liquidator,
        uint256 marginLiquidated
    );

    event PositionClosed(
        uint256 positionId,
        address indexed sender,
        uint256 marginClosed,
        uint256 amountToReturn,
        uint256 entryPrice,
        uint256 price,
        uint256 leverage
    );

    event LiquidationSubmitted(
        uint256 id,
        uint256 positionId,
        address indexed sender
    );

    /* Initializer (called only once) */

    function initialize(address _currency) public {
        require(!initialized, '!initialized');
        initialized = true;
        owner = msg.sender;
        liquidatorReward = 10;
        currency = _currency;
        currencyUnit = SafeMathExt.base10pow(IToken(_currency).decimals());
    }

    /* Methods called by governance */

    function registerContracts(
        address _products,
        address _queue,
        address _treasury
    ) external onlyOwner {
        products = _products;
        queue = _queue;
        treasury = _treasury;
        emit NewContracts(_products, _queue, _treasury);
    }

    function setCurrencyMin(uint256 _amount) external onlyOwner {
        minimumMargin = _amount;
        emit NewMinimum(_amount);
    }

    function setLiquidatorReward(uint256 _amount) external onlyOwner {
        require(_amount <= 100, '!percent');
        liquidatorReward = _amount;
        emit NewLiquidatorReward(_amount);
    }

    function pauseUsers(address[] calldata users) external onlyOwner {
        for (uint256 i = 0; i < users.length; i++) {
            pausedUsers[users[i]] = block.number;
        }
    }

    function unpauseUsers(address[] calldata users) external onlyOwner {
        for (uint256 i = 0; i < users.length; i++) {
            pausedUsers[users[i]] = 0;
        }
    }

    // TODO review
    function capUserBalance(
        address user,
        uint256 newBalanceCap
    ) external onlyOwner {
        // user must be blocked in a previous transaction before we can cap the balance
        uint256 pauseBlockNumber = pausedUsers[user];
        require(pauseBlockNumber > 0 && pauseBlockNumber < block.number, '!user_not_paused');
        uint256 treasuryBalance = ITreasury(treasury).getUserBalance(user);
        // trading balance and newBalance are 8 decimals, treasuryBalance 18 decimals (in most cases)
        require(newBalanceCap.mulDecimal8(currencyUnit) >= treasuryBalance, '!too_low');
        if (freeMargins[user] > newBalanceCap) {
            freeMargins[user] = newBalanceCap;
        }
    }

    function pause() external onlyOwner {
        paused = true;
    }

    function unpause() external onlyOwner {
        paused = false;
    }

    /* Methods called by the client */

    function deposit(
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external whenNotPaused {
        uint256 amt = amount.mulDecimal8(currencyUnit);
        Permit.permit(currency, amt, msg.sender, treasury, deadline, v, r, s);
        ITreasury(treasury).userDeposit(msg.sender, amt);
        freeMargins[msg.sender] = freeMargins[msg.sender].add(amount);
        emit Deposited(amount);
    }

    function withdraw(
        uint256 amount
    ) external whenNotPaused whenNotUserPaused(msg.sender) {
        freeMargins[msg.sender] = freeMargins[msg.sender].sub(amount, '!balance');
        ITreasury(treasury).userWithdraw(msg.sender, amount.mulDecimal8(currencyUnit));
        emit Withdrew(amount);
    }

    function submitOrder(
        bool isBuy,
        bytes32 symbol,
        uint256 margin,
        uint256 leverage
    ) external whenNotPaused whenNotUserPaused(msg.sender) {
        require(margin >= minimumMargin, '!margin');
        require(leverage >= SafeMathExt.UNIT8, '!leverage');
        uint256 maxLeverage = IProducts(products).getMaxLeverage(symbol, true);
        require(maxLeverage > 0, '!symbol');
        require(leverage <= maxLeverage, '!max_leverage');
        freeMargins[msg.sender] = freeMargins[msg.sender].sub(margin, '!balance');
        uint256 id = _queueOrder(isBuy, symbol, margin, leverage, 0, address(0));
        positions[id] = Position({isBuy: isBuy, margin: SafeMathExt.safeUint64(margin), leverage: SafeMathExt.safeUint64(leverage), sender: msg.sender, symbol: bytes12(''), price: 0, block: 0, id: 0});
    }

    function submitOrderUpdate(
        uint256 positionId,
        uint256 margin
    ) external whenNotPaused {
        Position storage position = positions[positionId];
        require(position.price > 0, '!found');
        require(position.sender == msg.sender, '!authorized');
        // partial or full close
        require(margin <= uint256(position.margin), '!margin');
        _queueOrder(!position.isBuy, bytes32(position.symbol), margin, uint256(position.leverage), positionId, address(0));
    }

    function liquidatePositions(uint256[] calldata positionIds) external {
        uint256 length = positionIds.length;
        require(length < 6, '!too_many');
        for (uint256 i = 0; i < length; i++) {
            uint256 positionId = positionIds[i];
            Position storage position = positions[positionId];
            if (position.price > 0 && !liquidatingIds[positionId]) {
                liquidatingIds[positionId] = true;
                _queueOrder(!position.isBuy, bytes32(position.symbol), 0, 0, positionId, msg.sender);
            }
        }
    }

    function getUserPositions(address user) external view returns(Position[] memory _positions) {
        uint256 length = userPositionIds[user].length();
        _positions = new Position[](length);
        for (uint256 i=0; i < length; i++) {
            uint256 id = userPositionIds[user].at(i);
            Position memory positionWithId = positions[id];
            positionWithId.id = id;
            _positions[i] = positionWithId;
        }
        return _positions;
    }

    function getUserFreeMargin(address user) external view returns(uint256) {
        return freeMargins[user];
    }

    /* Queue methods */

    function processOrder(
        uint256 id,
        bytes32 symbol,
        uint256 price,
        uint256 margin,
        uint256 positionId,
        address liquidator
    ) external whenNotPaused onlyQueue {
        if (positionId > 0) {
            if (liquidator != address(0)) {
                delete liquidatingIds[positionId];
                Position memory position = positions[positionId];
                require(position.price > 0, '!found');
                uint256 positionMargin = uint256(position.margin);
                (uint256 pnl, bool isPnlNegative) = _calculatePnl(position, positionMargin, price);
                if (isPnlNegative && pnl >= positionMargin) {
                    _processLiquidation(liquidator, positionId, positionMargin, position.sender);
                }
            } else {
                _processClose(margin, price, positionId);
            }
        } else {
            _processOpen(id, symbol, price);
        }
    }

    function cancelOrder(
        uint256 id,
        uint256 positionId,
        address liquidator,
        string calldata reason
    ) external onlyQueue {
        if (positionId == 0) {
            // cancelling a new order
            Position storage position = positions[id];
            address sender = position.sender;
            uint256 margin = uint256(position.margin);
            delete positions[id];
            // release margin back to user
            freeMargins[sender] = freeMargins[sender].add(margin);
            emit OrderCancelled(id, id, sender, reason);
        } else if (liquidator != address(0)) {
            // cancelling a liquidation request
            delete liquidatingIds[id];
            emit OrderCancelled(id, positionId, liquidator, reason);
        } else {
            // cancelling a full or partial close order (sender could be address zero)
            emit OrderCancelled(id, positionId, positions[positionId].sender, reason);
        }
    }

    /* Internal methods */

    function _queueOrder(
        bool isBuy,
        bytes32 symbol,
        uint256 margin,
        uint256 leverage,
        uint256 positionId,
        address liquidator
    ) internal returns (uint256 id) {
        id = IQueue(queue).queueOrder(symbol, margin, positionId, liquidator);

        if (liquidator != address(0)) {
            emit LiquidationSubmitted(id, positionId, msg.sender);
        } else {
            emit OrderSubmitted(id, msg.sender, isBuy, symbol, margin, leverage, positionId);
        }
        return id;
    }

    function _processOpen(
        uint256 id,
        bytes32 symbol,
        uint256 price
    ) internal {
        Position storage position = positions[id];
        bool isBuy = position.isBuy;
        uint256 margin = uint256(position.margin);
        uint256 leverage = uint256(position.leverage);
        address sender = position.sender;
        // calculate execution price
        uint256 spread = IProducts(products).getSpread(symbol);
        if (isBuy) {
            price = price.mulDecimal8(SafeMathExt.UNIT8.add(spread));
        } else {
            price = price.mulDecimal8(SafeMathExt.UNIT8.sub(spread));
        }
        // complete the Position struct started in submitOrder
        position.symbol = bytes12(symbol);
        position.price = SafeMathExt.safeUint64(price);
        position.block = uint48(block.number);
        // user to position ID
        userPositionIds[sender].add(id);
        // event
        emit PositionOpened(id, sender, isBuy, symbol, margin, leverage, price);
    }

    function _processClose(
        uint256 margin,
        uint256 price,
        uint256 positionId
    ) internal {
        Position memory mPosition = positions[positionId];
        uint256 positionMargin = uint256(mPosition.margin);
        require(margin <= positionMargin, '!margin');
        uint256 spread = IProducts(products).getSpread(bytes32(mPosition.symbol));
        // execution price
        if (mPosition.isBuy) {
            price = price.mulDecimal8(SafeMathExt.UNIT8.sub(spread));
        } else {
            price = price.mulDecimal8(SafeMathExt.UNIT8.add(spread));
        }
        // pnl
        (uint256 pnl, bool isPnlNegative) = _calculatePnl(mPosition, margin, price);
        uint256 amountToReturn;
        if (isPnlNegative && pnl >= margin) {
            // position is liquidated
            delete positions[positionId];
            userPositionIds[mPosition.sender].remove(positionId);
            // transfer user margin to surplus
            ITreasury(treasury).collectFromUser(mPosition.sender, positionMargin.mulDecimal8(currencyUnit));
        } else {
            if (margin < positionMargin) {
                // partial close, update position margin
                Position storage position = positions[positionId];
                position.margin = SafeMathExt.safeUint64(positionMargin.sub(margin));
            } else {
                // full close, remove from mappings
                delete positions[positionId];
                userPositionIds[mPosition.sender].remove(positionId);
            }
            if (isPnlNegative) {
                amountToReturn = margin.sub(pnl);
                // return amountToReturn to free margin
                freeMargins[mPosition.sender] = freeMargins[mPosition.sender].add(amountToReturn);
                // collect pnl
                ITreasury(treasury).collectFromUser(mPosition.sender, pnl.mulDecimal8(currencyUnit));
            } else {
                amountToReturn = margin.add(pnl);
                freeMargins[mPosition.sender] = freeMargins[mPosition.sender].add(amountToReturn);
            }
        }
        emit PositionClosed(positionId, mPosition.sender, margin, amountToReturn, mPosition.price, price, mPosition.leverage);
    }

    function _processLiquidation(
        address liquidator,
        uint256 positionId,
        uint256 positionMargin,
        address positionSender
    ) internal {
        delete positions[positionId];
        userPositionIds[positionSender].remove(positionId);
        // collect margin from user
        ITreasury(treasury).collectFromUser(positionSender, positionMargin.mulDecimal8(currencyUnit));
        // pay liquidatorReward % of margin to liquidator
        uint256 liquidatorMargin = positionMargin.mul(liquidatorReward).div(100);
        freeMargins[liquidator] = freeMargins[liquidator].add(liquidatorMargin);
        emit PositionLiquidated(positionId, positionSender, liquidator, positionMargin);
    }

    /* Helpers */

    function _calculatePnl(
        Position memory position,
        uint256 margin,
        uint256 price
    ) internal view returns (uint256 pnl, bool isPnlNegative) {
        uint256 positionLeverage = uint256(position.leverage);
        uint256 positionPrice = uint256(position.price);
        if (position.isBuy) {
            if (price >= position.price) {
                pnl = margin.mul(positionLeverage).mul(price.sub(positionPrice)).div(positionPrice).div(SafeMathExt.UNIT8);
            } else {
                pnl = margin.mul(positionLeverage).mul(positionPrice.sub(price)).div(positionPrice).div(SafeMathExt.UNIT8);
                isPnlNegative = true;
            }
        } else {
            if (price > position.price) {
                pnl = margin.mul(positionLeverage).mul(price.sub(positionPrice)).div(positionPrice).div(SafeMathExt.UNIT8);
                isPnlNegative = true;
            } else {
                pnl = margin.mul(positionLeverage).mul(positionPrice.sub(price)).div(positionPrice).div(SafeMathExt.UNIT8);
            }
        }
        // Calculate funding to apply on this position
        uint256 fundingToApply = margin.mul(positionLeverage).mul(block.number.sub(uint256(position.block))).mul(IProducts(products).getFundingRate(bytes32(position.symbol))).div(1e16);
        // Subtract funding from pnl
        if (isPnlNegative) {
            pnl = pnl.add(fundingToApply);
        } else if (fundingToApply > pnl) {
            isPnlNegative = true;
            pnl = fundingToApply.sub(pnl);
        } else {
            pnl = pnl.sub(fundingToApply);
        }
        return (pnl, isPnlNegative);
    }

    /* Modifiers */

    modifier onlyOwner() {
        require(msg.sender == owner, '!authorized');
        _;
    }

    modifier onlyQueue() {
        require(msg.sender == queue, '!authorized');
        _;
    }

    modifier whenNotUserPaused(address user) {
        require(pausedUsers[user] == 0, '!pausedUser');
        _;
    }

    modifier whenNotPaused() {
        require(!paused, '!paused');
        _;
    }

}

@openzeppelin/contracts/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @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/interfaces/IEIP712.sol

pragma solidity ^0.7.3;

interface IEIP712 {

    /* ========== OPTIONAL VIEWS ========== */

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external view returns (bytes32);
    function nonces(address wallet) external view returns (uint256);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;

}

contracts/interfaces/IEIP712_DAI.sol

pragma solidity ^0.7.3;

interface IEIP712_DAI {

    function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;

}

contracts/interfaces/IProducts.sol

pragma solidity ^0.7.3;

interface IProducts {

	function getMaxLeverage(bytes32 symbol, bool checkDisabled) external view returns (uint256);
	function getFundingRate(bytes32 symbol) external view returns (uint256);
	function getSpread(bytes32 symbol) external view returns (uint256);

}

contracts/interfaces/IQueue.sol

pragma solidity ^0.7.3;

interface IQueue {

    function firstOrderId() external view returns (uint256);
    function nextOrderId() external view returns (uint256);
    function processedOrdersCount() external view returns (uint256);

    function queueOrder(bytes32 symbol, uint256 margin, uint256 positionId, address liquidator) external returns (uint256);

}

contracts/interfaces/IToken.sol

pragma solidity ^0.7.3;

import './IEIP712.sol';

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

interface IToken is IERC20, IEIP712 {

    /* ========== OPTIONAL VIEWS ========== */

    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);

    /* ========== VIEWS ========== */

    function paused() external view returns (bool);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function initialize(address synthTrading, string memory _name, string memory _symbol) external;

    function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
    function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);

    function mint(address to, uint256 amount) external;
    function burn(uint256 amount) external;
    function burnFrom(address account, uint256 amount) external;

    function pause() external;
    function unpause() external;

}

contracts/interfaces/ITreasury.sol

pragma solidity ^0.7.3;

interface ITreasury {

    function userDeposit(address user, uint256 amount) external;
    function userWithdraw(address user, uint256 amount) external;
    function collectFromUser(address user, uint256 amount) external;
    function payToUser(address user, uint256 amount) external;
    
    function getUserBalance(address user) external view returns (uint256);

}

contracts/libraries/Permit.sol

pragma solidity ^0.7.3;

import '../interfaces/IToken.sol';
import '../interfaces/IEIP712_DAI.sol';

library Permit {

	function permit(
		address currency,
		uint256 amount,
		address sender,
		address spender,
		uint256 deadline,
		uint8 v,
		bytes32 r,
		bytes32 s
	) internal {
		if (IToken(currency).allowance(sender, spender) < amount) {
		    if (keccak256(bytes(IToken(currency).symbol())) == 0xa5e92f3efb6826155f1f728e162af9d7cda33a574a1153b58f03ea01cc37e568) {
		        // DAI has a custom permit method
		        uint256 nonce = IToken(currency).nonces(sender);
		        IEIP712_DAI(currency).permit(sender, spender, nonce, deadline, true, v, r, s);
		    }/* else {
		        IToken(currency).permit(sender, spender, uint256(-1), deadline, v, r, s);
		    }*/
		}
	}

}

contracts/libraries/SafeMathExt.sol

pragma solidity ^0.7.3;

import '@openzeppelin/contracts/math/SafeMath.sol';

library SafeMathExt {

    using SafeMath for uint256;

    uint256 public constant UNIT8 = 1e8;
    uint256 public constant UNIT18 = 1e18;

    function base10pow(uint8 exponent) internal pure returns (uint256) {
        // very common
        if (exponent == 18) return 1e18;
        if (exponent == 6) return 1e6;

        uint256 result = 1;

        while (exponent >= 10) {
            result = result.mul(uint256(1e10));
            exponent -= 10;
        }

        while (exponent > 0) {
            result = result.mul(uint256(10));
            exponent--;
        }

        return result;
    }

    function mulDecimal(uint256 x, uint256 y) internal pure returns (uint256) {
        return x.mul(y) / UNIT18;
    }

    function divDecimal(uint256 x, uint256 y) internal pure returns (uint256) {
        return x.mul(UNIT18).div(y);
    }

    function mulDecimal8(uint256 x, uint256 y) internal pure returns (uint256) {
        return x.mul(y) / UNIT8;
    }

    function divDecimal8(uint256 x, uint256 y) internal pure returns (uint256) {
        return x.mul(UNIT8).div(y);
    }

    function safeUint64(uint256 x) internal pure returns (uint64) {
        require(x <= uint64(-1), 'SafeMath: cast overflow');
        return uint64(x);
    }

}

contracts/libraries/UintSet.sol

pragma solidity ^0.7.3;

library UintSet {

    struct Set {
        uint256[] _values;

        // Position of the value in the `values` array, plus 1 because index 0 means a value is not in the set
        mapping (uint256 => uint256) _indexes;
    }

    function add(Set storage set, uint256 value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    function remove(Set storage set, uint256 value) internal returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

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

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

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            uint256 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based

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

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

            return true;
        } else {
            return false;
        }
    }

    function contains(Set storage set, uint256 value) internal view returns (bool) {
        return set._indexes[value] != 0;
    }

    function length(Set storage set) internal view returns (uint256) {
        return set._values.length;
    }

    function at(Set storage set, uint256 index) internal view returns (uint256) {
        require(set._values.length > index, 'UintEnumerableSet: OUT_OF_BOUNDS');
        return set._values[index];
    }

}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "istanbul",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.