Contract 0x6bd780e7fdf01d77e4d475c821f1e7ae05409072 12

 

Contract Overview

Dolomite: Margin
Balance:
0 ETH

ETH Value:
$0.00

Token:
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x6eb66be2d6bc1f3809ed0efb44cd557b7b345f66c6662a105e6d9a32796d24e1Operate2230738042024-06-18 7:25:003 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000031020.01
0xed74d51bf7675e141ec14b27a1004a1ac60a28c7035fb27ff0aa7972cf2f77f2Operate2230723552024-06-18 7:18:573 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029960.01
0xd3f0d3a3841ade78d66255e26107d4367b58e3b824427b9b646f037cb57e5e0bOperate2230723402024-06-18 7:18:533 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029960.01
0x79e22ca7fb52db02382b3f90050cee901808ed4bffc4b4006e638ec8d925b8dcOperate2230723252024-06-18 7:18:503 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0x22fbe63d55bb5557e920fcb2684e243d1b55c4d7573ab671b9dd6a18b717e801Operate2230723102024-06-18 7:18:463 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0x8780bba94baed85e4d388ddafda40728e617d28e5f2ce5b009fa3a8c975776bfOperate2230722952024-06-18 7:18:423 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0xbd61a76a57b2d6ec491aaab6126018c7cc233d10549fd42878f25015341e3a05Operate2230722802024-06-18 7:18:383 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0x2653fe0fcab61fb5edc133f1c822b18e046f99ed2682dc9a29828a4cf78a4698Operate2230722652024-06-18 7:18:343 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0xb2d32b7c6ecddf3017a075853eaeb10621fb35b09973fbcb96572a09911f639fOperate2230722502024-06-18 7:18:313 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0x49226854efd11f57b6af0aa722c17c767485476992ef473510c575c2958019deOperate2230722352024-06-18 7:18:273 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0x9f5e649101e266e71af29487d8496c4e2f99db4e0756b475a8c7898440cc3b06Operate2230722202024-06-18 7:18:233 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029950.01
0x499e152a55cf8e1d414d9b664d62c99dbdcf9c6fb7897a830584e654f9e44ffdOperate2230722052024-06-18 7:18:193 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029960.01
0x3646212db4e0ac3b874c5a1f379829f826761d079d217f5385de65dda364bec7Operate2230721902024-06-18 7:18:163 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029960.01
0x0eb41bc982fad79a852ed9a40b2029a72c146bc76314f8125cd079d131ee0ebfOperate2230721752024-06-18 7:18:123 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029940.01
0xac915f6ec993d235ac888cb3722db369c0af8f619befbf42d9fdea51b91e340dOperate2230721602024-06-18 7:18:083 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029930.01
0xccd3774c6755de38582932400378608c0646ced796916ed711bb37dfade3c825Operate2230721452024-06-18 7:18:043 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000031190.01
0xd4e4ccdb32f6b28787f80b5c189bec51bf1834acaa1cbf7d5e49d3981abee0e4Operate2230719652024-06-18 7:17:193 days 9 hrs ago0x1ff6b8e1192eb0369006bbad76da9068b68961b2 IN  Dolomite: Margin0 ETH0.000029910.01
0x0ba21faf333b66de684349443984eb8908e2a9b72adb2256eac9c76e480b9305Operate1886760622024-03-09 14:05:04104 days 2 hrs ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000456650.1
0x83c9d6b15c7ac438dd820c5d2cdd5712814543f750555215f4617ecbe2912b86Operate1680565362024-01-07 16:04:37166 days 47 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000377680.1
0x13c038c48334a6a55a13ae24c046fe910c8815c1d9de81599c25502f02530a00Operate1680564102024-01-07 16:04:04166 days 48 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000377670.1
0x623cca18e7e5abefb62c248e03e468c76b6529f17ba49db11c858bdd4f291247Operate1680563302024-01-07 16:03:44166 days 48 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000378610.1
0x4a0b71d57e0277f25f4bf67ac209c36556275f1e227143e0293b06e57dd4dd05Operate1680562622024-01-07 16:03:27166 days 49 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000378040.1
0xa72ff96818c898acceb036989fbc5112c0843d016f9bc53cc60e21771f1a66f7Operate1680561922024-01-07 16:03:10166 days 49 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000379490.1
0x8a6ca9df1989f6204f5b8b99ef39f7ed460b54c12b8ee0dd9355c3cd1536e764Operate1680560902024-01-07 16:02:43166 days 49 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000373250.1
0x8f441c38b16dfe1f8213d93f3c9c3cf8daf5aa1b66c1ee485af07f2367802875Operate1680560472024-01-07 16:02:32166 days 49 mins ago0x52256ef863a713ef349ae6e97a7e8f35785145de IN  Dolomite: Margin0 ETH0.000380950.1
[ Download CSV Export 

OVERVIEW

Dolomite Margin is the core smart contract entry-point for Dolomite's margin system & DEX trading protocol.

Latest 25 internal transaction
Parent Txn Hash Block From To Value
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0x2f503beb8c79b739f55e5b702273267492f9ba900 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0x2f503beb8c79b739f55e5b702273267492f9ba900 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xea4e670fd64ae82af5a3d77b3db6b5e28a5522de0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago 0xb77a493a4950cad1b049e222d62bce14ff423c6f Dolomite: Margin0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xc2cbd99bb35b22c43010a8c8266cdff057f70bb10 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago 0xb77a493a4950cad1b049e222d62bce14ff423c6f Dolomite: Margin0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xea4e670fd64ae82af5a3d77b3db6b5e28a5522de0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago 0xb77a493a4950cad1b049e222d62bce14ff423c6f Dolomite: Margin0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xc2cbd99bb35b22c43010a8c8266cdff057f70bb10 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago 0xb77a493a4950cad1b049e222d62bce14ff423c6f Dolomite: Margin0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xea4e670fd64ae82af5a3d77b3db6b5e28a5522de0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago 0xb77a493a4950cad1b049e222d62bce14ff423c6f Dolomite: Margin0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xc2cbd99bb35b22c43010a8c8266cdff057f70bb10 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago 0xb77a493a4950cad1b049e222d62bce14ff423c6f Dolomite: Margin0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xb77a493a4950cad1b049e222d62bce14ff423c6f0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0x1e0be797880d3db0ce503cd40429a3a9f1cf56d70 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin Arbitrum: USDC Token0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0x353e0b387663b5dada800cc30e926f49e6adaf090 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin Wrapped Ether0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0x1e0be797880d3db0ce503cd40429a3a9f1cf56d70 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xea3fe12d8cc2e87f99e985ee271971c8080065310 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xea3fe12d8cc2e87f99e985ee271971c8080065310 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xea4e670fd64ae82af5a3d77b3db6b5e28a5522de0 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0xc2cbd99bb35b22c43010a8c8266cdff057f70bb10 ETH
0xe644043f710b99c2b8af4b34e0fdc0121690f4ee2a4232a235badb30316c13ad720786082023-03-21 9:45:34458 days 7 hrs ago Dolomite: Margin 0x7908b447ed2050043bb32daffab06739701245270 ETH
[ Download CSV Export 
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

Contract Source Code Verified (Exact Match)

Contract Name:
DolomiteMargin

Compiler Version
v0.5.16+commit.9c3226ce

Optimization Enabled:
Yes with 10000 runs

Other Settings:
default evmVersion
File 1 of 48 : DolomiteMargin.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Admin } from "./Admin.sol";
import { Getters } from "./Getters.sol";
import { Operation } from "./Operation.sol";
import { Permission } from "./Permission.sol";
import { State } from "./State.sol";
import { Storage } from "./lib/Storage.sol";
import { IDolomiteMargin } from "./interfaces/IDolomiteMargin.sol";


/**
 * @title DolomiteMargin
 * @author dYdX
 *
 * Main contract that inherits from other contracts
 */
contract DolomiteMargin is
    IDolomiteMargin,
    State,
    Admin,
    Getters,
    Operation,
    Permission
{
    // ============ Constructor ============

    constructor(
        Storage.RiskParams memory riskParams,
        Storage.RiskLimits memory riskLimits
    )
        public
    {
        g_state.riskParams = riskParams;
        g_state.riskLimits = riskLimits;
    }
}

File 2 of 48 : Account.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Types } from "./Types.sol";
import { EnumerableSet } from "./EnumerableSet.sol";


/**
 * @title Account
 * @author dYdX
 *
 * Library of structs and functions that represent an account
 */
library Account {
    // ============ Enums ============

    /*
     * Most-recently-cached account status.
     *
     * Normal: Can only be liquidated if the account values are violating the global margin-ratio.
     * Liquid: Can be liquidated no matter the account values.
     *         Can be vaporized if there are no more positive account values.
     * Vapor:  Has only negative (or zeroed) account values. Can be vaporized.
     *
     */
    enum Status {
        Normal,
        Liquid,
        Vapor
    }

    // ============ Structs ============

    // Represents the unique key that specifies an account
    struct Info {
        address owner;  // The address that owns the account
        uint256 number; // A nonce that allows a single address to control many accounts
    }

    // The complete storage for any account
    struct Storage {
        Status status;
        uint32 numberOfMarketsWithDebt;
        EnumerableSet.Set marketsWithNonZeroBalanceSet;
        mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
    }

    // ============ Library Functions ============

    function equals(
        Info memory a,
        Info memory b
    )
        internal
        pure
        returns (bool)
    {
        return a.owner == b.owner && a.number == b.number;
    }
}

File 3 of 48 : IERC20.sol
pragma solidity ^0.5.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
 * the optional functions; to access them see {ERC20Detailed}.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

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

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

File 4 of 48 : Ownable.sol
pragma solidity ^0.5.0;

import "../GSN/Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
contract Ownable is Context {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () internal {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

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

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

    /**
     * @dev Returns true if the caller is the current owner.
     */
    function isOwner() public view returns (bool) {
        return _msgSender() == _owner;
    }

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     */
    function _transferOwnership(address newOwner) internal {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

File 5 of 48 : SafeMath.sol
pragma solidity ^0.5.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.
     *
     * _Available since v2.4.0._
     */
    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.
     *
     * _Available since v2.4.0._
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        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.
     *
     * _Available since v2.4.0._
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

File 6 of 48 : Math.sol
pragma solidity ^0.5.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}

File 7 of 48 : Context.sol
pragma solidity ^0.5.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
contract Context {
    // Empty internal constructor, to prevent people from mistakenly deploying
    // an instance of this contract, which should be used via inheritance.
    constructor () internal { }
    // solhint-disable-previous-line no-empty-blocks

    function _msgSender() internal view returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

File 8 of 48 : Types.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { DolomiteMarginMath } from "./DolomiteMarginMath.sol";


/**
 * @title Types
 * @author dYdX
 *
 * Library for interacting with the basic structs used in DolomiteMargin
 */
library Types {
    using DolomiteMarginMath for uint256;

    // ============ Permission ============

    struct OperatorArg {
        address operator;
        bool trusted;
    }

    // ============ AssetAmount ============

    enum AssetDenomination {
        Wei, // the amount is denominated in wei
        Par  // the amount is denominated in par
    }

    enum AssetReference {
        Delta, // the amount is given as a delta from the current value
        Target // the amount is given as an exact number to end up at
    }

    struct AssetAmount {
        bool sign; // true if positive
        AssetDenomination denomination;
        AssetReference ref;
        uint256 value;
    }

    // ============ Par (Principal Amount) ============

    // Total borrow and supply values for a market
    struct TotalPar {
        uint128 borrow;
        uint128 supply;
    }

    // Individual principal amount for an account
    struct Par {
        bool sign; // true if positive
        uint128 value;
    }

    function zeroPar()
        internal
        pure
        returns (Par memory)
    {
        return Par({
            sign: false,
            value: 0
        });
    }

    function sub(
        Par memory a,
        Par memory b
    )
        internal
        pure
        returns (Par memory)
    {
        return add(a, negative(b));
    }

    function add(
        Par memory a,
        Par memory b
    )
        internal
        pure
        returns (Par memory)
    {
        Par memory result;
        if (a.sign == b.sign) {
            result.sign = a.sign;
            result.value = SafeMath.add(a.value, b.value).to128();
        } else {
            if (a.value >= b.value) {
                result.sign = a.sign;
                result.value = SafeMath.sub(a.value, b.value).to128();
            } else {
                result.sign = b.sign;
                result.value = SafeMath.sub(b.value, a.value).to128();
            }
        }
        return result;
    }

    function equals(
        Par memory a,
        Par memory b
    )
        internal
        pure
        returns (bool)
    {
        if (a.value == b.value) {
            if (a.value == 0) {
                return true;
            }
            return a.sign == b.sign;
        }
        return false;
    }

    function negative(
        Par memory a
    )
        internal
        pure
        returns (Par memory)
    {
        return Par({
            sign: !a.sign,
            value: a.value
        });
    }

    function isNegative(
        Par memory a
    )
        internal
        pure
        returns (bool)
    {
        return !a.sign && a.value > 0;
    }

    function isPositive(
        Par memory a
    )
        internal
        pure
        returns (bool)
    {
        return a.sign && a.value > 0;
    }

    function isZero(
        Par memory a
    )
        internal
        pure
        returns (bool)
    {
        return a.value == 0;
    }

    function isLessThanZero(
        Par memory a
    )
        internal
        pure
        returns (bool)
    {
        return a.value > 0 && !a.sign;
    }

    function isGreaterThanOrEqualToZero(
        Par memory a
    )
        internal
        pure
        returns (bool)
    {
        return isZero(a) || a.sign;
    }

    // ============ Wei (Token Amount) ============

    // Individual token amount for an account
    struct Wei {
        bool sign; // true if positive
        uint256 value;
    }

    function zeroWei()
        internal
        pure
        returns (Wei memory)
    {
        return Wei({
            sign: false,
            value: 0
        });
    }

    function sub(
        Wei memory a,
        Wei memory b
    )
        internal
        pure
        returns (Wei memory)
    {
        return add(a, negative(b));
    }

    function add(
        Wei memory a,
        Wei memory b
    )
        internal
        pure
        returns (Wei memory)
    {
        Wei memory result;
        if (a.sign == b.sign) {
            result.sign = a.sign;
            result.value = SafeMath.add(a.value, b.value);
        } else {
            if (a.value >= b.value) {
                result.sign = a.sign;
                result.value = SafeMath.sub(a.value, b.value);
            } else {
                result.sign = b.sign;
                result.value = SafeMath.sub(b.value, a.value);
            }
        }
        return result;
    }

    function equals(
        Wei memory a,
        Wei memory b
    )
        internal
        pure
        returns (bool)
    {
        if (a.value == b.value) {
            if (a.value == 0) {
                return true;
            }
            return a.sign == b.sign;
        }
        return false;
    }

    function negative(
        Wei memory a
    )
        internal
        pure
        returns (Wei memory)
    {
        return Wei({
            sign: !a.sign,
            value: a.value
        });
    }

    function isNegative(
        Wei memory a
    )
        internal
        pure
        returns (bool)
    {
        return !a.sign && a.value > 0;
    }

    function isPositive(
        Wei memory a
    )
        internal
        pure
        returns (bool)
    {
        return a.sign && a.value > 0;
    }

    function isZero(
        Wei memory a
    )
        internal
        pure
        returns (bool)
    {
        return a.value == 0;
    }
}

File 9 of 48 : Token.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { IERC20Detailed } from "../interfaces/IERC20Detailed.sol";


/**
 * @title Token
 * @author dYdX
 *
 * This library contains basic functions for interacting with ERC20 tokens. Modified to work with
 * tokens that don't adhere strictly to the ERC20 standard (for example tokens that don't return a
 * boolean value on success).
 */
library Token {

    // ============ Library Functions ============

    function transfer(
        address token,
        address to,
        uint256 amount
    )
        internal
    {
        if (amount == 0 || to == address(this)) {
            return;
        }

        _callOptionalReturn(
            token,
            abi.encodeWithSelector(IERC20Detailed(token).transfer.selector, to, amount),
            "Token: transfer failed"
        );
    }

    function transferFrom(
        address token,
        address from,
        address to,
        uint256 amount
    )
        internal
    {
        if (amount == 0 || to == from) {
            return;
        }

        // solium-disable arg-overflow
        _callOptionalReturn(
            token,
            abi.encodeWithSelector(IERC20Detailed(token).transferFrom.selector, from, to, amount),
            "Token: transferFrom failed"
        );
        // solium-enable arg-overflow
    }

    // ============ Private Functions ============

    function _callOptionalReturn(address token, bytes memory data, string memory error) 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.

        // A Solidity high level call has three parts:
        // 1. The target address is checked to contain contract code. Not needed since tokens are manually added
        // 2. The call itself is made, and success asserted
        // 3. The return value is decoded, which in turn checks the size of the returned data.

        // solium-disable-next-line security/no-low-level-calls
        (bool success, bytes memory returnData) = token.call(data);
        require(success, error);

        if (returnData.length > 0) {
            // Return data is optional
            require(abi.decode(returnData, (bool)), error);
        }
    }

}

File 10 of 48 : Time.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

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


/**
 * @title Time
 * @author dYdX
 *
 * Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106)
 */
library Time {

    // ============ Library Functions ============

    function currentTime()
        internal
        view
        returns (uint32)
    {
        return DolomiteMarginMath.to32(block.timestamp);
    }
}

File 11 of 48 : Storage.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Account } from "./Account.sol";
import { Bits } from "./Bits.sol";
import { Cache } from "./Cache.sol";
import { Decimal } from "./Decimal.sol";
import { Interest } from "./Interest.sol";
import { EnumerableSet } from "./EnumerableSet.sol";
import { DolomiteMarginMath } from "./DolomiteMarginMath.sol";
import { Monetary } from "./Monetary.sol";
import { Require } from "./Require.sol";
import { Time } from "./Time.sol";
import { Token } from "./Token.sol";
import { Types } from "./Types.sol";
import { IERC20Detailed } from "../interfaces/IERC20Detailed.sol";
import { IInterestSetter } from "../interfaces/IInterestSetter.sol";
import { IPriceOracle } from "../interfaces/IPriceOracle.sol";


/**
 * @title Storage
 * @author dYdX
 *
 * Functions for reading, writing, and verifying state in DolomiteMargin
 */
library Storage {
    using Cache for Cache.MarketCache;
    using Storage for Storage.State;
    using DolomiteMarginMath for uint256;
    using Types for Types.Par;
    using Types for Types.Wei;
    using SafeMath for uint256;
    using EnumerableSet for EnumerableSet.Set;

    // ============ Constants ============

    bytes32 internal constant FILE = "Storage";

    // ============ Structs ============

    // All information necessary for tracking a market
    struct Market {
        // Contract address of the associated ERC20 token
        address token;

        // Whether additional borrows are allowed for this market
        bool isClosing;

        // Whether this market can be removed and its ID can be recycled and reused
        bool isRecyclable;

        // Total aggregated supply and borrow amount of the entire market
        Types.TotalPar totalPar;

        // Interest index of the market
        Interest.Index index;

        // Contract address of the price oracle for this market
        IPriceOracle priceOracle;

        // Contract address of the interest setter for this market
        IInterestSetter interestSetter;

        // Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's
        // required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and
        // increasing its borrowed value. This is done through the following operation:
        // `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))`
        // This number increases the user's borrowed wei by multiplying it by:
        // `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))`
        Decimal.D256 marginPremium;

        // Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the
        // `liquidationSpread` using the following formula:
        // `liquidationSpread = liquidationSpread * (1 + spreadPremium)`
        // NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0
        // (when performing a liquidation between two markets)
        Decimal.D256 spreadPremium;

        // The maximum amount that can be held by the protocol. This allows the protocol to cap any additional risk
        // that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this
        // value to 0 is analogous to having no limit. This value can never be below 0.
        Types.Wei maxWei;
    }

    // The global risk parameters that govern the health and security of the system
    struct RiskParams {
        // Required ratio of over-collateralization
        Decimal.D256 marginRatio;

        // Percentage penalty incurred by liquidated accounts
        Decimal.D256 liquidationSpread;

        // Percentage of the borrower's interest fee that gets passed to the suppliers
        Decimal.D256 earningsRate;

        // The minimum absolute borrow value of an account
        // There must be sufficient incentivize to liquidate undercollateralized accounts
        Monetary.Value minBorrowedValue;

        // The maximum number of markets a user can have a non-zero balance for a given account.
        uint256 accountMaxNumberOfMarketsWithBalances;
    }

    // The maximum RiskParam values that can be set
    struct RiskLimits {
        // The highest that the ratio can be for liquidating under-water accounts
        uint64 marginRatioMax;
        // The highest that the liquidation rewards can be when a liquidator liquidates an account
        uint64 liquidationSpreadMax;
        // The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of
        // 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give
        // suppliers 90% of the interest that borrowers pay.
        uint64 earningsRateMax;
        // The highest min margin ratio premium that can be applied to a particular market. Meaning, a value of 100%
        // (1e18) would require borrowers to maintain an extra 100% collateral to maintain a healthy margin ratio. This
        // value works by increasing the debt owed and decreasing the supply held for the particular market by this
        // amount, plus 1e18 (since a value of 10% needs to be applied as `decimal.plusOne`)
        uint64 marginPremiumMax;
        // The highest liquidation reward that can be applied to a particular market. This percentage is applied
        // in addition to the liquidation spread in `RiskParams`. Meaning a value of 1e18 is 100%. It is calculated as:
        // `liquidationSpread * Decimal.onePlus(spreadPremium)`
        uint64 spreadPremiumMax;
        uint128 minBorrowedValueMax;
    }

    // The entire storage state of DolomiteMargin
    struct State {
        // number of markets
        uint256 numMarkets;

        // marketId => Market
        mapping (uint256 => Market) markets;

        // token address => marketId
        mapping (address => uint256) tokenToMarketId;

        // Linked list from marketId to the next recycled market id
        mapping(uint256 => uint256) recycledMarketIds;

        // owner => account number => Account
        mapping (address => mapping (uint256 => Account.Storage)) accounts;

        // Addresses that can control other users accounts
        mapping (address => mapping (address => bool)) operators;

        // Addresses that can control all users accounts
        mapping (address => bool) globalOperators;

        // Addresses of auto traders that can only be called by global operators. IE for expirations
        mapping (address => bool) specialAutoTraders;

        // mutable risk parameters of the system
        RiskParams riskParams;

        // immutable risk limits of the system
        RiskLimits riskLimits;
    }

    // ============ Functions ============

    function getToken(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        view
        returns (address)
    {
        return state.markets[marketId].token;
    }

    function getTotalPar(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        view
        returns (Types.TotalPar memory)
    {
        return state.markets[marketId].totalPar;
    }

    function getMaxWei(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        view
        returns (Types.Wei memory)
    {
        return state.markets[marketId].maxWei;
    }

    function getIndex(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        view
        returns (Interest.Index memory)
    {
        return state.markets[marketId].index;
    }

    function getNumExcessTokens(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        view
        returns (Types.Wei memory)
    {
        Interest.Index memory index = state.getIndex(marketId);
        Types.TotalPar memory totalPar = state.getTotalPar(marketId);

        address token = state.getToken(marketId);

        Types.Wei memory balanceWei = Types.Wei({
            sign: true,
            value: IERC20Detailed(token).balanceOf(address(this))
        });

        (
            Types.Wei memory supplyWei,
            Types.Wei memory borrowWei
        ) = Interest.totalParToWei(totalPar, index);

        // borrowWei is negative, so subtracting it makes the value more positive
        return balanceWei.sub(borrowWei).sub(supplyWei);
    }

    function getStatus(
        Storage.State storage state,
        Account.Info memory account
    )
        internal
        view
        returns (Account.Status)
    {
        return state.accounts[account.owner][account.number].status;
    }

    function getPar(
        Storage.State storage state,
        Account.Info memory account,
        uint256 marketId
    )
        internal
        view
        returns (Types.Par memory)
    {
        return state.accounts[account.owner][account.number].balances[marketId];
    }

    function getWei(
        Storage.State storage state,
        Account.Info memory account,
        uint256 marketId,
        Interest.Index memory index
    )
        internal
        view
        returns (Types.Wei memory)
    {
        Types.Par memory par = state.getPar(account, marketId);

        if (par.isZero()) {
            return Types.zeroWei();
        }

        return Interest.parToWei(par, index);
    }

    function getMarketsWithBalancesSet(
        Storage.State storage state,
        Account.Info memory account
    )
    internal
    view
    returns (EnumerableSet.Set storage)
    {
        return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet;
    }

    function getMarketsWithBalances(
        Storage.State storage state,
        Account.Info memory account
    )
    internal
    view
    returns (uint256[] memory)
    {
        return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.values();
    }

    function getAccountMarketWithBalanceAtIndex(
        Storage.State storage state,
        Account.Info memory account,
        uint256 index
    )
    internal
    view
    returns (uint256)
    {
        return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.getAtIndex(index);
    }

    function getNumberOfMarketsWithBalances(
        Storage.State storage state,
        Account.Info memory account
    )
    internal
    view
    returns (uint256)
    {
        return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.length();
    }

    function getAccountNumberOfMarketsWithDebt(
        Storage.State storage state,
        Account.Info memory account
    )
    internal
    view
    returns (uint256)
    {
        return state.accounts[account.owner][account.number].numberOfMarketsWithDebt;
    }

    function getLiquidationSpreadForPair(
        Storage.State storage state,
        uint256 heldMarketId,
        uint256 owedMarketId
    )
        internal
        view
        returns (Decimal.D256 memory)
    {
        uint256 result = state.riskParams.liquidationSpread.value;
        result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].spreadPremium));
        result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].spreadPremium));
        return Decimal.D256({
            value: result
        });
    }

    function fetchNewIndex(
        Storage.State storage state,
        uint256 marketId,
        Interest.Index memory index
    )
        internal
        view
        returns (Interest.Index memory)
    {
        Interest.Rate memory rate = state.fetchInterestRate(marketId, index);

        return Interest.calculateNewIndex(
            index,
            rate,
            state.getTotalPar(marketId),
            state.riskParams.earningsRate
        );
    }

    function fetchInterestRate(
        Storage.State storage state,
        uint256 marketId,
        Interest.Index memory index
    )
        internal
        view
        returns (Interest.Rate memory)
    {
        Types.TotalPar memory totalPar = state.getTotalPar(marketId);
        (
            Types.Wei memory supplyWei,
            Types.Wei memory borrowWei
        ) = Interest.totalParToWei(totalPar, index);

        Interest.Rate memory rate = state.markets[marketId].interestSetter.getInterestRate(
            state.getToken(marketId),
            borrowWei.value,
            supplyWei.value
        );

        return rate;
    }

    function fetchPrice(
        Storage.State storage state,
        uint256 marketId,
        address token
    )
        internal
        view
        returns (Monetary.Price memory)
    {
        IPriceOracle oracle = IPriceOracle(state.markets[marketId].priceOracle);
        Monetary.Price memory price = oracle.getPrice(token);
        Require.that(
            price.value != 0,
            FILE,
            "Price cannot be zero",
            marketId
        );
        return price;
    }

    function getAccountValues(
        Storage.State storage state,
        Account.Info memory account,
        Cache.MarketCache memory cache,
        bool adjustForLiquidity
    )
        internal
        view
        returns (Monetary.Value memory, Monetary.Value memory)
    {
        Monetary.Value memory supplyValue;
        Monetary.Value memory borrowValue;

        uint256 numMarkets = cache.getNumMarkets();
        for (uint256 i = 0; i < numMarkets; i++) {
            Types.Wei memory userWei = state.getWei(account, cache.getAtIndex(i).marketId, cache.getAtIndex(i).index);

            if (userWei.isZero()) {
                continue;
            }

            uint256 assetValue = userWei.value.mul(cache.getAtIndex(i).price.value);
            Decimal.D256 memory adjust = Decimal.one();
            if (adjustForLiquidity) {
                adjust = Decimal.onePlus(state.markets[cache.getAtIndex(i).marketId].marginPremium);
            }

            if (userWei.sign) {
                supplyValue.value = supplyValue.value.add(Decimal.div(assetValue, adjust));
            } else {
                borrowValue.value = borrowValue.value.add(Decimal.mul(assetValue, adjust));
            }
        }

        return (supplyValue, borrowValue);
    }

    function isCollateralized(
        Storage.State storage state,
        Account.Info memory account,
        Cache.MarketCache memory cache,
        bool requireMinBorrow
    )
        internal
        view
        returns (bool)
    {
        if (state.getAccountNumberOfMarketsWithDebt(account) == 0) {
            // The user does not have a balance with a borrow amount, so they must be collateralized
            return true;
        }

        // get account values (adjusted for liquidity)
        (
            Monetary.Value memory supplyValue,
            Monetary.Value memory borrowValue
        ) = state.getAccountValues(account, cache, /* adjustForLiquidity = */ true);

        if (requireMinBorrow) {
            Require.that(
                borrowValue.value >= state.riskParams.minBorrowedValue.value,
                FILE,
                "Borrow value too low",
                account.owner,
                account.number
            );
        }

        uint256 requiredMargin = Decimal.mul(borrowValue.value, state.riskParams.marginRatio);

        return supplyValue.value >= borrowValue.value.add(requiredMargin);
    }

    function isGlobalOperator(
        Storage.State storage state,
        address operator
    )
        internal
        view
        returns (bool)
    {
        return state.globalOperators[operator];
    }

    function isAutoTraderSpecial(
        Storage.State storage state,
        address autoTrader
    )
        internal
        view
        returns (bool)
    {
        return state.specialAutoTraders[autoTrader];
    }

    function isLocalOperator(
        Storage.State storage state,
        address owner,
        address operator
    )
        internal
        view
        returns (bool)
    {
        return state.operators[owner][operator];
    }

    function requireIsGlobalOperator(
        Storage.State storage state,
        address operator
    )
        internal
        view
    {
        bool isValidOperator = state.isGlobalOperator(operator);

        Require.that(
            isValidOperator,
            FILE,
            "Unpermissioned global operator",
            operator
        );
    }

    function requireIsOperator(
        Storage.State storage state,
        Account.Info memory account,
        address operator
    )
        internal
        view
    {
        bool isValidOperator =
            operator == account.owner
            || state.isGlobalOperator(operator)
            || state.isLocalOperator(account.owner, operator);

        Require.that(
            isValidOperator,
            FILE,
            "Unpermissioned operator",
            operator
        );
    }

    /**
     * Determine and set an account's balance based on the intended balance change. Return the
     * equivalent amount in wei
     */
    function getNewParAndDeltaWei(
        Storage.State storage state,
        Account.Info memory account,
        uint256 marketId,
        Interest.Index memory index,
        Types.AssetAmount memory amount
    )
        internal
        view
        returns (Types.Par memory, Types.Wei memory)
    {
        Types.Par memory oldPar = state.getPar(account, marketId);

        if (amount.value == 0 && amount.ref == Types.AssetReference.Delta) {
            return (oldPar, Types.zeroWei());
        }

        Types.Wei memory oldWei = Interest.parToWei(oldPar, index);
        Types.Par memory newPar;
        Types.Wei memory deltaWei;

        if (amount.denomination == Types.AssetDenomination.Wei) {
            deltaWei = Types.Wei({
                sign: amount.sign,
                value: amount.value
            });
            if (amount.ref == Types.AssetReference.Target) {
                deltaWei = deltaWei.sub(oldWei);
            }
            newPar = Interest.weiToPar(oldWei.add(deltaWei), index);
        } else { // AssetDenomination.Par
            newPar = Types.Par({
                sign: amount.sign,
                value: amount.value.to128()
            });
            if (amount.ref == Types.AssetReference.Delta) {
                newPar = oldPar.add(newPar);
            }
            deltaWei = Interest.parToWei(newPar, index).sub(oldWei);
        }

        return (newPar, deltaWei);
    }

    function getNewParAndDeltaWeiForLiquidation(
        Storage.State storage state,
        Account.Info memory account,
        uint256 marketId,
        Interest.Index memory index,
        Types.AssetAmount memory amount
    )
        internal
        view
        returns (Types.Par memory, Types.Wei memory)
    {
        Types.Par memory oldPar = state.getPar(account, marketId);

        Require.that(
            !oldPar.isPositive(),
            FILE,
            "Owed balance cannot be positive",
            account.owner,
            account.number
        );

        (
            Types.Par memory newPar,
            Types.Wei memory deltaWei
        ) = state.getNewParAndDeltaWei(
            account,
            marketId,
            index,
            amount
        );

        // if attempting to over-repay the owed asset, bound it by the maximum
        if (newPar.isPositive()) {
            newPar = Types.zeroPar();
            deltaWei = state.getWei(account, marketId, index).negative();
        }

        Require.that(
            !deltaWei.isNegative() && oldPar.value >= newPar.value,
            FILE,
            "Owed balance cannot increase",
            account.owner,
            account.number
        );

        // if not paying back enough wei to repay any par, then bound wei to zero
        if (oldPar.equals(newPar)) {
            deltaWei = Types.zeroWei();
        }

        return (newPar, deltaWei);
    }

    function isVaporizable(
        Storage.State storage state,
        Account.Info memory account,
        Cache.MarketCache memory cache
    )
        internal
        view
        returns (bool)
    {
        bool hasNegative = false;
        uint256 numMarkets = cache.getNumMarkets();
        for (uint256 i = 0; i < numMarkets; i++) {
            Types.Par memory par = state.getPar(account, cache.getAtIndex(i).marketId);
            if (par.isZero()) {
                continue;
            } else if (par.sign) {
                return false;
            } else {
                hasNegative = true;
            }
        }
        return hasNegative;
    }

    // =============== Setter Functions ===============

    function updateIndex(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        returns (Interest.Index memory)
    {
        Interest.Index memory index = state.getIndex(marketId);
        if (index.lastUpdate == Time.currentTime()) {
            return index;
        }
        return state.markets[marketId].index = state.fetchNewIndex(marketId, index);
    }

    function setStatus(
        Storage.State storage state,
        Account.Info memory account,
        Account.Status status
    )
        internal
    {
        state.accounts[account.owner][account.number].status = status;
    }

    function setPar(
        Storage.State storage state,
        Account.Info memory account,
        uint256 marketId,
        Types.Par memory newPar
    )
        internal
    {
        Types.Par memory oldPar = state.getPar(account, marketId);

        if (Types.equals(oldPar, newPar)) {
            // GUARD statement
            return;
        }

        // updateTotalPar
        Types.TotalPar memory totalPar = state.getTotalPar(marketId);

        // roll-back oldPar
        if (oldPar.sign) {
            totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128();
        } else {
            totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128();
        }

        // roll-forward newPar
        if (newPar.sign) {
            totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128();
        } else {
            totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128();
        }

        if (oldPar.isLessThanZero() && newPar.isGreaterThanOrEqualToZero()) {
            // user went from borrowing to repaying or positive
            state.accounts[account.owner][account.number].numberOfMarketsWithDebt -= 1;
        } else if (oldPar.isGreaterThanOrEqualToZero() && newPar.isLessThanZero()) {
            // user went from zero or positive to borrowing
            state.accounts[account.owner][account.number].numberOfMarketsWithDebt += 1;
        }

        if (newPar.isZero() && (!oldPar.isZero())) {
            // User went from a non-zero balance to zero. Remove the market from the set.
            state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.remove(marketId);
        } else if ((!newPar.isZero()) && oldPar.isZero()) {
            // User went from zero to non-zero. Add the market to the set.
            state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.add(marketId);
        }

        state.markets[marketId].totalPar = totalPar;
        state.accounts[account.owner][account.number].balances[marketId] = newPar;
    }

    /**
     * Determine and set an account's balance based on a change in wei
     */
    function setParFromDeltaWei(
        Storage.State storage state,
        Account.Info memory account,
        uint256 marketId,
        Interest.Index memory index,
        Types.Wei memory deltaWei
    )
        internal
    {
        if (deltaWei.isZero()) {
            return;
        }
        Types.Wei memory oldWei = state.getWei(account, marketId, index);
        Types.Wei memory newWei = oldWei.add(deltaWei);
        Types.Par memory newPar = Interest.weiToPar(newWei, index);
        state.setPar(
            account,
            marketId,
            newPar
        );
    }

    /**
     * Initializes the cache using the set bits
     */
    function initializeCache(
        Storage.State storage state,
        Cache.MarketCache memory cache
    ) internal view {
        cache.markets = new Cache.MarketInfo[](cache.marketsLength);
        uint counter = 0;

        // Really neat byproduct of iterating through a bitmap using the least significant bit, where each set flag
        // represents the marketId, --> the initialized `cache.markets` array is sorted in O(n)!
        // Meaning, this function call is O(n) where `n` is the number of markets in the cache
        for (uint i = 0; i < cache.marketBitmaps.length; i++) {
            uint bitmap = cache.marketBitmaps[i];
            while (bitmap != 0) {
                uint nextSetBit = Bits.getLeastSignificantBit(bitmap);
                uint marketId = Bits.getMarketIdFromBit(i, nextSetBit);
                address token = state.getToken(marketId);
                Types.TotalPar memory totalPar = state.getTotalPar(marketId);
                cache.markets[counter++] = Cache.MarketInfo({
                    marketId: marketId,
                    token: token,
                    isClosing: state.markets[marketId].isClosing,
                    borrowPar: totalPar.borrow,
                    supplyPar: totalPar.supply,
                    index: state.getIndex(marketId),
                    price: state.fetchPrice(marketId, token)
                });

                // unset the set bit
                bitmap = Bits.unsetBit(bitmap, nextSetBit);
            }
            if (counter == cache.marketsLength) {
                break;
            }
        }

        Require.that(
            cache.marketsLength == counter,
            FILE,
            "cache initialized improperly",
            cache.marketsLength,
            cache.markets.length
        );
    }
}

File 12 of 48 : SafeLiquidationCallback.sol
/*

    Copyright 2022 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";

import { ILiquidationCallback } from "../interfaces/ILiquidationCallback.sol";
import { Account } from "../lib/Account.sol";
import { ExcessivelySafeCall } from "../lib/ExcessivelySafeCall.sol";
import { DolomiteMarginMath } from "../lib/DolomiteMarginMath.sol";
import { Types } from "../lib/Types.sol";


library SafeLiquidationCallback {
    using Address for address;
    using ExcessivelySafeCall for address;

    // ============ Events ============

    event LogLiquidationCallbackSuccess(address indexed liquidAccountOwner, uint liquidAccountNumber);

    event LogLiquidationCallbackFailure(address indexed liquidAccountOwner, uint liquidAccountNumber, string reason);

    // ============ Functions ============

    function callLiquidateCallbackIfNecessary(
        Account.Info memory liquidAccount,
        uint heldMarket,
        Types.Wei memory heldDeltaWei,
        uint owedMarket,
        Types.Wei memory owedDeltaWei
    ) internal {
        if (liquidAccount.owner.isContract()) {
            uint16 maxCopyBytes = 256;
            (bool isCallSuccessful, bytes memory result) = liquidAccount.owner.excessivelySafeCall(
                /* _gas= */ Math.min(gasleft(), 1000000), // send, at most, 1,000,000 gas to the liquidation callback
                maxCopyBytes, // receive at-most this many bytes worth of return data
                abi.encodeWithSelector(
                    ILiquidationCallback(liquidAccount.owner).onLiquidate.selector,
                    liquidAccount.number,
                    heldMarket,
                    heldDeltaWei,
                    owedMarket,
                    owedDeltaWei
                )
            );

            if (isCallSuccessful) {
                emit LogLiquidationCallbackSuccess(liquidAccount.owner, liquidAccount.number);
            } else {
                // For reversions:
                // - the first 4 bytes is the method ID
                // - the next 32 bytes is the offset (hardcoded 0x20)
                // - the next 32 bytes is the length of the string
                // Here is an example result. The first 68 bytes (136 hexadecimal characters) are the templated
                // 08c379a0                                                         // erroring method ID
                // 0000000000000000000000000000000000000000000000000000000000000020 // offset to where string is
                // 0000000000000000000000000000000000000000000000000000000000000001 // string length
                // 2100000000000000000000000000000000000000000000000000000000000000 // string itself - not templated
                if (result.length < 68) {
                    result = bytes("");
                } else {
                    // parse the result bytes error message into a human-readable string
                    uint length;
                    // solium-disable-next-line security/no-inline-assembly
                    assembly {
                        result := add(result, 0x04)
                        length := mload(add(result, 0x40))
                        if gt(length, sub(maxCopyBytes, 0x44)) {
                            // if the length from `result` is longer than the max length, subtract the 68 bytes
                            // from the maxCopyBytes
                            mstore(add(result, 0x40), sub(maxCopyBytes, 0x44))
                        }
                    }
                    result = bytes(abi.decode(result, (string)));
                }
                emit LogLiquidationCallbackFailure(
                    liquidAccount.owner,
                    liquidAccount.number,
                    string(result)
                );
            }
        }
    }

}

File 13 of 48 : Require.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;


/**
 * @title Require
 * @author dYdX
 *
 * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
 */
library Require {

    // ============ Constants ============

    uint256 constant ASCII_ZERO = 48; // '0'
    uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
    uint256 constant ASCII_LOWER_EX = 120; // 'x'
    bytes2 constant COLON = 0x3a20; // ': '
    bytes2 constant COMMA = 0x2c20; // ', '
    bytes2 constant LPAREN = 0x203c; // ' <'
    byte constant RPAREN = 0x3e; // '>'
    uint256 constant FOUR_BIT_MASK = 0xf;

    // ============ Library Functions ============

    function that(
        bool must,
        bytes32 file,
        bytes32 reason
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason)
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        uint256 payloadA
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        RPAREN
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        uint256 payloadA,
        uint256 payloadB
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        COMMA,
                        stringify(payloadB),
                        RPAREN
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        address payloadA
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        RPAREN
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        address payloadA,
        uint256 payloadB
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        COMMA,
                        stringify(payloadB),
                        RPAREN
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        address payloadA,
        uint256 payloadB,
        uint256 payloadC
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        COMMA,
                        stringify(payloadB),
                        COMMA,
                        stringify(payloadC),
                        RPAREN
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        bytes32 payloadA
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        RPAREN
                    )
                )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        bytes32 payloadA,
        uint256 payloadB,
        uint256 payloadC
    )
        internal
        pure
    {
        if (!must) {
            revert(
                string(
                    abi.encodePacked(
                        stringifyTruncated(file),
                        COLON,
                        stringifyTruncated(reason),
                        LPAREN,
                        stringify(payloadA),
                        COMMA,
                        stringify(payloadB),
                        COMMA,
                        stringify(payloadC),
                        RPAREN
                    )
                )
            );
        }
    }

    // ============ Private Functions ============

    function stringifyTruncated(
        bytes32 input
    )
        private
        pure
        returns (bytes memory)
    {
        // put the input bytes into the result
        bytes memory result = abi.encodePacked(input);

        // determine the length of the input by finding the location of the last non-zero byte
        for (uint256 i = 32; i > 0; ) {
            // reverse-for-loops with unsigned integer
            /* solium-disable-next-line security/no-modify-for-iter-var */
            i--;

            // find the last non-zero byte in order to determine the length
            if (result[i] != 0) {
                uint256 length = i + 1;

                /* solium-disable-next-line security/no-inline-assembly */
                assembly {
                    mstore(result, length) // r.length = length;
                }

                return result;
            }
        }

        // all bytes are zero
        return new bytes(0);
    }

    function stringify(
        uint256 input
    )
        private
        pure
        returns (bytes memory)
    {
        if (input == 0) {
            return "0";
        }

        // get the final string length
        uint256 j = input;
        uint256 length;
        while (j != 0) {
            length++;
            j /= 10;
        }

        // allocate the string
        bytes memory bstr = new bytes(length);

        // populate the string starting with the least-significant character
        j = input;
        for (uint256 i = length; i > 0; ) {
            // reverse-for-loops with unsigned integer
            /* solium-disable-next-line security/no-modify-for-iter-var */
            i--;

            // take last decimal digit
            bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));

            // remove the last decimal digit
            j /= 10;
        }

        return bstr;
    }

    function stringify(
        address input
    )
        private
        pure
        returns (bytes memory)
    {
        uint256 z = uint256(input);

        // addresses are "0x" followed by 20 bytes of data which take up 2 characters each
        bytes memory result = new bytes(42);

        // populate the result with "0x"
        result[0] = byte(uint8(ASCII_ZERO));
        result[1] = byte(uint8(ASCII_LOWER_EX));

        // for each byte (starting from the lowest byte), populate the result with two characters
        for (uint256 i = 0; i < 20; i++) {
            // each byte takes two characters
            uint256 shift = i * 2;

            // populate the least-significant character
            result[41 - shift] = char(z & FOUR_BIT_MASK);
            z = z >> 4;

            // populate the most-significant character
            result[40 - shift] = char(z & FOUR_BIT_MASK);
            z = z >> 4;
        }

        return result;
    }

    function stringify(
        bytes32 input
    )
        private
        pure
        returns (bytes memory)
    {
        uint256 z = uint256(input);

        // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
        bytes memory result = new bytes(66);

        // populate the result with "0x"
        result[0] = byte(uint8(ASCII_ZERO));
        result[1] = byte(uint8(ASCII_LOWER_EX));

        // for each byte (starting from the lowest byte), populate the result with two characters
        for (uint256 i = 0; i < 32; i++) {
            // each byte takes two characters
            uint256 shift = i * 2;

            // populate the least-significant character
            result[65 - shift] = char(z & FOUR_BIT_MASK);
            z = z >> 4;

            // populate the most-significant character
            result[64 - shift] = char(z & FOUR_BIT_MASK);
            z = z >> 4;
        }

        return result;
    }

    function char(
        uint256 input
    )
        private
        pure
        returns (byte)
    {
        // return ASCII digit (0-9)
        if (input < 10) {
            return byte(uint8(input + ASCII_ZERO));
        }

        // return ASCII letter (a-f)
        return byte(uint8(input + ASCII_RELATIVE_ZERO));
    }
}

File 14 of 48 : Monetary.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;


/**
 * @title Monetary
 * @author dYdX
 *
 * Library for types involving money
 */
library Monetary {

    /*
     * The price of a base-unit of an asset. Has `36 - token.decimals` decimals
     */
    struct Price {
        uint256 value;
    }

    /*
     * Total value of an some amount of an asset. Equal to (price * amount). Has 36 decimals.
     */
    struct Value {
        uint256 value;
    }
}

File 15 of 48 : Interest.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Decimal } from "./Decimal.sol";
import { DolomiteMarginMath } from "./DolomiteMarginMath.sol";
import { Time } from "./Time.sol";
import { Types } from "./Types.sol";


/**
 * @title Interest
 * @author dYdX
 *
 * Library for managing the interest rate and interest indexes of DolomiteMargin
 */
library Interest {
    using DolomiteMarginMath for uint256;
    using SafeMath for uint256;

    // ============ Constants ============

    bytes32 constant FILE = "Interest";
    uint64 constant BASE = 10**18;

    // ============ Structs ============

    struct Rate {
        uint256 value;
    }

    struct Index {
        uint96 borrow;
        uint96 supply;
        uint32 lastUpdate;
    }

    // ============ Library Functions ============

    /**
     * Get a new market Index based on the old index and market interest rate.
     * Calculate interest for borrowers by using the formula rate * time. Approximates
     * continuously-compounded interest when called frequently, but is much more
     * gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate,
     * then prorated across all suppliers.
     *
     * @param  index         The old index for a market
     * @param  rate          The current interest rate of the market
     * @param  totalPar      The total supply and borrow par values of the market
     * @param  earningsRate  The portion of the interest that is forwarded to the suppliers
     * @return               The updated index for a market
     */
    function calculateNewIndex(
        Index memory index,
        Rate memory rate,
        Types.TotalPar memory totalPar,
        Decimal.D256 memory earningsRate
    )
        internal
        view
        returns (Index memory)
    {
        (
            Types.Wei memory supplyWei,
            Types.Wei memory borrowWei
        ) = totalParToWei(totalPar, index);

        // get interest increase for borrowers
        uint32 currentTime = Time.currentTime();
        uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate));

        // get interest increase for suppliers
        uint256 supplyInterest;
        if (Types.isZero(supplyWei)) {
            supplyInterest = 0;
        } else {
            supplyInterest = Decimal.mul(borrowInterest, earningsRate);
            if (borrowWei.value < supplyWei.value) {
                // scale down the interest by the amount being supplied. Why? Because interest is only being paid on
                // the borrowWei, which means it's split amongst all of the supplyWei. Scaling it down normalizes it
                // for the suppliers to share what's being paid by borrowers
                supplyInterest = DolomiteMarginMath.getPartial(supplyInterest, borrowWei.value, supplyWei.value);
            }
        }
        assert(supplyInterest <= borrowInterest);

        return Index({
            borrow: DolomiteMarginMath.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(),
            supply: DolomiteMarginMath.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(),
            lastUpdate: currentTime
        });
    }

    function newIndex()
        internal
        view
        returns (Index memory)
    {
        return Index({
            borrow: BASE,
            supply: BASE,
            lastUpdate: Time.currentTime()
        });
    }

    /*
     * Convert a principal amount to a token amount given an index.
     */
    function parToWei(
        Types.Par memory input,
        Index memory index
    )
        internal
        pure
        returns (Types.Wei memory)
    {
        uint256 inputValue = uint256(input.value);
        if (input.sign) {
            return Types.Wei({
                sign: true,
                value: inputValue.getPartialRoundHalfUp(index.supply, BASE)
            });
        } else {
            return Types.Wei({
                sign: false,
                value: inputValue.getPartialRoundHalfUp(index.borrow, BASE)
            });
        }
    }

    /*
     * Convert a token amount to a principal amount given an index.
     */
    function weiToPar(
        Types.Wei memory input,
        Index memory index
    )
        internal
        pure
        returns (Types.Par memory)
    {
        if (input.sign) {
            return Types.Par({
                sign: true,
                value: input.value.getPartialRoundHalfUp(BASE, index.supply).to128()
            });
        } else {
            return Types.Par({
                sign: false,
                value: input.value.getPartialRoundHalfUp(BASE, index.borrow).to128()
            });
        }
    }

    /*
     * Convert the total supply and borrow principal amounts of a market to total supply and borrow
     * token amounts.
     */
    function totalParToWei(
        Types.TotalPar memory totalPar,
        Index memory index
    )
        internal
        pure
        returns (Types.Wei memory, Types.Wei memory)
    {
        Types.Par memory supplyPar = Types.Par({
            sign: true,
            value: totalPar.supply
        });
        Types.Par memory borrowPar = Types.Par({
            sign: false,
            value: totalPar.borrow
        });
        Types.Wei memory supplyWei = parToWei(supplyPar, index);
        Types.Wei memory borrowWei = parToWei(borrowPar, index);
        return (supplyWei, borrowWei);
    }
}

File 16 of 48 : Exchange.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Require } from "./Require.sol";
import { Token } from "./Token.sol";
import { Types } from "./Types.sol";
import { IExchangeWrapper } from "../interfaces/IExchangeWrapper.sol";


/**
 * @title Exchange
 * @author dYdX
 *
 * Library for transferring tokens and interacting with ExchangeWrappers by using the Wei struct
 */
library Exchange {
    using Types for Types.Wei;

    // ============ Constants ============

    bytes32 constant FILE = "Exchange";

    // ============ Library Functions ============

    function transferOut(
        address token,
        address to,
        Types.Wei memory deltaWei
    )
        internal
    {
        Require.that(
            !deltaWei.isPositive(),
            FILE,
            "Cannot transferOut positive",
            deltaWei.value
        );

        Token.transfer(
            token,
            to,
            deltaWei.value
        );
    }

    function transferIn(
        address token,
        address from,
        Types.Wei memory deltaWei
    )
        internal
    {
        Require.that(
            !deltaWei.isNegative(),
            FILE,
            "Cannot transferIn negative",
            deltaWei.value
        );

        Token.transferFrom(
            token,
            from,
            address(this),
            deltaWei.value
        );
    }

    function getCost(
        address exchangeWrapper,
        address supplyToken,
        address borrowToken,
        Types.Wei memory desiredAmount,
        bytes memory orderData
    )
        internal
        view
        returns (Types.Wei memory)
    {
        Require.that(
            !desiredAmount.isNegative(),
            FILE,
            "Cannot getCost negative",
            desiredAmount.value
        );

        Types.Wei memory result;
        result.sign = false;
        result.value = IExchangeWrapper(exchangeWrapper).getExchangeCost(
            supplyToken,
            borrowToken,
            desiredAmount.value,
            orderData
        );

        return result;
    }

    function exchange(
        address exchangeWrapper,
        address accountOwner,
        address supplyToken,
        address borrowToken,
        Types.Wei memory requestedFillAmount,
        bytes memory orderData
    )
        internal
        returns (Types.Wei memory)
    {
        Require.that(
            !requestedFillAmount.isPositive(),
            FILE,
            "Cannot exchange positive",
            requestedFillAmount.value
        );

        transferOut(borrowToken, exchangeWrapper, requestedFillAmount);

        Types.Wei memory result;
        result.sign = true;
        result.value = IExchangeWrapper(exchangeWrapper).exchange(
            accountOwner,
            address(this),
            supplyToken,
            borrowToken,
            requestedFillAmount.value,
            orderData
        );

        transferIn(supplyToken, exchangeWrapper, result);

        return result;
    }
}

File 17 of 48 : ExcessivelySafeCall.sol
/*

    Copyright 2022 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;


/**
 * @author https://github.com/nomad-xyz
 */
library ExcessivelySafeCall {

    /// @notice Use when you _really_ really _really_ don't trust the called
    /// contract. This prevents the called contract from causing reversion of
    /// the caller in as many ways as we can.
    /// @dev The main difference between this and a solidity low-level call is
    /// that we limit the number of bytes that the callee can cause to be
    /// copied to caller memory. This prevents stupid things like malicious
    /// contracts returning 10,000,000 bytes causing a local OOG when copying
    /// to memory.
    /// @param _target The address to call
    /// @param _gas The amount of gas to forward to the remote contract
    /// @param _maxCopy The maximum number of bytes of returndata to copy
    /// to memory.
    /// @param _calldata The data to send to the remote contract
    /// @return success and returndata, as `.call()`. Returndata is capped to
    /// `_maxCopy` bytes.
    function excessivelySafeCall(
        address _target,
        uint256 _gas,
        uint16 _maxCopy,
        bytes memory _calldata
    ) internal returns (bool, bytes memory) {
        // set up for assembly call
        uint256 _toCopy;
        bool _success;
        bytes memory _returndata = new bytes(_maxCopy);
        // dispatch message to recipient
        // by assembly calling "handle" function
        // we call via assembly to avoid mem-copying a very large returnData
        // returned by a malicious contract
        /* solium-disable security/no-inline-assembly */
        assembly {
            _success := call(
                _gas, // gas
                _target, // recipient
                0, // ether value
                add(_calldata, 0x20), // inloc
                mload(_calldata), // inlen
                0, // outloc
                0 // outlen
            )
            // limit our copy to 256 bytes
            _toCopy := returndatasize()
            if gt(_toCopy, _maxCopy) {
                _toCopy := _maxCopy
            }
            // Store the length of the copied bytes
            mstore(_returndata, _toCopy)
            // copy the bytes from returndata[0:_toCopy]
            returndatacopy(add(_returndata, 0x20), 0, _toCopy)
        }
        /* solium-enable security/no-inline-assembly */
        return (_success, _returndata);
    }

    /// @notice Use when you _really_ really _really_ don't trust the called
    /// contract. This prevents the called contract from causing reversion of
    /// the caller in as many ways as we can.
    /// @dev The main difference between this and a solidity low-level call is
    /// that we limit the number of bytes that the callee can cause to be
    /// copied to caller memory. This prevents stupid things like malicious
    /// contracts returning 10,000,000 bytes causing a local OOG when copying
    /// to memory.
    /// @param _target The address to call
    /// @param _gas The amount of gas to forward to the remote contract
    /// @param _maxCopy The maximum number of bytes of returndata to copy
    /// to memory.
    /// @param _calldata The data to send to the remote contract
    /// @return success and returndata, as `.call()`. Returndata is capped to
    /// `_maxCopy` bytes.
    function excessivelySafeStaticCall(
        address _target,
        uint256 _gas,
        uint16 _maxCopy,
        bytes memory _calldata
    ) internal view returns (bool, bytes memory) {
        // set up for assembly call
        uint256 _toCopy;
        bool _success;
        bytes memory _returndata = new bytes(_maxCopy);
        // dispatch message to recipient
        // by assembly calling "handle" function
        // we call via assembly to avoid mem-copying a very large returndata
        // returned by a malicious contract
        /* solium-disable security/no-inline-assembly */
        assembly {
            _success := staticcall(
                _gas, // gas
                _target, // recipient
                add(_calldata, 0x20), // inloc
                mload(_calldata), // inlen
                0, // outloc
                0 // outlen
            )
            // limit our copy to 256 bytes
            _toCopy := returndatasize()
            if gt(_toCopy, _maxCopy) {
                _toCopy := _maxCopy
            }
            // Store the length of the copied bytes
            mstore(_returndata, _toCopy)
            // copy the bytes from returndata[0:_toCopy]
            returndatacopy(add(_returndata, 0x20), 0, _toCopy)
        }
        /* solium-enable security/no-inline-assembly */
        return (_success, _returndata);
    }
}

File 18 of 48 : Events.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Account } from "./Account.sol";
import { Actions } from "./Actions.sol";
import { Cache } from "./Cache.sol";
import { Interest } from "./Interest.sol";
import { Monetary } from "./Monetary.sol";
import { Storage } from "./Storage.sol";
import { Types } from "./Types.sol";


/**
 * @title Events
 * @author dYdX
 *
 * Library to parse and emit logs from which the state of all accounts and indexes can be followed
 */
library Events {
    using Types for Types.Wei;
    using Storage for Storage.State;

    // ============ Events ============

    event LogIndexUpdate(
        uint256 indexed market,
        Interest.Index index
    );

    event LogOraclePrice(
        uint256 indexed market,
        Monetary.Price price
    );

    event LogOperation(
        address sender
    );

    event LogDeposit(
        address indexed accountOwner,
        uint256 accountNumber,
        uint256 market,
        BalanceUpdate update,
        address from
    );

    event LogWithdraw(
        address indexed accountOwner,
        uint256 accountNumber,
        uint256 market,
        BalanceUpdate update,
        address to
    );

    event LogTransfer(
        address indexed accountOneOwner,
        uint256 accountOneNumber,
        address indexed accountTwoOwner,
        uint256 accountTwoNumber,
        uint256 market,
        BalanceUpdate updateOne,
        BalanceUpdate updateTwo
    );

    event LogBuy(
        address indexed accountOwner,
        uint256 accountNumber,
        uint256 takerMarket,
        uint256 makerMarket,
        BalanceUpdate takerUpdate,
        BalanceUpdate makerUpdate,
        address exchangeWrapper
    );

    event LogSell(
        address indexed accountOwner,
        uint256 accountNumber,
        uint256 takerMarket,
        uint256 makerMarket,
        BalanceUpdate takerUpdate,
        BalanceUpdate makerUpdate,
        address exchangeWrapper
    );

    event LogTrade(
        address indexed takerAccountOwner,
        uint256 takerAccountNumber,
        address indexed makerAccountOwner,
        uint256 makerAccountNumber,
        uint256 inputMarket,
        uint256 outputMarket,
        BalanceUpdate takerInputUpdate,
        BalanceUpdate takerOutputUpdate,
        BalanceUpdate makerInputUpdate,
        BalanceUpdate makerOutputUpdate,
        address autoTrader
    );

    event LogCall(
        address indexed accountOwner,
        uint256 accountNumber,
        address callee
    );

    event LogLiquidate(
        address indexed solidAccountOwner,
        uint256 solidAccountNumber,
        address indexed liquidAccountOwner,
        uint256 liquidAccountNumber,
        uint256 heldMarket,
        uint256 owedMarket,
        BalanceUpdate solidHeldUpdate,
        BalanceUpdate solidOwedUpdate,
        BalanceUpdate liquidHeldUpdate,
        BalanceUpdate liquidOwedUpdate
    );

    event LogVaporize(
        address indexed solidAccountOwner,
        uint256 solidAccountNumber,
        address indexed vaporAccountOwner,
        uint256 vaporAccountNumber,
        uint256 heldMarket,
        uint256 owedMarket,
        BalanceUpdate solidHeldUpdate,
        BalanceUpdate solidOwedUpdate,
        BalanceUpdate vaporOwedUpdate
    );

    // ============ Structs ============

    struct BalanceUpdate {
        Types.Wei deltaWei;
        Types.Par newPar;
    }

    // ============ Internal Functions ============

    function logIndexUpdate(
        uint256 marketId,
        Interest.Index memory index
    )
        internal
    {
        emit LogIndexUpdate(
            marketId,
            index
        );
    }

    function logOraclePrice(
        Cache.MarketInfo memory marketInfo
    )
        internal
    {
        emit LogOraclePrice(
            marketInfo.marketId,
            marketInfo.price
        );
    }

    function logOperation()
        internal
    {
        emit LogOperation(msg.sender);
    }

    function logDeposit(
        Storage.State storage state,
        Actions.DepositArgs memory args,
        Types.Wei memory deltaWei
    )
        internal
    {
        emit LogDeposit(
            args.account.owner,
            args.account.number,
            args.market,
            getBalanceUpdate(
                state,
                args.account,
                args.market,
                deltaWei
            ),
            args.from
        );
    }

    function logWithdraw(
        Storage.State storage state,
        Actions.WithdrawArgs memory args,
        Types.Wei memory deltaWei
    )
        internal
    {
        emit LogWithdraw(
            args.account.owner,
            args.account.number,
            args.market,
            getBalanceUpdate(
                state,
                args.account,
                args.market,
                deltaWei
            ),
            args.to
        );
    }

    function logTransfer(
        Storage.State storage state,
        Actions.TransferArgs memory args,
        Types.Wei memory deltaWei
    )
        internal
    {
        emit LogTransfer(
            args.accountOne.owner,
            args.accountOne.number,
            args.accountTwo.owner,
            args.accountTwo.number,
            args.market,
            getBalanceUpdate(
                state,
                args.accountOne,
                args.market,
                deltaWei
            ),
            getBalanceUpdate(
                state,
                args.accountTwo,
                args.market,
                deltaWei.negative()
            )
        );
    }

    function logBuy(
        Storage.State storage state,
        Actions.BuyArgs memory args,
        Types.Wei memory takerWei,
        Types.Wei memory makerWei
    )
        internal
    {
        emit LogBuy(
            args.account.owner,
            args.account.number,
            args.takerMarket,
            args.makerMarket,
            getBalanceUpdate(
                state,
                args.account,
                args.takerMarket,
                takerWei
            ),
            getBalanceUpdate(
                state,
                args.account,
                args.makerMarket,
                makerWei
            ),
            args.exchangeWrapper
        );
    }

    function logSell(
        Storage.State storage state,
        Actions.SellArgs memory args,
        Types.Wei memory takerWei,
        Types.Wei memory makerWei
    )
        internal
    {
        emit LogSell(
            args.account.owner,
            args.account.number,
            args.takerMarket,
            args.makerMarket,
            getBalanceUpdate(
                state,
                args.account,
                args.takerMarket,
                takerWei
            ),
            getBalanceUpdate(
                state,
                args.account,
                args.makerMarket,
                makerWei
            ),
            args.exchangeWrapper
        );
    }

    function logTrade(
        Storage.State storage state,
        Actions.TradeArgs memory args,
        Types.Wei memory inputWei,
        Types.Wei memory outputWei
    )
        internal
    {
        BalanceUpdate[4] memory updates = [
            getBalanceUpdate(
                state,
                args.takerAccount,
                args.inputMarket,
                inputWei.negative()
            ),
            getBalanceUpdate(
                state,
                args.takerAccount,
                args.outputMarket,
                outputWei.negative()
            ),
            getBalanceUpdate(
                state,
                args.makerAccount,
                args.inputMarket,
                inputWei
            ),
            getBalanceUpdate(
                state,
                args.makerAccount,
                args.outputMarket,
                outputWei
            )
        ];

        emit LogTrade(
            args.takerAccount.owner,
            args.takerAccount.number,
            args.makerAccount.owner,
            args.makerAccount.number,
            args.inputMarket,
            args.outputMarket,
            updates[0],
            updates[1],
            updates[2],
            updates[3],
            args.autoTrader
        );
    }

    function logCall(
        Actions.CallArgs memory args
    )
        internal
    {
        emit LogCall(
            args.account.owner,
            args.account.number,
            args.callee
        );
    }

    function logLiquidate(
        Storage.State storage state,
        Actions.LiquidateArgs memory args,
        Types.Wei memory heldWei,
        Types.Wei memory owedWei
    )
        internal
    {
        BalanceUpdate memory solidHeldUpdate = getBalanceUpdate(
            state,
            args.solidAccount,
            args.heldMarket,
            heldWei.negative()
        );
        BalanceUpdate memory solidOwedUpdate = getBalanceUpdate(
            state,
            args.solidAccount,
            args.owedMarket,
            owedWei.negative()
        );
        BalanceUpdate memory liquidHeldUpdate = getBalanceUpdate(
            state,
            args.liquidAccount,
            args.heldMarket,
            heldWei
        );
        BalanceUpdate memory liquidOwedUpdate = getBalanceUpdate(
            state,
            args.liquidAccount,
            args.owedMarket,
            owedWei
        );

        emit LogLiquidate(
            args.solidAccount.owner,
            args.solidAccount.number,
            args.liquidAccount.owner,
            args.liquidAccount.number,
            args.heldMarket,
            args.owedMarket,
            solidHeldUpdate,
            solidOwedUpdate,
            liquidHeldUpdate,
            liquidOwedUpdate
        );
    }

    function logVaporize(
        Storage.State storage state,
        Actions.VaporizeArgs memory args,
        Types.Wei memory heldWei,
        Types.Wei memory owedWei,
        Types.Wei memory excessWei
    )
        internal
    {
        BalanceUpdate memory solidHeldUpdate = getBalanceUpdate(
            state,
            args.solidAccount,
            args.heldMarket,
            heldWei.negative()
        );
        BalanceUpdate memory solidOwedUpdate = getBalanceUpdate(
            state,
            args.solidAccount,
            args.owedMarket,
            owedWei.negative()
        );
        BalanceUpdate memory vaporOwedUpdate = getBalanceUpdate(
            state,
            args.vaporAccount,
            args.owedMarket,
            owedWei.add(excessWei)
        );

        emit LogVaporize(
            args.solidAccount.owner,
            args.solidAccount.number,
            args.vaporAccount.owner,
            args.vaporAccount.number,
            args.heldMarket,
            args.owedMarket,
            solidHeldUpdate,
            solidOwedUpdate,
            vaporOwedUpdate
        );
    }

    // ============ Private Functions ============

    function getBalanceUpdate(
        Storage.State storage state,
        Account.Info memory account,
        uint256 market,
        Types.Wei memory deltaWei
    )
        private
        view
        returns (BalanceUpdate memory)
    {
        return BalanceUpdate({
            deltaWei: deltaWei,
            newPar: state.getPar(account, market)
        });
    }
}

File 19 of 48 : EnumerableSet.sol
/*

    Copyright 2021 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;


library EnumerableSet {

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

    /**
    * @dev Add a value to a set. O(1).
     *
     * @return true if the value was added to the set, that is if it was not already present.
     */
    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._valueToIndexMap[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * @return true if the value was removed from the set, that is if it was present.
     */
    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._valueToIndexMap[value];

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

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

            if (lastIndex != toDeleteIndex) {
                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._valueToIndexMap[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored, which is the last index
            set._values.pop();

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

            return true;
        } else {
            return false;
        }
    }

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

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

    /**
     * @dev Returns the value at the corresponding index. O(1).
     */
    function getAtIndex(Set storage set, uint256 index) internal view returns (uint256) {
        return set._values[index];
    }

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

}

File 20 of 48 : DolomiteMarginMath.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Require } from "./Require.sol";


/**
 * @title Math
 * @author dYdX
 *
 * Library for non-standard Math functions
 */
library DolomiteMarginMath {
    using SafeMath for uint256;

    // ============ Constants ============

    bytes32 constant FILE = "Math";

    // ============ Library Functions ============

    /*
     * Return target * (numerator / denominator).
     */
    function getPartial(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
        internal
        pure
        returns (uint256)
    {
        return target.mul(numerator).div(denominator);
    }

    /*
     * Return target * (numerator / denominator), but rounded half-up. Meaning, a result of 101.1 rounds to 102
     * instead of 101.
     */
    function getPartialRoundUp(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
        internal
        pure
        returns (uint256)
    {
        if (target == 0 || numerator == 0) {
            // SafeMath will check for zero denominator
            return SafeMath.div(0, denominator);
        }
        return target.mul(numerator).sub(1).div(denominator).add(1);
    }

    /*
     * Return target * (numerator / denominator), but rounded half-up. Meaning, a result of 101.5 rounds to 102
     * instead of 101.
     */
    function getPartialRoundHalfUp(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
        internal
        pure
        returns (uint256)
    {
        if (target == 0 || numerator == 0) {
            // SafeMath will check for zero denominator
            return SafeMath.div(0, denominator);
        }
        uint result = target.mul(numerator);
        // round the denominator comparator up to ensure a fair comparison is done on the `result`'s modulo.
        // For example, 51 / 103 == 0; 51 % 103 == 51; ((103 - 1) / 2) + 1 == 52; 51 < 52, therefore no round up
        return result.div(denominator).add(result.mod(denominator) >= denominator.sub(1).div(2).add(1) ? 1 : 0);
    }

    function to128(
        uint256 number
    )
        internal
        pure
        returns (uint128)
    {
        uint128 result = uint128(number);
        Require.that(
            result == number,
            FILE,
            "Unsafe cast to uint128",
            number
        );
        return result;
    }

    function to96(
        uint256 number
    )
        internal
        pure
        returns (uint96)
    {
        uint96 result = uint96(number);
        Require.that(
            result == number,
            FILE,
            "Unsafe cast to uint96",
            number
        );
        return result;
    }

    function to32(
        uint256 number
    )
        internal
        pure
        returns (uint32)
    {
        uint32 result = uint32(number);
        Require.that(
            result == number,
            FILE,
            "Unsafe cast to uint32",
            number
        );
        return result;
    }
}

File 21 of 48 : Decimal.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { DolomiteMarginMath } from "./DolomiteMarginMath.sol";


/**
 * @title Decimal
 * @author dYdX
 *
 * Library that defines a fixed-point number with 18 decimal places.
 */
library Decimal {
    using SafeMath for uint256;

    // ============ Constants ============

    uint256 constant BASE = 10**18;

    // ============ Structs ============

    struct D256 {
        uint256 value;
    }

    // ============ Functions ============

    function one()
        internal
        pure
        returns (D256 memory)
    {
        return D256({ value: BASE });
    }

    function onePlus(
        D256 memory d
    )
        internal
        pure
        returns (D256 memory)
    {
        return D256({ value: d.value.add(BASE) });
    }

    function mul(
        uint256 target,
        D256 memory d
    )
        internal
        pure
        returns (uint256)
    {
        return DolomiteMarginMath.getPartial(target, d.value, BASE);
    }

    function div(
        uint256 target,
        D256 memory d
    )
        internal
        pure
        returns (uint256)
    {
        return DolomiteMarginMath.getPartial(target, BASE, d.value);
    }
}

File 22 of 48 : Cache.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Bits } from "./Bits.sol";
import { Interest } from "./Interest.sol";
import { Monetary } from "./Monetary.sol";
import { Require } from "./Require.sol";


/**
 * @title Cache
 * @author dYdX
 *
 * Library for caching information about markets
 */
library Cache {

    // ============ Constants ============

    bytes32 internal constant FILE = "Cache";

    // ============ Structs ============

    struct MarketInfo {
        uint marketId;
        address token;
        bool isClosing;
        uint128 borrowPar;
        uint128 supplyPar;
        Interest.Index index;
        Monetary.Price price;
    }

    struct MarketCache {
        MarketInfo[] markets;
        uint256[] marketBitmaps;
        uint256 marketsLength;
    }

    // ============ Setter Functions ============

    /**
     * Initialize an empty cache for some given number of total markets.
     */
    function create(
        uint256 numMarkets
    )
        internal
        pure
        returns (MarketCache memory)
    {
        return MarketCache({
            markets: new MarketInfo[](0),
            marketBitmaps: Bits.createBitmaps(numMarkets),
            marketsLength: 0
        });
    }

    // ============ Getter Functions ============

    function getNumMarkets(
        MarketCache memory cache
    )
        internal
        pure
        returns (uint256)
    {
        return cache.markets.length;
    }

    function hasMarket(
        MarketCache memory cache,
        uint256 marketId
    )
        internal
        pure
        returns (bool)
    {
        return Bits.hasBit(cache.marketBitmaps, marketId);
    }

    function get(
        MarketCache memory cache,
        uint256 marketId
    )
        internal
        pure
        returns (MarketInfo memory)
    {
        Require.that(
            cache.markets.length > 0,
            FILE,
            "not initialized"
        );
        return _getInternal(
            cache.markets,
            0,
            cache.marketsLength,
            marketId
        );
    }

    function set(
        MarketCache memory cache,
        uint256 marketId
    )
        internal
        pure
    {
        // Devs should not be able to call this function once the `markets` array has been initialized (non-zero length)
        Require.that(
            cache.markets.length == 0,
            FILE,
            "already initialized"
        );

        Bits.setBit(cache.marketBitmaps, marketId);

        cache.marketsLength += 1;
    }

    function getAtIndex(
        MarketCache memory cache,
        uint256 index
    )
        internal
        pure
        returns (MarketInfo memory)
    {
        Require.that(
            index < cache.markets.length,
            FILE,
            "invalid index",
            index,
            cache.markets.length
        );
        return cache.markets[index];
    }

    // ============ Private Functions ============

    function _getInternal(
        MarketInfo[] memory data,
        uint beginInclusive,
        uint endExclusive,
        uint marketId
    ) private pure returns (MarketInfo memory) {
        uint len = endExclusive - beginInclusive;
        // If length equals 0 OR length equals 1 but the item wasn't found, revert
        assert(!(len == 0 || (len == 1 && data[beginInclusive].marketId != marketId)));

        uint mid = beginInclusive + len / 2;
        uint midMarketId = data[mid].marketId;
        if (marketId < midMarketId) {
            return _getInternal(
                data,
                beginInclusive,
                mid,
                marketId
            );
        } else if (marketId > midMarketId) {
            return _getInternal(
                data,
                mid + 1,
                endExclusive,
                marketId
            );
        } else {
            return data[mid];
        }
    }

}

File 23 of 48 : Bits.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

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


/**
 * @title Bits
 * @author Dolomite
 *
 * Library for caching information about markets
 */
library Bits {

    // ============ Constants ============

    uint internal constant ONE = 1;
    uint256 internal constant MAX_UINT_BITS = 256;

    // ============ Functions ============

    function createBitmaps(uint maxLength) internal pure returns (uint[] memory) {
        return new uint[]((maxLength / MAX_UINT_BITS) + ONE);
    }

    function getMarketIdFromBit(
        uint index,
        uint bit
    ) internal pure returns (uint) {
        return (MAX_UINT_BITS * index) + bit;
    }

    function setBit(
        uint[] memory bitmaps,
        uint marketId
    ) internal pure {
        uint bucketIndex = marketId / MAX_UINT_BITS;
        uint indexFromRight = marketId % MAX_UINT_BITS;
        bitmaps[bucketIndex] |= (ONE << indexFromRight);
    }

    function hasBit(
        uint[] memory bitmaps,
        uint marketId
    ) internal pure returns (bool) {
        uint bucketIndex = marketId / MAX_UINT_BITS;
        uint indexFromRight = marketId % MAX_UINT_BITS;
        uint bit = bitmaps[bucketIndex] & (ONE << indexFromRight);
        return bit > 0;
    }

    function unsetBit(
        uint bitmap,
        uint bit
    ) internal pure returns (uint) {
        return bitmap - (ONE << bit);
    }

    // solium-disable security/no-assign-params
    function getLeastSignificantBit(uint256 x) internal pure returns (uint) {
        // gas usage peaks at 350 per call

        uint lsb = 255;

        if (x & uint128(-1) > 0) {
            lsb -= 128;
        } else {
            x >>= 128;
        }

        if (x & uint64(-1) > 0) {
            lsb -= 64;
        } else {
            x >>= 64;
        }

        if (x & uint32(-1) > 0) {
            lsb -= 32;
        } else {
            x >>= 32;
        }

        if (x & uint16(-1) > 0) {
            lsb -= 16;
        } else {
            x >>= 16;
        }

        if (x & uint8(-1) > 0) {
            lsb -= 8;
        } else {
            x >>= 8;
        }

        if (x & 0xf > 0) {
            lsb -= 4;
        } else {
            x >>= 4;
        }

        if (x & 0x3 > 0) {
            lsb -= 2;
        } else {
            x >>= 2;
            // solium-enable security/no-assign-params
        }

        if (x & 0x1 > 0) {
            lsb -= 1;
        }

        return lsb;
    }
}

File 24 of 48 : Actions.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Account } from "./Account.sol";
import { Types } from "./Types.sol";


/**
 * @title Actions
 * @author dYdX
 *
 * Library that defines and parses valid Actions
 */
library Actions {

    // ============ Constants ============

    bytes32 constant FILE = "Actions";

    // ============ Enums ============

    enum ActionType {
        Deposit,   // supply tokens
        Withdraw,  // borrow tokens
        Transfer,  // transfer balance between accounts
        Buy,       // buy an amount of some token (externally)
        Sell,      // sell an amount of some token (externally)
        Trade,     // trade tokens against another account
        Liquidate, // liquidate an undercollateralized or expiring account
        Vaporize,  // use excess tokens to zero-out a completely negative account
        Call       // send arbitrary data to an address
    }

    enum AccountLayout {
        OnePrimary,
        TwoPrimary,
        PrimaryAndSecondary
    }

    enum MarketLayout {
        ZeroMarkets,
        OneMarket,
        TwoMarkets
    }

    // ============ Structs ============

    /*
     * Arguments that are passed to DolomiteMargin in an ordered list as part of a single operation.
     * Each ActionArgs has an actionType which specifies which action struct that this data will be
     * parsed into before being processed.
     */
    struct ActionArgs {
        ActionType actionType;
        uint256 accountId;
        Types.AssetAmount amount;
        uint256 primaryMarketId;
        uint256 secondaryMarketId;
        address otherAddress;
        uint256 otherAccountId;
        bytes data;
    }

    // ============ Action Types ============

    /*
     * Moves tokens from an address to DolomiteMargin. Can either repay a borrow or provide additional supply.
     */
    struct DepositArgs {
        Types.AssetAmount amount;
        Account.Info account;
        uint256 market;
        address from;
    }

    /*
     * Moves tokens from DolomiteMargin to another address. Can either borrow tokens or reduce the amount
     * previously supplied.
     */
    struct WithdrawArgs {
        Types.AssetAmount amount;
        Account.Info account;
        uint256 market;
        address to;
    }

    /*
     * Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
     * The amount field applies to accountOne.
     * This action does not require any token movement since the trade is done internally to DolomiteMargin.
     */
    struct TransferArgs {
        Types.AssetAmount amount;
        Account.Info accountOne;
        Account.Info accountTwo;
        uint256 market;
    }

    /*
     * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
     * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
     * applies to the makerMarket.
     */
    struct BuyArgs {
        Types.AssetAmount amount;
        Account.Info account;
        uint256 makerMarket;
        uint256 takerMarket;
        address exchangeWrapper;
        bytes orderData;
    }

    /*
     * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
     * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
     * to the takerMarket.
     */
    struct SellArgs {
        Types.AssetAmount amount;
        Account.Info account;
        uint256 takerMarket;
        uint256 makerMarket;
        address exchangeWrapper;
        bytes orderData;
    }

    /*
     * Trades balances between two accounts using any external contract that implements the
     * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
     * which it is trading on-behalf-of). The amount field applies to the makerAccount and the
     * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
     * quote a change for the makerAccount in the outputMarket (or will disallow the trade).
     * This action does not require any token movement since the trade is done internally to DolomiteMargin.
     */
    struct TradeArgs {
        Types.AssetAmount amount;
        Account.Info takerAccount;
        Account.Info makerAccount;
        uint256 inputMarket;
        uint256 outputMarket;
        address autoTrader;
        bytes tradeData;
    }

    /*
     * Each account must maintain a certain margin-ratio (specified globally). If the account falls
     * below this margin-ratio, it can be liquidated by any other account. This allows anyone else
     * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
     * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
     * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
     * account also sets a flag on the account that the account is being liquidated. This allows
     * anyone to continue liquidating the account until there are no more borrows being taken by the
     * liquidating account. Liquidators do not have to liquidate the entire account all at once but
     * can liquidate as much as they choose. The liquidating flag allows liquidators to continue
     * liquidating the account even if it becomes collateralized through partial liquidation or
     * price movement.
     */
    struct LiquidateArgs {
        Types.AssetAmount amount;
        Account.Info solidAccount;
        Account.Info liquidAccount;
        uint256 owedMarket;
        uint256 heldMarket;
    }

    /*
     * Similar to liquidate, but vaporAccounts are accounts that have only negative balances remaining. The arbitrageur
     * pays back the negative asset (owedMarket) of the vaporAccount in exchange for a collateral asset (heldMarket) at
     * a favorable spread. However, since the liquidAccount has no collateral assets, the collateral must come from
     * DolomiteMargin's excess tokens.
     */
    struct VaporizeArgs {
        Types.AssetAmount amount;
        Account.Info solidAccount;
        Account.Info vaporAccount;
        uint256 owedMarket;
        uint256 heldMarket;
    }

    /*
     * Passes arbitrary bytes of data to an external contract that implements the Callee interface.
     * Does not change any asset amounts. This function may be useful for setting certain variables
     * on layer-two contracts for certain accounts without having to make a separate Ethereum
     * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
     * from an operator of the particular account.
     */
    struct CallArgs {
        Account.Info account;
        address callee;
        bytes data;
    }

    // ============ Helper Functions ============

    function getMarketLayout(
        ActionType actionType
    )
        internal
        pure
        returns (MarketLayout)
    {
        if (
            actionType == Actions.ActionType.Deposit
            || actionType == Actions.ActionType.Withdraw
            || actionType == Actions.ActionType.Transfer
        ) {
            return MarketLayout.OneMarket;
        }
        else if (actionType == Actions.ActionType.Call) {
            return MarketLayout.ZeroMarkets;
        }
        return MarketLayout.TwoMarkets;
    }

    function getAccountLayout(
        ActionType actionType
    )
        internal
        pure
        returns (AccountLayout)
    {
        if (
            actionType == Actions.ActionType.Transfer
            || actionType == Actions.ActionType.Trade
        ) {
            return AccountLayout.TwoPrimary;
        } else if (
            actionType == Actions.ActionType.Liquidate
            || actionType == Actions.ActionType.Vaporize
        ) {
            return AccountLayout.PrimaryAndSecondary;
        }
        return AccountLayout.OnePrimary;
    }

    // ============ Parsing Functions ============

    function parseDepositArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (DepositArgs memory)
    {
        return DepositArgs({
            amount: args.amount,
            account: accounts[args.accountId],
            market: args.primaryMarketId,
            from: args.otherAddress
        });
    }

    function parseWithdrawArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (WithdrawArgs memory)
    {
        return WithdrawArgs({
            amount: args.amount,
            account: accounts[args.accountId],
            market: args.primaryMarketId,
            to: args.otherAddress
        });
    }

    function parseTransferArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (TransferArgs memory)
    {
        return TransferArgs({
            amount: args.amount,
            accountOne: accounts[args.accountId],
            accountTwo: accounts[args.otherAccountId],
            market: args.primaryMarketId
        });
    }

    function parseBuyArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (BuyArgs memory)
    {
        return BuyArgs({
            amount: args.amount,
            account: accounts[args.accountId],
            makerMarket: args.primaryMarketId,
            takerMarket: args.secondaryMarketId,
            exchangeWrapper: args.otherAddress,
            orderData: args.data
        });
    }

    function parseSellArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (SellArgs memory)
    {
        return SellArgs({
            amount: args.amount,
            account: accounts[args.accountId],
            takerMarket: args.primaryMarketId,
            makerMarket: args.secondaryMarketId,
            exchangeWrapper: args.otherAddress,
            orderData: args.data
        });
    }

    function parseTradeArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (TradeArgs memory)
    {
        return TradeArgs({
            amount: args.amount,
            takerAccount: accounts[args.accountId],
            makerAccount: accounts[args.otherAccountId],
            inputMarket: args.primaryMarketId,
            outputMarket: args.secondaryMarketId,
            autoTrader: args.otherAddress,
            tradeData: args.data
        });
    }

    function parseLiquidateArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (LiquidateArgs memory)
    {
        return LiquidateArgs({
            amount: args.amount,
            solidAccount: accounts[args.accountId],
            liquidAccount: accounts[args.otherAccountId],
            owedMarket: args.primaryMarketId,
            heldMarket: args.secondaryMarketId
        });
    }

    function parseVaporizeArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (VaporizeArgs memory)
    {
        return VaporizeArgs({
            amount: args.amount,
            solidAccount: accounts[args.accountId],
            vaporAccount: accounts[args.otherAccountId],
            owedMarket: args.primaryMarketId,
            heldMarket: args.secondaryMarketId
        });
    }

    function parseCallArgs(
        Account.Info[] memory accounts,
        ActionArgs memory args
    )
        internal
        pure
        returns (CallArgs memory)
    {
        return CallArgs({
            account: accounts[args.accountId],
            callee: args.otherAddress,
            data: args.data
        });
    }
}

File 25 of 48 : Address.sol
pragma solidity ^0.5.5;

/**
 * @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) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

    /**
     * @dev Converts an `address` into `address payable`. Note that this is
     * simply a type cast: the actual underlying value is not changed.
     *
     * _Available since v2.4.0._
     */
    function toPayable(address account) internal pure returns (address payable) {
        return address(uint160(account));
    }

    /**
     * @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].
     *
     * _Available since v2.4.0._
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

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

File 26 of 48 : IRecyclable.sol
/*

    Copyright 2021 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

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

import { Account } from "../lib/Account.sol";
import { Types } from "../lib/Types.sol";


/**
 * @title IRecyclable
 * @author Dolomite
 *
 * Interface that recyclable tokens/markets must implement
 */
contract IRecyclable {

    // ============ Public State Variables ============

    /**
     * @notice The max timestamp at which tokens represented by this contract should be expired, allowing liquidators
     *          to close margin positions involving this token, so this contract can be recycled.
     */
    uint public MAX_EXPIRATION_TIMESTAMP;

    // ============ Public Functions ============

    /**
     * @return  The token around which this recycle contract wraps.
     */
    function TOKEN() external view returns (IERC20);

    /**
     * A callback for the recyclable market that allows it to perform any cleanup logic, preventing its usage with
     * DolomiteMargin once this transaction completes. #isRecycled  should return `true` after this function is called.
     */
    function recycle() external;

    /**
     * Called when the market is initialized in DolomiteMargin
     */
    function initialize() external;

    /**
     * @return The account number used to index into the account for this user
     */
    function getAccountNumber(Account.Info calldata account) external pure returns (uint256);

    function getAccountPar(Account.Info calldata account) external view returns (Types.Par memory);

    /**
     * @return  True if this contract is recycled, disallowing further deposits/interactions with DolomiteMargin and freeing this
     *          token's `MARKET_ID`.
     */
    function isRecycled() external view returns (bool);

    /**
     * @dev Deposits the underlying token into this smart contract and adds to the user's balance with DolomiteMargin. The user
     *      must set an allowance for `TOKEN`, using this contract as the `spender`.
     */
    function depositIntoDolomiteMargin(uint accountNumber, uint amount) external;

    /**
     * @dev Withdraws a specific amount of a user's balance from the smart contract to `msg.sender`
     */
    function withdrawFromDolomiteMargin(uint accountNumber, uint amount) external;

    /**
     * @dev Withdraws the user's remaining balance from the smart contract, after this contract has been recycled.
     */
    function withdrawAfterRecycle(uint accountNumber) external;

    /**
     * @dev Performs a trade between a user and the specified `IExchangeWrapper` to open or a close a margin position
     *      involving this market. Specifying `isOpen` will change the taker amount from borrowAmount (if true) to
     *      `supplyAmount` (if false). Keep in mind, this taker amount is passed through as `requestedFillAmount` to
     *      `IExchangeWrapper`.
     */
    function trade(
        uint accountNumber,
        Types.AssetAmount calldata supplyAmount, // equivalent to amounts[amounts.length - 1]
        address borrowToken,
        Types.AssetAmount calldata borrowAmount,
        address exchangeWrapper,
        uint expirationTimestamp,
        bool isOpen,
        bytes calldata tradeData
    )
        external;

    /**
     * @return  true if this recyclable contract is expired, or false if it's not yet.
     */
    function isExpired() public view returns (bool) {
        return MAX_EXPIRATION_TIMESTAMP < block.timestamp;
    }
}

File 27 of 48 : IPriceOracle.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Monetary } from "../lib/Monetary.sol";


/**
 * @title IPriceOracle
 * @author dYdX
 *
 * Interface that Price Oracles for DolomiteMargin must implement in order to report prices.
 */
contract IPriceOracle {

    // ============ Constants ============

    uint256 public constant ONE_DOLLAR = 10 ** 36;

    // ============ Public Functions ============

    /**
     * Get the price of a token
     *
     * @param  token  The ERC20 token address of the market
     * @return        The USD price of a base unit of the token, then multiplied by 10^36.
     *                So a USD-stable coin with 18 decimal places would return 10^18.
     *                This is the price of the base unit rather than the price of a "human-readable"
     *                token amount. Every ERC20 may have a different number of decimals.
     */
    function getPrice(
        address token
    )
        public
        view
        returns (Monetary.Price memory);
}

File 28 of 48 : ILiquidationCallback.sol
/*

    Copyright 2021 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;

import "../lib/Types.sol";


interface ILiquidationCallback {

    /**
     * A callback function to notify the smart contract that it is being liquidated. This function is called before the
     * new balances are set in state, so calling `getAccountPar/Wei` will return this liquidated account's balance
     * before `heldDeltaWei` or `owedDeltaWei` are applied.
     *
     * @param accountNumber The account number being liquidated
     * @param heldMarketId  The market that was positive for this account, whose collateral is being seized
     * @param heldDeltaWei  The amount of seized collateral; always negative or 0
     * @param owedMarketId  The borrowed balance that is being forcefully repaid
     * @param owedDeltaWei  The amount of borrowed assets to be repaid. Always 0 or positive, since the user's balance
     *                      is going from negative to 0.
     */
    function onLiquidate(
        uint accountNumber,
        uint heldMarketId,
        Types.Wei calldata heldDeltaWei,
        uint owedMarketId,
        Types.Wei calldata owedDeltaWei
    ) external;
}

File 29 of 48 : IInterestSetter.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Interest } from "../lib/Interest.sol";


/**
 * @title IInterestSetter
 * @author dYdX
 *
 * Interface that Interest Setters for DolomiteMargin must implement in order to report interest rates.
 */
interface IInterestSetter {

    // ============ Public Functions ============

    /**
     * Get the interest rate of a token given some borrowed and supplied amounts
     *
     * @param  token        The address of the ERC20 token for the market
     * @param  borrowWei    The total borrowed token amount for the market
     * @param  supplyWei    The total supplied token amount for the market
     * @return              The interest rate per second
     */
    function getInterestRate(
        address token,
        uint256 borrowWei,
        uint256 supplyWei
    )
        external
        view
        returns (Interest.Rate memory);
}

File 30 of 48 : IExchangeWrapper.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;


/**
 * @title IExchangeWrapper
 * @author dYdX
 *
 * Interface that Exchange Wrappers for DolomiteMargin must implement in order to trade ERC20 tokens.
 */
interface IExchangeWrapper {

    // ============ Public Functions ============

    /**
     * Exchange some amount of takerToken for makerToken.
     *
     * @param  tradeOriginator      Address of the initiator of the trade (however, this value
     *                              cannot always be trusted as it is set at the discretion of the
     *                              msg.sender)
     * @param  receiver             Address to set allowance on once the trade has completed
     * @param  makerToken           Address of makerToken, the token to receive (target asset; IE path[path.length - 1])
     * @param  takerToken           Address of takerToken, the token to pay (originator asset; IE path[0])
     * @param  requestedFillAmount  Amount of takerToken being paid
     * @param  orderData            Arbitrary bytes data for any information to pass to the exchange
     * @return                      The amount of makerToken received
     */
    function exchange(
        address tradeOriginator,
        address receiver,
        address makerToken,
        address takerToken,
        uint256 requestedFillAmount,
        bytes calldata orderData
    )
        external
        returns (uint256);

    /**
     * Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
     * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
     * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
     * than desiredMakerToken
     *
     * @param  makerToken         Address of makerToken, the token to receive
     * @param  takerToken         Address of takerToken, the token to pay
     * @param  desiredMakerToken  Amount of makerToken requested
     * @param  orderData          Arbitrary bytes data for any information to pass to the exchange
     * @return                    Amount of takerToken the needed to complete the exchange
     */
    function getExchangeCost(
        address makerToken,
        address takerToken,
        uint256 desiredMakerToken,
        bytes calldata orderData
    )
        external
        view
        returns (uint256);
}

File 31 of 48 : IERC20Detailed.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

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


/**
 * @title IERC20
 * @author dYdX
 *
 * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
 * that we don't automatically revert when calling non-compliant tokens that have no return value for
 * transfer(), transferFrom(), or approve().
 */
contract IERC20Detailed is IERC20 {

    function name() external view returns (string memory);

    function symbol() external view returns (string memory);

    function decimals() external view returns (uint8);
}

File 32 of 48 : IDolomiteMargin.sol
/*

    Copyright 2021 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;

import { IInterestSetter } from "../interfaces/IInterestSetter.sol";
import { IPriceOracle } from "../interfaces/IPriceOracle.sol";

import { Account } from "../lib/Account.sol";
import { Actions } from "../lib/Actions.sol";
import { Decimal } from "../lib/Decimal.sol";
import { Interest } from "../lib/Interest.sol";
import { Monetary } from "../lib/Monetary.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";

interface IDolomiteMargin {

    // ============ Getters for Markets ============

    /**
     * Get the ERC20 token address for a market.
     *
     * @param  token    The token to query
     * @return          The token's marketId if the token is valid
     */
    function getMarketIdByTokenAddress(
        address token
    ) external view returns (uint256);

    /**
     * Get the ERC20 token address for a market.
     *
     * @param  marketId  The market to query
     * @return           The token address
     */
    function getMarketTokenAddress(
        uint256 marketId
    ) external view returns (address);

    /**
     * Return true if a particular market is in closing mode. Additional borrows cannot be taken
     * from a market that is closing.
     *
     * @param  marketId  The market to query
     * @return           True if the market is closing
     */
    function getMarketIsClosing(
        uint256 marketId
    )
    external
    view
    returns (bool);

    /**
     * Get the price of the token for a market.
     *
     * @param  marketId  The market to query
     * @return           The price of each atomic unit of the token
     */
    function getMarketPrice(
        uint256 marketId
    ) external view returns (Monetary.Price memory);

    /**
     * Get the total number of markets.
     *
     * @return  The number of markets
     */
    function getNumMarkets() external view returns (uint256);

    /**
     * Get the total principal amounts (borrowed and supplied) for a market.
     *
     * @param  marketId  The market to query
     * @return           The total principal amounts
     */
    function getMarketTotalPar(
        uint256 marketId
    ) external view returns (Types.TotalPar memory);

    /**
     * Get the most recently cached interest index for a market.
     *
     * @param  marketId  The market to query
     * @return           The most recent index
     */
    function getMarketCachedIndex(
        uint256 marketId
    ) external view returns (Interest.Index memory);

    /**
     * Get the interest index for a market if it were to be updated right now.
     *
     * @param  marketId  The market to query
     * @return           The estimated current index
     */
    function getMarketCurrentIndex(
        uint256 marketId
    ) external view returns (Interest.Index memory);

    /**
     * Get the price oracle address for a market.
     *
     * @param  marketId  The market to query
     * @return           The price oracle address
     */
    function getMarketPriceOracle(
        uint256 marketId
    ) external view returns (IPriceOracle);

    /**
     * Get the interest-setter address for a market.
     *
     * @param  marketId  The market to query
     * @return           The interest-setter address
     */
    function getMarketInterestSetter(
        uint256 marketId
    ) external view returns (IInterestSetter);

    /**
     * Get the margin premium for a market. A margin premium makes it so that any positions that
     * include the market require a higher collateralization to avoid being liquidated.
     *
     * @param  marketId  The market to query
     * @return           The market's margin premium
     */
    function getMarketMarginPremium(
        uint256 marketId
    ) external view returns (Decimal.D256 memory);

    /**
     * Get the spread premium for a market. A spread premium makes it so that any liquidations
     * that include the market have a higher spread than the global default.
     *
     * @param  marketId  The market to query
     * @return           The market's spread premium
     */
    function getMarketSpreadPremium(
        uint256 marketId
    ) external view returns (Decimal.D256 memory);

    /**
     * Return true if this market can be removed and its ID can be recycled and reused
     *
     * @param  marketId  The market to query
     * @return           True if the market is recyclable
     */
    function getMarketIsRecyclable(
        uint256 marketId
    ) external view returns (bool);

    /**
     * Gets the recyclable markets, up to `n` length. If `n` is greater than the length of the list, 0's are returned
     * for the empty slots.
     *
     * @param  n    The number of markets to get, bounded by the linked list being smaller than `n`
     * @return      The list of recyclable markets, in the same order held by the linked list
     */
    function getRecyclableMarkets(
        uint256 n
    ) external view returns (uint[] memory);

    /**
     * Get the current borrower interest rate for a market.
     *
     * @param  marketId  The market to query
     * @return           The current interest rate
     */
    function getMarketInterestRate(
        uint256 marketId
    ) external view returns (Interest.Rate memory);

    /**
     * Get basic information about a particular market.
     *
     * @param  marketId  The market to query
     * @return           A Storage.Market struct with the current state of the market
     */
    function getMarket(
        uint256 marketId
    ) external view returns (Storage.Market memory);

    /**
     * Get comprehensive information about a particular market.
     *
     * @param  marketId  The market to query
     * @return           A tuple containing the values:
     *                    - A Storage.Market struct with the current state of the market
     *                    - The current estimated interest index
     *                    - The current token price
     *                    - The current market interest rate
     */
    function getMarketWithInfo(
        uint256 marketId
    )
    external
    view
    returns (
        Storage.Market memory,
        Interest.Index memory,
        Monetary.Price memory,
        Interest.Rate memory
    );

    /**
     * Get the number of excess tokens for a market. The number of excess tokens is calculated by taking the current
     * number of tokens held in DolomiteMargin, adding the number of tokens owed to DolomiteMargin by borrowers, and
     * subtracting the number of tokens owed to suppliers by DolomiteMargin.
     *
     * @param  marketId  The market to query
     * @return           The number of excess tokens
     */
    function getNumExcessTokens(
        uint256 marketId
    ) external view returns (Types.Wei memory);

    // ============ Getters for Accounts ============

    /**
     * Get the principal value for a particular account and market.
     *
     * @param  account   The account to query
     * @param  marketId  The market to query
     * @return           The principal value
     */
    function getAccountPar(
        Account.Info calldata account,
        uint256 marketId
    ) external view returns (Types.Par memory);

    /**
     * Get the principal value for a particular account and market, with no check the market is valid. Meaning, markets
     * that don't exist return 0.
     *
     * @param  account   The account to query
     * @param  marketId  The market to query
     * @return           The principal value
     */
    function getAccountParNoMarketCheck(
        Account.Info calldata account,
        uint256 marketId
    ) external view returns (Types.Par memory);

    /**
     * Get the token balance for a particular account and market.
     *
     * @param  account   The account to query
     * @param  marketId  The market to query
     * @return           The token amount
     */
    function getAccountWei(
        Account.Info calldata account,
        uint256 marketId
    ) external view returns (Types.Wei memory);

    /**
     * Get the status of an account (Normal, Liquidating, or Vaporizing).
     *
     * @param  account  The account to query
     * @return          The account's status
     */
    function getAccountStatus(
        Account.Info calldata account
    ) external view returns (Account.Status);

    /**
     * Get a list of markets that have a non-zero balance for an account
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountMarketsWithBalances(
        Account.Info calldata account
    ) external view returns (uint256[] memory);

    /**
     * Get the number of markets that have a non-zero balance for an account
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountNumberOfMarketsWithBalances(
        Account.Info calldata account
    ) external view returns (uint256);

    /**
     * Get the marketId for an account's market with a non-zero balance at the given index
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountMarketWithBalanceAtIndex(
        Account.Info calldata account,
        uint256 index
    ) external view returns (uint256);

    /**
     * Get the number of markets with which an account has a negative balance.
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountNumberOfMarketsWithDebt(
        Account.Info calldata account
    ) external view returns (uint256);

    /**
     * Get the total supplied and total borrowed value of an account.
     *
     * @param  account  The account to query
     * @return          The following values:
     *                   - The supplied value of the account
     *                   - The borrowed value of the account
     */
    function getAccountValues(
        Account.Info calldata account
    ) external view returns (Monetary.Value memory, Monetary.Value memory);

    /**
     * Get the total supplied and total borrowed values of an account adjusted by the marginPremium
     * of each market. Supplied values are divided by (1 + marginPremium) for each market and
     * borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these
     * adjusted values gives the margin-ratio of the account which will be compared to the global
     * margin-ratio when determining if the account can be liquidated.
     *
     * @param  account  The account to query
     * @return          The following values:
     *                   - The supplied value of the account (adjusted for marginPremium)
     *                   - The borrowed value of the account (adjusted for marginPremium)
     */
    function getAdjustedAccountValues(
        Account.Info calldata account
    ) external view returns (Monetary.Value memory, Monetary.Value memory);

    /**
     * Get an account's summary for each market.
     *
     * @param  account  The account to query
     * @return          The following values:
     *                   - The market IDs for each market
     *                   - The ERC20 token address for each market
     *                   - The account's principal value for each market
     *                   - The account's (supplied or borrowed) number of tokens for each market
     */
    function getAccountBalances(
        Account.Info calldata account
    ) external view returns (uint[] memory, address[] memory, Types.Par[] memory, Types.Wei[] memory);

    // ============ Getters for Account Permissions ============

    /**
     * Return true if a particular address is approved as an operator for an owner's accounts.
     * Approved operators can act on the accounts of the owner as if it were the operator's own.
     *
     * @param  owner     The owner of the accounts
     * @param  operator  The possible operator
     * @return           True if operator is approved for owner's accounts
     */
    function getIsLocalOperator(
        address owner,
        address operator
    ) external view returns (bool);

    /**
     * Return true if a particular address is approved as a global operator. Such an address can
     * act on any account as if it were the operator's own.
     *
     * @param  operator  The address to query
     * @return           True if operator is a global operator
     */
    function getIsGlobalOperator(
        address operator
    ) external view returns (bool);

    /**
     * Checks if the autoTrader can only be called invoked by a global operator
     *
     * @param autoTrader    The trader that should be checked for special call privileges.
     */
    function getIsAutoTraderSpecial(address autoTrader) external view returns (bool);

    // ============ Getters for Risk Params ============

    /**
     * Get the global minimum margin-ratio that every position must maintain to prevent being
     * liquidated.
     *
     * @return  The global margin-ratio
     */
    function getMarginRatio() external view returns (Decimal.D256 memory);

    /**
     * Get the global liquidation spread. This is the spread between oracle prices that incentivizes
     * the liquidation of risky positions.
     *
     * @return  The global liquidation spread
     */
    function getLiquidationSpread() external view returns (Decimal.D256 memory);

    /**
     * Get the adjusted liquidation spread for some market pair. This is equal to the global
     * liquidation spread multiplied by (1 + spreadPremium) for each of the two markets.
     *
     * @param  heldMarketId  The market for which the account has collateral
     * @param  owedMarketId  The market for which the account has borrowed tokens
     * @return               The adjusted liquidation spread
     */
    function getLiquidationSpreadForPair(
        uint256 heldMarketId,
        uint256 owedMarketId
    ) external view returns (Decimal.D256 memory);

    /**
     * Get the global earnings-rate variable that determines what percentage of the interest paid
     * by borrowers gets passed-on to suppliers.
     *
     * @return  The global earnings rate
     */
    function getEarningsRate() external view returns (Decimal.D256 memory);

    /**
     * Get the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
     *
     * @return  The global minimum borrow value
     */
    function getMinBorrowedValue() external view returns (Monetary.Value memory);

    /**
     * Get all risk parameters in a single struct.
     *
     * @return  All global risk parameters
     */
    function getRiskParams() external view returns (Storage.RiskParams memory);

    /**
     * Get all risk parameter limits in a single struct. These are the maximum limits at which the
     * risk parameters can be set by the admin of DolomiteMargin.
     *
     * @return  All global risk parameter limits
     */
    function getRiskLimits() external view returns (Storage.RiskLimits memory);

    // ============ Write Functions ============

    /**
     * The main entry-point to DolomiteMargin that allows users and contracts to manage accounts.
     * Take one or more actions on one or more accounts. The msg.sender must be the owner or
     * operator of all accounts except for those being liquidated, vaporized, or traded with.
     * One call to operate() is considered a singular "operation". Account collateralization is
     * ensured only after the completion of the entire operation.
     *
     * @param  accounts  A list of all accounts that will be used in this operation. Cannot contain
     *                   duplicates. In each action, the relevant account will be referred-to by its
     *                   index in the list.
     * @param  actions   An ordered list of all actions that will be taken in this operation. The
     *                   actions will be processed in order.
     */
    function operate(
        Account.Info[] calldata accounts,
        Actions.ActionArgs[] calldata actions
    ) external;

    /**
     * Approves/disapproves any number of operators. An operator is an external address that has the
     * same permissions to manipulate an account as the owner of the account. Operators are simply
     * addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts.
     *
     * Operators are also able to act as AutoTrader contracts on behalf of the account owner if the
     * operator is a smart contract and implements the IAutoTrader interface.
     *
     * @param  args  A list of OperatorArgs which have an address and a boolean. The boolean value
     *               denotes whether to approve (true) or revoke approval (false) for that address.
     */
    function setOperators(
        Types.OperatorArg[] calldata args
    ) external;

}

File 33 of 48 : ICallee.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Account } from "../lib/Account.sol";


/**
 * @title ICallee
 * @author dYdX
 *
 * Interface that Callees for DolomiteMargin must implement in order to ingest data.
 */
contract ICallee {

    // ============ Public Functions ============

    /**
     * Allows users to send this contract arbitrary data.
     *
     * @param  sender       The msg.sender to DolomiteMargin
     * @param  accountInfo  The account from which the data is being sent
     * @param  data         Arbitrary data given by the sender
     */
    function callFunction(
        address sender,
        Account.Info memory accountInfo,
        bytes memory data
    )
        public;
}

File 34 of 48 : IAutoTrader.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Account } from "../lib/Account.sol";
import { Types } from "../lib/Types.sol";


/**
 * @title IAutoTrader
 * @author dYdX
 *
 * Interface that Auto-Traders for DolomiteMargin must implement in order to approve trades.
 */
contract IAutoTrader {

    // ============ Public Functions ============

    /**
     * Allows traders to make trades approved by this smart contract. The active trader's account is
     * the takerAccount and the passive account (for which this contract approves trades
     * on-behalf-of) is the makerAccount.
     *
     * @param  inputMarketId   The market for which the trader specified the original amount
     * @param  outputMarketId  The market for which the trader wants the resulting amount specified
     * @param  makerAccount    The account for which this contract is making trades
     * @param  takerAccount    The account requesting the trade
     * @param  oldInputPar     The old principal amount for the makerAccount for the inputMarketId
     * @param  newInputPar     The new principal amount for the makerAccount for the inputMarketId
     * @param  inputWei        The change in token amount for the makerAccount for the inputMarketId
     * @param  data            Arbitrary data passed in by the trader
     * @return                 The AssetAmount for the makerAccount for the outputMarketId
     */
    function getTradeCost(
        uint256 inputMarketId,
        uint256 outputMarketId,
        Account.Info memory makerAccount,
        Account.Info memory takerAccount,
        Types.Par memory oldInputPar,
        Types.Par memory newInputPar,
        Types.Wei memory inputWei,
        bytes memory data
    )
        public
        returns (Types.AssetAmount memory);
}

File 35 of 48 : WithdrawalImpl.sol
/*

    Copyright 2021 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Actions } from "../lib/Actions.sol";
import { Events } from "../lib/Events.sol";
import { Exchange } from "../lib/Exchange.sol";
import { Interest } from "../lib/Interest.sol";
import { Require } from "../lib/Require.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";


library WithdrawalImpl {
    using Storage for Storage.State;

    // ============ Constants ============

    bytes32 constant FILE = "WithdrawalImpl";

    // ============ Account Actions ============

    function withdraw(
        Storage.State storage state,
        Actions.WithdrawArgs memory args,
        Interest.Index memory index
    )
    public
    {
        state.requireIsOperator(args.account, msg.sender);

        (
            Types.Par memory newPar,
            Types.Wei memory deltaWei
        ) = state.getNewParAndDeltaWei(
            args.account,
            args.market,
            index,
            args.amount
        );

        state.setPar(
            args.account,
            args.market,
            newPar
        );

        // requires a negative deltaWei
        Exchange.transferOut(
            state.getToken(args.market),
            args.to,
            deltaWei
        );

        Events.logWithdraw(
            state,
            args,
            deltaWei
        );
    }
}

File 36 of 48 : TransferImpl.sol
/*

    Copyright 2021 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Actions } from "../lib/Actions.sol";
import { Events } from "../lib/Events.sol";
import { Interest } from "../lib/Interest.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";


library TransferImpl {
    using Storage for Storage.State;
    using Types for Types.Wei;

    // ============ Constants ============

    bytes32 constant FILE = "TransferImpl";

    // ============ Account Actions ============

    function transfer(
        Storage.State storage state,
        Actions.TransferArgs memory args,
        Interest.Index memory index
    )
    public
    {
        state.requireIsOperator(args.accountOne, msg.sender);
        state.requireIsOperator(args.accountTwo, msg.sender);

        (
            Types.Par memory newPar,
            Types.Wei memory deltaWei
        ) = state.getNewParAndDeltaWei(
            args.accountOne,
            args.market,
            index,
            args.amount
        );

        state.setPar(
            args.accountOne,
            args.market,
            newPar
        );

        state.setParFromDeltaWei(
            args.accountTwo,
            args.market,
            index,
            deltaWei.negative()
        );

        Events.logTransfer(
            state,
            args,
            deltaWei
        );
    }
}

File 37 of 48 : TradeImpl.sol
/*

    Copyright 2021 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { IAutoTrader } from "../interfaces/IAutoTrader.sol";

import { Actions } from "../lib/Actions.sol";
import { Cache } from "../lib/Cache.sol";
import { Events } from "../lib/Events.sol";
import { Exchange } from "../lib/Exchange.sol";
import { Interest } from "../lib/Interest.sol";
import { Require } from "../lib/Require.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";


library TradeImpl {
    using Storage for Storage.State;
    using Types for Types.Wei;

    // ============ Constants ============

    bytes32 constant FILE = "TradeImpl";

    // ============ Account Actions ============

    function buy(
        Storage.State storage state,
        Actions.BuyArgs memory args,
        Interest.Index memory takerIndex,
        Interest.Index memory makerIndex
    )
    public
    {
        state.requireIsOperator(args.account, msg.sender);

        address takerToken = state.getToken(args.takerMarket);
        address makerToken = state.getToken(args.makerMarket);

        (
            Types.Par memory makerPar,
            Types.Wei memory makerWei
        ) = state.getNewParAndDeltaWei(
            args.account,
            args.makerMarket,
            makerIndex,
            args.amount
        );

        Types.Wei memory takerWei = Exchange.getCost(
            args.exchangeWrapper,
            makerToken,
            takerToken,
            makerWei,
            args.orderData
        );

        Types.Wei memory tokensReceived = Exchange.exchange(
            args.exchangeWrapper,
            args.account.owner,
            makerToken,
            takerToken,
            takerWei,
            args.orderData
        );

        Require.that(
            tokensReceived.value >= makerWei.value,
            FILE,
            "Buy amount less than promised",
            tokensReceived.value
        );

        state.setPar(
            args.account,
            args.makerMarket,
            makerPar
        );

        state.setParFromDeltaWei(
            args.account,
            args.takerMarket,
            takerIndex,
            takerWei
        );

        Events.logBuy(
            state,
            args,
            takerWei,
            makerWei
        );
    }

    function sell(
        Storage.State storage state,
        Actions.SellArgs memory args,
        Interest.Index memory takerIndex,
        Interest.Index memory makerIndex
    )
    public
    {
        state.requireIsOperator(args.account, msg.sender);

        address takerToken = state.getToken(args.takerMarket);
        address makerToken = state.getToken(args.makerMarket);

        (
            Types.Par memory takerPar,
            Types.Wei memory takerWei
        ) = state.getNewParAndDeltaWei(
            args.account,
            args.takerMarket,
            takerIndex,
            args.amount
        );

        Types.Wei memory makerWei = Exchange.exchange(
            args.exchangeWrapper,
            args.account.owner,
            makerToken,
            takerToken,
            takerWei,
            args.orderData
        );

        state.setPar(
            args.account,
            args.takerMarket,
            takerPar
        );

        state.setParFromDeltaWei(
            args.account,
            args.makerMarket,
            makerIndex,
            makerWei
        );

        Events.logSell(
            state,
            args,
            takerWei,
            makerWei
        );
    }

    function trade(
        Storage.State storage state,
        Actions.TradeArgs memory args,
        Interest.Index memory inputIndex,
        Interest.Index memory outputIndex
    )
    public
    {
        state.requireIsOperator(args.takerAccount, msg.sender);
        state.requireIsOperator(args.makerAccount, args.autoTrader);
        if (state.isAutoTraderSpecial(args.autoTrader)) {
            Require.that(
                state.isGlobalOperator(msg.sender),
                FILE,
                "Unpermissioned trade operator"
            );
        }

        Types.Par memory oldInputPar = state.getPar(
            args.makerAccount,
            args.inputMarket
        );

        (
            Types.Par memory newInputPar,
            Types.Wei memory inputWei
        ) = state.getNewParAndDeltaWei(
            args.makerAccount,
            args.inputMarket,
            inputIndex,
            args.amount
        );

        Types.AssetAmount memory outputAmount = IAutoTrader(args.autoTrader).getTradeCost(
            args.inputMarket,
            args.outputMarket,
            args.makerAccount,
            args.takerAccount,
            oldInputPar,
            newInputPar,
            inputWei,
            args.tradeData
        );

        (
            Types.Par memory newOutputPar,
            Types.Wei memory outputWei
        ) = state.getNewParAndDeltaWei(
            args.makerAccount,
            args.outputMarket,
            outputIndex,
            outputAmount
        );

        Require.that(
            outputWei.isZero() || inputWei.isZero() || outputWei.sign != inputWei.sign,
            FILE,
            "Trades cannot be one-sided",
            args.autoTrader
        );

        // set the balance for the maker
        state.setPar(
            args.makerAccount,
            args.inputMarket,
            newInputPar
        );
        state.setPar(
            args.makerAccount,
            args.outputMarket,
            newOutputPar
        );

        // set the balance for the taker
        state.setParFromDeltaWei(
            args.takerAccount,
            args.inputMarket,
            inputIndex,
            inputWei.negative()
        );
        state.setParFromDeltaWei(
            args.takerAccount,
            args.outputMarket,
            outputIndex,
            outputWei.negative()
        );

        Events.logTrade(
            state,
            args,
            inputWei,
            outputWei
        );
    }
}

File 38 of 48 : OperationImpl.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IAutoTrader } from "../interfaces/IAutoTrader.sol";
import { ICallee } from "../interfaces/ICallee.sol";
import { Account } from "../lib/Account.sol";
import { Actions } from "../lib/Actions.sol";
import { Cache } from "../lib/Cache.sol";
import { Decimal } from "../lib/Decimal.sol";
import { EnumerableSet } from "../lib/EnumerableSet.sol";
import { Events } from "../lib/Events.sol";
import { Exchange } from "../lib/Exchange.sol";
import { Interest } from "../lib/Interest.sol";
import { DolomiteMarginMath } from "../lib/DolomiteMarginMath.sol";
import { Monetary } from "../lib/Monetary.sol";
import { Require } from "../lib/Require.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";
import { CallImpl } from "./CallImpl.sol";
import { DepositImpl } from "./DepositImpl.sol";
import { LiquidateOrVaporizeImpl } from "./LiquidateOrVaporizeImpl.sol";
import { TradeImpl } from "./TradeImpl.sol";
import { TransferImpl } from "./TransferImpl.sol";
import { WithdrawalImpl } from "./WithdrawalImpl.sol";


/**
 * @title OperationImpl
 * @author dYdX
 *
 * Logic for processing actions
 */
library OperationImpl {
    using Cache for Cache.MarketCache;
    using EnumerableSet for EnumerableSet.Set;
    using SafeMath for uint256;
    using Storage for Storage.State;
    using Types for Types.Par;
    using Types for Types.Wei;

    // ============ Constants ============

    bytes32 constant FILE = "OperationImpl";

    // ============ Public Functions ============

    function operate(
        Storage.State storage state,
        Account.Info[] memory accounts,
        Actions.ActionArgs[] memory actions
    )
        public
    {
        Events.logOperation();

        _verifyInputs(accounts, actions);

        (
            bool[] memory primaryAccounts,
            uint256[] memory numberOfMarketsWithBalancesPerAccount,
            Cache.MarketCache memory cache
        ) = _runPreprocessing(
            state,
            accounts,
            actions
        );

        _runActions(
            state,
            accounts,
            actions,
            cache
        );

        _verifyFinalState(
            state,
            accounts,
            primaryAccounts,
            numberOfMarketsWithBalancesPerAccount,
            cache
        );
    }

    // ============ Helper Functions ============

    function _verifyInputs(
        Account.Info[] memory accounts,
        Actions.ActionArgs[] memory actions
    )
        private
        pure
    {
        Require.that(
            accounts.length != 0,
            FILE,
            "Cannot have zero accounts"
        );
        Require.that(
            actions.length != 0,
            FILE,
            "Cannot have zero actions"
        );

        for (uint256 a = 0; a < accounts.length; a++) {
            for (uint256 b = a + 1; b < accounts.length; b++) {
                Require.that(
                    !Account.equals(accounts[a], accounts[b]),
                    FILE,
                    "Cannot duplicate accounts",
                    accounts[a].owner,
                    accounts[a].number
                );
            }
        }
    }

    function _runPreprocessing(
        Storage.State storage state,
        Account.Info[] memory accounts,
        Actions.ActionArgs[] memory actions
    )
        private
        returns (
            bool[] memory,
            uint256[] memory,
            Cache.MarketCache memory
        )
    {
        uint256 numMarkets = state.numMarkets;
        bool[] memory primaryAccounts = new bool[](accounts.length);
        uint256[] memory numberOfMarketsWithBalancesPerAccount = new uint256[](accounts.length);
        Cache.MarketCache memory cache = Cache.create(numMarkets);

        // keep track of primary accounts and indexes that need updating
        for (uint256 i = 0; i < actions.length; i++) {
            Actions.ActionArgs memory arg = actions[i];
            Actions.ActionType actionType = arg.actionType;
            Actions.MarketLayout marketLayout = Actions.getMarketLayout(actionType);
            Actions.AccountLayout accountLayout = Actions.getAccountLayout(actionType);

            // parse out primary accounts
            if (accountLayout != Actions.AccountLayout.OnePrimary) {
                Require.that(
                    arg.accountId != arg.otherAccountId,
                    FILE,
                    "Duplicate accounts in action",
                    i
                );
                if (accountLayout == Actions.AccountLayout.TwoPrimary) {
                    primaryAccounts[arg.otherAccountId] = true;
                } else {
                    // accountLayout == Actions.AccountLayout.PrimaryAndSecondary
                    Require.that(
                        !primaryAccounts[arg.otherAccountId],
                        FILE,
                        "Requires non-primary account",
                        arg.otherAccountId
                    );
                }
            }
            primaryAccounts[arg.accountId] = true;

            // keep track of indexes to update
            if (marketLayout == Actions.MarketLayout.OneMarket) {
                _updateMarket(state, cache, arg.primaryMarketId);
            } else if (marketLayout == Actions.MarketLayout.TwoMarkets) {
                Require.that(
                    arg.primaryMarketId != arg.secondaryMarketId,
                    FILE,
                    "Duplicate markets in action",
                    i
                );
                _updateMarket(state, cache, arg.primaryMarketId);
                _updateMarket(state, cache, arg.secondaryMarketId);
            }
        }

        // get any other markets for which an account has a balance
        for (uint256 a = 0; a < accounts.length; a++) {
            uint[] memory marketIdsWithBalance = state.getMarketsWithBalances(accounts[a]);
            numberOfMarketsWithBalancesPerAccount[a] = marketIdsWithBalance.length;
            for (uint256 i = 0; i < marketIdsWithBalance.length; i++) {
                _updateMarket(state, cache, marketIdsWithBalance[i]);
            }
        }

        state.initializeCache(cache);

        for (uint i = 0; i < cache.getNumMarkets(); i++) {
            Events.logOraclePrice(cache.getAtIndex(i));
        }

        return (primaryAccounts, numberOfMarketsWithBalancesPerAccount, cache);
    }

    function _updateMarket(
        Storage.State storage state,
        Cache.MarketCache memory cache,
        uint256 marketId
    )
        private
    {
        if (!cache.hasMarket(marketId)) {
            cache.set(marketId);
            Events.logIndexUpdate(marketId, state.updateIndex(marketId));
        }
    }

    function _runActions(
        Storage.State storage state,
        Account.Info[] memory accounts,
        Actions.ActionArgs[] memory actions,
        Cache.MarketCache memory cache
    )
        private
    {
        for (uint256 i = 0; i < actions.length; i++) {
            Actions.ActionArgs memory action = actions[i];
            Actions.ActionType actionType = action.actionType;

            if (actionType == Actions.ActionType.Deposit) {
                Actions.DepositArgs memory depositArgs = Actions.parseDepositArgs(accounts, action);
                DepositImpl.deposit(
                    state,
                    depositArgs,
                    cache.get(depositArgs.market).index
                );
            } else if (actionType == Actions.ActionType.Withdraw) {
                Actions.WithdrawArgs memory withdrawArgs = Actions.parseWithdrawArgs(accounts, action);
                WithdrawalImpl.withdraw(
                    state,
                    withdrawArgs,
                    cache.get(withdrawArgs.market).index
                );
            } else if (actionType == Actions.ActionType.Transfer) {
                Actions.TransferArgs memory transferArgs = Actions.parseTransferArgs(accounts, action);
                TransferImpl.transfer(
                    state,
                    transferArgs,
                    cache.get(transferArgs.market).index
                );
            } else if (actionType == Actions.ActionType.Buy) {
                Actions.BuyArgs memory buyArgs = Actions.parseBuyArgs(accounts, action);
                TradeImpl.buy(
                    state,
                    buyArgs,
                    cache.get(buyArgs.takerMarket).index,
                    cache.get(buyArgs.makerMarket).index
                );
            } else if (actionType == Actions.ActionType.Sell) {
                Actions.SellArgs memory sellArgs = Actions.parseSellArgs(accounts, action);
                TradeImpl.sell(
                    state,
                    sellArgs,
                    cache.get(sellArgs.takerMarket).index,
                    cache.get(sellArgs.makerMarket).index
                );
            } else if (actionType == Actions.ActionType.Trade) {
                Actions.TradeArgs memory tradeArgs = Actions.parseTradeArgs(accounts, action);
                TradeImpl.trade(
                    state,
                    tradeArgs,
                    cache.get(tradeArgs.inputMarket).index,
                    cache.get(tradeArgs.outputMarket).index
                );
            } else if (actionType == Actions.ActionType.Liquidate) {
                LiquidateOrVaporizeImpl.liquidate(
                    state,
                    cache,
                    Actions.parseLiquidateArgs(accounts, action)
                );
            } else if (actionType == Actions.ActionType.Vaporize) {
                LiquidateOrVaporizeImpl.vaporize(
                    state,
                    cache,
                    Actions.parseVaporizeArgs(accounts, action)
                );
            } else {
                assert(actionType == Actions.ActionType.Call);
                // solium-disable-next-line
                CallImpl.call(
                    state,
                    Actions.parseCallArgs(accounts, action)
                );
            }
        }
    }

    function _verifyFinalState(
        Storage.State storage state,
        Account.Info[] memory accounts,
        bool[] memory primaryAccounts,
        uint256[] memory numberOfMarketsWithBalancesPerAccount,
        Cache.MarketCache memory cache
    )
        private
    {
        // verify no increase in borrowPar for closing markets
        uint256 numMarkets = cache.getNumMarkets();
        for (uint256 i = 0; i < numMarkets; i++) {
            uint256 marketId = cache.getAtIndex(i).marketId;
            Types.TotalPar memory totalPar = state.getTotalPar(marketId);
            if (cache.getAtIndex(i).isClosing) {
                Require.that(
                    totalPar.borrow <= cache.getAtIndex(i).borrowPar,
                    FILE,
                    "Market is closing",
                    marketId
                );
            }

            Types.Wei memory maxWei = state.getMaxWei(marketId);
            if (maxWei.value != 0) {
                // require total supply is less than the max OR it scaled down
                Interest.Index memory index = cache.getAtIndex(i).index;
                (Types.Wei memory totalSupplyWei,) = Interest.totalParToWei(totalPar, index);
                Types.Wei memory cachedSupplyWei = Interest.parToWei(
                    Types.Par(true, cache.getAtIndex(i).supplyPar),
                    index
                );
                Require.that(
                    totalSupplyWei.value <= maxWei.value || totalSupplyWei.value <= cachedSupplyWei.value,
                    FILE,
                    "Total supply exceeds max supply",
                    marketId
                );
            }

            if (state.markets[marketId].isRecyclable) {
                // This market is recyclable. Check that only the `token` is the owner
                for (uint256 a = 0; a < accounts.length; a++) {
                    if (accounts[a].owner != cache.getAtIndex(i).token) {
                        // If the owner of the recyclable token isn't the TokenProxy,
                        // THEN check that the account doesn't have a balance for this recyclable `marketId`
                        Require.that(
                            !state.getMarketsWithBalancesSet(accounts[a]).contains(marketId),
                            FILE,
                            "Invalid recyclable owner",
                            accounts[a].owner,
                            accounts[a].number,
                            marketId
                        );
                    }
                }
            }
        }

        // verify account collateralization
        for (uint256 a = 0; a < accounts.length; a++) {
            Account.Info memory account = accounts[a];

            _verifyNumberOfMarketsWithBalances(state, account, numberOfMarketsWithBalancesPerAccount[a]);

            // don't check collateralization for non-primary accounts
            if (!primaryAccounts[a]) {
                continue;
            }

            // validate minBorrowedValue
            bool collateralized = state.isCollateralized(account, cache, /* requireMinBorrow = */ true);

            // check collateralization for primary accounts
            Require.that(
                collateralized,
                FILE,
                "Undercollateralized account",
                account.owner,
                account.number
            );

            // ensure status is normal for primary accounts
            if (state.getStatus(account) != Account.Status.Normal) {
                state.setStatus(account, Account.Status.Normal);
            }
        }
    }

    function _verifyNumberOfMarketsWithBalances(
        Storage.State storage state,
        Account.Info memory account,
        uint256 cachedNumberOfMarketsWithBalances
    )
        private view
    {
        // The account should either have less markets with balances than at the start of the transaction OR
        // less markets with balances than the max number of markets with balances per account
        uint256 actualNumberOfMarketsWithBalances = state.getNumberOfMarketsWithBalances(account);
        Require.that(
            actualNumberOfMarketsWithBalances <= cachedNumberOfMarketsWithBalances ||
            actualNumberOfMarketsWithBalances <= state.riskParams.accountMaxNumberOfMarketsWithBalances,
            FILE,
            "Too many non-zero balances",
            account.owner,
            account.number
        );
    }
}

File 39 of 48 : LiquidateOrVaporizeImpl.sol
/*

    Copyright 2021 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ILiquidationCallback } from "../interfaces/ILiquidationCallback.sol";
import { Account } from "../lib/Account.sol";
import { Actions } from "../lib/Actions.sol";
import { Cache } from "../lib/Cache.sol";
import { Decimal } from "../lib/Decimal.sol";
import { Events } from "../lib/Events.sol";
import { Interest } from "../lib/Interest.sol";
import { DolomiteMarginMath } from "../lib/DolomiteMarginMath.sol";
import { Monetary } from "../lib/Monetary.sol";
import { Require } from "../lib/Require.sol";
import { SafeLiquidationCallback } from "../lib/SafeLiquidationCallback.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";


/**
 * @dev A library that combines shares code for executing Liquidation or Vaporization actions.
 */
library LiquidateOrVaporizeImpl {
    using Cache for Cache.MarketCache;
    using SafeMath for uint256;
    using Storage for Storage.State;
    using Types for Types.Par;
    using Types for Types.Wei;

    // ============ Constants ============

    bytes32 constant FILE = "LiquidateOrVaporizeImpl";

    // ============ Account Functions ============

    function liquidate(
        Storage.State storage state,
        Cache.MarketCache memory cache,
        Actions.LiquidateArgs memory args
    )
    public
    {
        state.requireIsGlobalOperator(msg.sender);

        // verify liquidatable
        if (Account.Status.Liquid != state.getStatus(args.liquidAccount)) {
            Require.that(
                !state.isCollateralized(args.liquidAccount, cache, /* requireMinBorrow = */ false),
                FILE,
                "Unliquidatable account",
                args.liquidAccount.owner,
                args.liquidAccount.number
            );
            state.setStatus(args.liquidAccount, Account.Status.Liquid);
        }

        Types.Wei memory maxHeldWei = state.getWei(
            args.liquidAccount,
            args.heldMarket,
            cache.get(args.heldMarket).index
        );

        Require.that(
            !maxHeldWei.isNegative(),
            FILE,
            "Collateral cannot be negative",
            args.heldMarket
        );

        Interest.Index memory owedIndex = cache.get(args.owedMarket).index;
        Interest.Index memory heldIndex = cache.get(args.heldMarket).index;
        (
            Types.Par memory owedPar,
            Types.Wei memory owedWei
        ) = state.getNewParAndDeltaWeiForLiquidation(
            args.liquidAccount,
            args.owedMarket,
            owedIndex,
            args.amount
        );

        (
            Monetary.Price memory heldPrice,
            Monetary.Price memory owedPriceAdj
        ) = _getLiquidationPrices(
            state,
            cache,
            args.heldMarket,
            args.owedMarket
        );

        Types.Wei memory heldWei = _owedWeiToHeldWei(owedWei, heldPrice, owedPriceAdj);

        // if attempting to over-borrow the held asset, bound it by the maximum
        if (heldWei.value > maxHeldWei.value) {
            heldWei = maxHeldWei.negative();
            owedWei = _heldWeiToOwedWei(heldWei, heldPrice, owedPriceAdj);

            SafeLiquidationCallback.callLiquidateCallbackIfNecessary(
                args.liquidAccount,
                args.heldMarket,
                heldWei,
                args.owedMarket,
                owedWei
            );

            state.setPar(
                args.liquidAccount,
                args.heldMarket,
                Types.zeroPar()
            );
            state.setParFromDeltaWei(
                args.liquidAccount,
                args.owedMarket,
                owedIndex,
                owedWei
            );
        } else {
            SafeLiquidationCallback.callLiquidateCallbackIfNecessary(
                args.liquidAccount,
                args.heldMarket,
                heldWei,
                args.owedMarket,
                owedWei
            );

            state.setPar(
                args.liquidAccount,
                args.owedMarket,
                owedPar
            );
            state.setParFromDeltaWei(
                args.liquidAccount,
                args.heldMarket,
                heldIndex,
                heldWei
            );
        }

        // set the balances for the solid account
        state.setParFromDeltaWei(
            args.solidAccount,
            args.owedMarket,
            owedIndex,
            owedWei.negative()
        );
        state.setParFromDeltaWei(
            args.solidAccount,
            args.heldMarket,
            heldIndex,
            heldWei.negative()
        );

        Events.logLiquidate(
            state,
            args,
            heldWei,
            owedWei
        );
    }

    function vaporize(
        Storage.State storage state,
        Cache.MarketCache memory cache,
        Actions.VaporizeArgs memory args
    )
    public
    {
        state.requireIsOperator(args.solidAccount, msg.sender);

        // verify vaporizable
        if (Account.Status.Vapor != state.getStatus(args.vaporAccount)) {
            Require.that(
                state.isVaporizable(args.vaporAccount, cache),
                FILE,
                "Unvaporizable account",
                args.vaporAccount.owner,
                args.vaporAccount.number
            );
            state.setStatus(args.vaporAccount, Account.Status.Vapor);
        }

        // First, attempt to refund using the same token
        // cache.get(args.owedMarket).index is not stored in a variable here to avoid the "stack too deep" error
        (
            bool fullyRepaid,
            Types.Wei memory excessWei
        ) = _vaporizeUsingExcess(state, args, cache.get(args.owedMarket).index);
        if (fullyRepaid) {
            Events.logVaporize(
                state,
                args,
                Types.zeroWei(),
                Types.zeroWei(),
                excessWei
            );
            return;
        }

        Types.Wei memory maxHeldWei = state.getNumExcessTokens(args.heldMarket);

        Require.that(
            !maxHeldWei.isNegative(),
            FILE,
            "Excess cannot be negative",
            args.heldMarket
        );

        (
            Types.Par memory owedPar,
            Types.Wei memory owedWei
        ) = state.getNewParAndDeltaWeiForLiquidation(
            args.vaporAccount,
            args.owedMarket,
            cache.get(args.owedMarket).index,
            args.amount
        );

        (
            Monetary.Price memory heldPrice,
            Monetary.Price memory owedPrice
        ) = _getLiquidationPrices(
            state,
            cache,
            args.heldMarket,
            args.owedMarket
        );

        Types.Wei memory heldWei = _owedWeiToHeldWei(owedWei, heldPrice, owedPrice);

        // if attempting to over-borrow the held asset, bound it by the maximum
        if (heldWei.value > maxHeldWei.value) {
            heldWei = maxHeldWei.negative();
            owedWei = _heldWeiToOwedWei(heldWei, heldPrice, owedPrice);

            SafeLiquidationCallback.callLiquidateCallbackIfNecessary(
                args.vaporAccount,
                args.heldMarket,
                Types.zeroWei(),
                args.owedMarket,
                owedWei
            );

            state.setParFromDeltaWei(
                args.vaporAccount,
                args.owedMarket,
                cache.get(args.owedMarket).index,
                owedWei
            );
        } else {
            SafeLiquidationCallback.callLiquidateCallbackIfNecessary(
                args.vaporAccount,
                args.heldMarket,
                Types.zeroWei(),
                args.owedMarket,
                owedWei
            );

            state.setPar(
                args.vaporAccount,
                args.owedMarket,
                owedPar
            );
        }

        // set the balances for the solid account
        state.setParFromDeltaWei(
            args.solidAccount,
            args.owedMarket,
            cache.get(args.owedMarket).index,
            owedWei.negative()
        );
        state.setParFromDeltaWei(
            args.solidAccount,
            args.heldMarket,
            cache.get(args.heldMarket).index,
            heldWei.negative()
        );

        Events.logVaporize(
            state,
            args,
            heldWei,
            owedWei,
            excessWei
        );
    }

    /**
     * Attempt to vaporize an account's balance using the excess tokens in the protocol. Return a
     * bool and a wei value. The boolean is true if and only if the balance was fully vaporized. The
     * Wei value is how many excess tokens were used to partially or fully vaporize the account's
     * negative balance.
     */
    function _vaporizeUsingExcess(
        Storage.State storage state,
        Actions.VaporizeArgs memory args,
        Interest.Index memory owedIndex
    )
    internal
    returns (bool, Types.Wei memory)
    {
        Types.Wei memory excessWei = state.getNumExcessTokens(args.owedMarket);

        // There are no excess funds, return zero
        if (!excessWei.isPositive()) {
            return (false, Types.zeroWei());
        }

        Types.Wei memory maxRefundWei = state.getWei(
            args.vaporAccount,
            args.owedMarket,
            owedIndex
        );
        maxRefundWei.sign = true;

        // The account is fully vaporizable using excess funds
        if (excessWei.value >= maxRefundWei.value) {
            state.setPar(
                args.vaporAccount,
                args.owedMarket,
                Types.zeroPar()
            );
            return (true, maxRefundWei);
        }

        // The account is only partially vaporizable using excess funds
        else {
            state.setParFromDeltaWei(
                args.vaporAccount,
                args.owedMarket,
                owedIndex,
                excessWei
            );
            return (false, excessWei);
        }
    }

    /**
     * For the purposes of liquidation or vaporization, get the value-equivalent amount of owedWei
     * given heldWei and the (spread-adjusted) prices of each asset.
     */
    function _heldWeiToOwedWei(
        Types.Wei memory heldWei,
        Monetary.Price memory heldPrice,
        Monetary.Price memory owedPrice
    )
    internal
    pure
    returns (Types.Wei memory)
    {
        return Types.Wei({
        sign: true,
        value: DolomiteMarginMath.getPartialRoundUp(heldWei.value, heldPrice.value, owedPrice.value)
        });
    }

    /**
     * For the purposes of liquidation or vaporization, get the value-equivalent amount of heldWei
     * given owedWei and the (spread-adjusted) prices of each asset.
     */
    function _owedWeiToHeldWei(
        Types.Wei memory owedWei,
        Monetary.Price memory heldPrice,
        Monetary.Price memory owedPrice
    )
    internal
    pure
    returns (Types.Wei memory)
    {
        return Types.Wei({
        sign: false,
        value: DolomiteMarginMath.getPartial(owedWei.value, owedPrice.value, heldPrice.value)
        });
    }

    /**
     * Return the (spread-adjusted) prices of two assets for the purposes of liquidation or
     * vaporization.
     */
    function _getLiquidationPrices(
        Storage.State storage state,
        Cache.MarketCache memory cache,
        uint256 heldMarketId,
        uint256 owedMarketId
    )
    internal
    view
    returns (
        Monetary.Price memory,
        Monetary.Price memory
    )
    {
        uint256 owedPrice = cache.get(owedMarketId).price.value;
        Decimal.D256 memory spread = state.getLiquidationSpreadForPair(
            heldMarketId,
            owedMarketId
        );

        Monetary.Price memory owedPriceAdj = Monetary.Price({
            value: owedPrice.add(Decimal.mul(owedPrice, spread))
        });

        return (cache.get(heldMarketId).price, owedPriceAdj);
    }
}

File 40 of 48 : DepositImpl.sol
/*

    Copyright 2021 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Actions } from "../lib/Actions.sol";
import { Events } from "../lib/Events.sol";
import { Exchange } from "../lib/Exchange.sol";
import { Interest } from "../lib/Interest.sol";
import { Require } from "../lib/Require.sol";
import { Storage } from "../lib/Storage.sol";
import { Types } from "../lib/Types.sol";


library DepositImpl {
    using Storage for Storage.State;

    // ============ Constants ============

    bytes32 constant FILE = "DepositImpl";

    // ============ Account Actions ============

    function deposit(
        Storage.State storage state,
        Actions.DepositArgs memory args,
        Interest.Index memory index
    )
        public
    {
        state.requireIsOperator(args.account, msg.sender);

        Require.that(
            args.from == msg.sender || args.from == args.account.owner,
            FILE,
            "Invalid deposit source",
            args.from
        );

        (
            Types.Par memory newPar,
            Types.Wei memory deltaWei
        ) = state.getNewParAndDeltaWei(
            args.account,
            args.market,
            index,
            args.amount
        );

        state.setPar(
            args.account,
            args.market,
            newPar
        );

        // requires a positive deltaWei
        Exchange.transferIn(
            state.getToken(args.market),
            args.from,
            deltaWei
        );

        Events.logDeposit(
            state,
            args,
            deltaWei
        );
    }
}

File 41 of 48 : CallImpl.sol
/*

    Copyright 2021 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { ICallee } from "../interfaces/ICallee.sol";
import { Actions } from "../lib/Actions.sol";
import { Cache } from "../lib/Cache.sol";
import { Events } from "../lib/Events.sol";
import { Storage } from "../lib/Storage.sol";


library CallImpl {
    using Cache for Cache.MarketCache;
    using Storage for Storage.State;

    // ============ Constants ============

    bytes32 constant FILE = "CallImpl";

    // ============ Account Actions ============

    function call(
        Storage.State storage state,
        Actions.CallArgs memory args
    )
    public
    {
        state.requireIsOperator(args.account, msg.sender);

        ICallee(args.callee).callFunction(
            msg.sender,
            args.account,
            args.data
        );

        Events.logCall(args);
    }
}

File 42 of 48 : AdminImpl.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { IERC20Detailed } from "../interfaces/IERC20Detailed.sol";
import { IInterestSetter } from "../interfaces/IInterestSetter.sol";
import { IPriceOracle } from "../interfaces/IPriceOracle.sol";
import { IRecyclable } from "../interfaces/IRecyclable.sol";
import { Decimal } from "../lib/Decimal.sol";
import { Interest } from "../lib/Interest.sol";
import { DolomiteMarginMath } from "../lib/DolomiteMarginMath.sol";
import { Monetary } from "../lib/Monetary.sol";
import { Require } from "../lib/Require.sol";
import { Storage } from "../lib/Storage.sol";
import { Token } from "../lib/Token.sol";
import { Types } from "../lib/Types.sol";


/**
 * @title AdminImpl
 * @author dYdX
 *
 * Administrative functions to keep the protocol updated
 */
library AdminImpl {
    using DolomiteMarginMath for uint256;
    using Storage for Storage.State;
    using Token for address;
    using Types for Types.Wei;

    // ============ Constants ============

    bytes32 constant FILE = "AdminImpl";

    uint256 constant HEAD_POINTER = uint(-1);

    uint256 constant ONE_WEEK = 86400 * 7;

    // ============ Events ============

    event LogWithdrawExcessTokens(
        address token,
        uint256 amount
    );

    event LogWithdrawUnsupportedTokens(
        address token,
        uint256 amount
    );

    event LogAddMarket(
        uint256 marketId,
        address token
    );

    event LogRemoveMarket(
        uint256 marketId,
        address token
    );

    event LogSetIsClosing(
        uint256 marketId,
        bool isClosing
    );

    event LogSetPriceOracle(
        uint256 marketId,
        address priceOracle
    );

    event LogSetInterestSetter(
        uint256 marketId,
        address interestSetter
    );

    event LogSetMarginPremium(
        uint256 marketId,
        Decimal.D256 marginPremium
    );

    event LogSetSpreadPremium(
        uint256 marketId,
        Decimal.D256 spreadPremium
    );

    event LogSetMaxWei(
        uint256 marketId,
        Types.Wei maxWei
    );

    event LogSetMarginRatio(
        Decimal.D256 marginRatio
    );

    event LogSetLiquidationSpread(
        Decimal.D256 liquidationSpread
    );

    event LogSetEarningsRate(
        Decimal.D256 earningsRate
    );

    event LogSetMinBorrowedValue(
        Monetary.Value minBorrowedValue
    );

    event LogSetAccountMaxNumberOfMarketsWithBalances(
        uint256 accountMaxNumberOfMarketsWithBalances
    );

    event LogSetGlobalOperator(
        address operator,
        bool approved
    );

    event LogSetAutoTraderIsSpecial(
        address autoTrader,
        bool isSpecial
    );

    // ============ Token Functions ============

    function ownerWithdrawExcessTokens(
        Storage.State storage state,
        uint256 marketId,
        address recipient
    )
    public
    returns (uint256)
    {
        _validateMarketId(state, marketId);
        Types.Wei memory excessWei = state.getNumExcessTokens(marketId);

        Require.that(
            !excessWei.isNegative(),
            FILE,
            "Negative excess"
        );

        address token = state.getToken(marketId);

        uint256 actualBalance = IERC20Detailed(token).balanceOf(address(this));
        if (excessWei.value > actualBalance) {
            excessWei.value = actualBalance;
        }

        token.transfer(recipient, excessWei.value);

        emit LogWithdrawExcessTokens(token, excessWei.value);

        return excessWei.value;
    }

    function ownerWithdrawUnsupportedTokens(
        Storage.State storage state,
        address token,
        address recipient
    )
    public
    returns (uint256)
    {
        _requireNoMarket(state, token);

        uint256 balance = IERC20Detailed(token).balanceOf(address(this));
        token.transfer(recipient, balance);

        emit LogWithdrawUnsupportedTokens(token, balance);

        return balance;
    }

    // ============ Market Functions ============

    function ownerAddMarket(
        Storage.State storage state,
        address token,
        IPriceOracle priceOracle,
        IInterestSetter interestSetter,
        Decimal.D256 memory marginPremium,
        Decimal.D256 memory spreadPremium,
        uint256 maxWei,
        bool isClosing,
        bool isRecyclable
    )
    public
    {
        _requireNoMarket(state, token);

        uint256 marketId = state.recycledMarketIds[HEAD_POINTER];
        if (marketId == 0) {
            // we can't recycle a marketId, so we get a new ID and increment the number of markets
            marketId = state.numMarkets;
            state.numMarkets++;
        } else {
            // we successfully recycled the market ID.
            // reset the head pointer to the next item in the linked list
            state.recycledMarketIds[HEAD_POINTER] = state.recycledMarketIds[marketId];
        }

        state.markets[marketId].token = token;
        state.markets[marketId].index = Interest.newIndex();
        state.markets[marketId].isClosing = isClosing;
        state.markets[marketId].isRecyclable = isRecyclable;
        state.tokenToMarketId[token] = marketId;

        emit LogAddMarket(marketId, token);
        if (isClosing) {
            emit LogSetIsClosing(marketId, isClosing);
        }

        _setPriceOracle(state, marketId, priceOracle);
        _setInterestSetter(state, marketId, interestSetter);
        _setMarginPremium(state, marketId, marginPremium);
        _setSpreadPremium(state, marketId, spreadPremium);
        _setMaxWei(state, marketId, maxWei);

        if (isRecyclable) {
            IRecyclable(token).initialize();
        }
    }

    function ownerRemoveMarkets(
        Storage.State storage state,
        uint[] memory marketIds,
        address salvager
    )
    public
    {
        for (uint i = 0; i < marketIds.length; i++) {
            address token = state.markets[marketIds[i]].token;
            Require.that(
                token != address(0),
                FILE,
                "market does not exist",
                marketIds[i]
            );
            Require.that(
                state.markets[marketIds[i]].isRecyclable,
                FILE,
                "market is not recyclable",
                marketIds[i]
            );

            (
                Types.Wei memory supplyWei,
                Types.Wei memory borrowWei
            ) = Interest.totalParToWei(state.getTotalPar(marketIds[i]), state.getIndex(marketIds[i]));

            Require.that(
                borrowWei.value == 0,
                FILE,
                "market has active borrows",
                marketIds[i]
            );
            uint expirationTimestamp = IRecyclable(state.getToken(marketIds[i])).MAX_EXPIRATION_TIMESTAMP();
            Require.that(
                expirationTimestamp < block.timestamp,
                FILE,
                "market is not expired",
                marketIds[i],
                expirationTimestamp
            );
            // Give the expiration timestamp a 7-day buffer to ensure enough time has passed for expirations to occur
            Require.that(
                (expirationTimestamp + ONE_WEEK) < block.timestamp,
                FILE,
                "expiration must pass buffer",
                marketIds[i],
                expirationTimestamp
            );

            Token.transfer(token, salvager, supplyWei.value);

            delete state.markets[marketIds[i]];
            delete state.tokenToMarketId[token];

            uint previousHead = state.recycledMarketIds[HEAD_POINTER];
            state.recycledMarketIds[HEAD_POINTER] = marketIds[i];
            if (previousHead != 0) {
                // marketId=0 is not recyclable so we can assume previousHead == 0 means the null case
                state.recycledMarketIds[marketIds[i]] = previousHead;
            }

            IRecyclable(token).recycle();

            emit LogRemoveMarket(marketIds[i], token);
        }
    }

    function ownerSetIsClosing(
        Storage.State storage state,
        uint256 marketId,
        bool isClosing
    )
    public
    {
        _validateMarketId(state, marketId);

        state.markets[marketId].isClosing = isClosing;
        emit LogSetIsClosing(marketId, isClosing);
    }

    function ownerSetPriceOracle(
        Storage.State storage state,
        uint256 marketId,
        IPriceOracle priceOracle
    )
    public
    {
        _validateMarketId(state, marketId);
        _setPriceOracle(state, marketId, priceOracle);
    }

    function ownerSetInterestSetter(
        Storage.State storage state,
        uint256 marketId,
        IInterestSetter interestSetter
    )
    public
    {
        _validateMarketId(state, marketId);
        _setInterestSetter(state, marketId, interestSetter);
    }

    function ownerSetMarginPremium(
        Storage.State storage state,
        uint256 marketId,
        Decimal.D256 memory marginPremium
    )
    public
    {
        _validateMarketId(state, marketId);
        _setMarginPremium(state, marketId, marginPremium);
    }

    function ownerSetSpreadPremium(
        Storage.State storage state,
        uint256 marketId,
        Decimal.D256 memory spreadPremium
    )
    public
    {
        _validateMarketId(state, marketId);
        _setSpreadPremium(state, marketId, spreadPremium);
    }

    function ownerSetMaxWei(
        Storage.State storage state,
        uint256 marketId,
        uint256 maxWei
    )
    public
    {
        _validateMarketId(state, marketId);
        _setMaxWei(state, marketId, maxWei);
    }

    // ============ Risk Functions ============

    function ownerSetMarginRatio(
        Storage.State storage state,
        Decimal.D256 memory ratio
    )
    public
    {
        Require.that(
            ratio.value <= state.riskLimits.marginRatioMax,
            FILE,
            "Ratio too high"
        );
        Require.that(
            ratio.value > state.riskParams.liquidationSpread.value,
            FILE,
            "Ratio cannot be <= spread"
        );
        state.riskParams.marginRatio = ratio;
        emit LogSetMarginRatio(ratio);
    }

    function ownerSetLiquidationSpread(
        Storage.State storage state,
        Decimal.D256 memory spread
    )
    public
    {
        Require.that(
            spread.value <= state.riskLimits.liquidationSpreadMax,
            FILE,
            "Spread too high"
        );
        Require.that(
            spread.value < state.riskParams.marginRatio.value,
            FILE,
            "Spread cannot be >= ratio"
        );
        state.riskParams.liquidationSpread = spread;
        emit LogSetLiquidationSpread(spread);
    }

    function ownerSetEarningsRate(
        Storage.State storage state,
        Decimal.D256 memory earningsRate
    )
    public
    {
        Require.that(
            earningsRate.value <= state.riskLimits.earningsRateMax,
            FILE,
            "Rate too high"
        );
        state.riskParams.earningsRate = earningsRate;
        emit LogSetEarningsRate(earningsRate);
    }

    function ownerSetMinBorrowedValue(
        Storage.State storage state,
        Monetary.Value memory minBorrowedValue
    )
    public
    {
        Require.that(
            minBorrowedValue.value <= state.riskLimits.minBorrowedValueMax,
            FILE,
            "Value too high"
        );
        state.riskParams.minBorrowedValue = minBorrowedValue;
        emit LogSetMinBorrowedValue(minBorrowedValue);
    }

    function ownerSetAccountMaxNumberOfMarketsWithBalances(
        Storage.State storage state,
        uint256 accountMaxNumberOfMarketsWithBalances
    ) public {
        Require.that(
            accountMaxNumberOfMarketsWithBalances >= 2,
            FILE,
            "Acct MaxNumberOfMarkets too low"
        );
        state.riskParams.accountMaxNumberOfMarketsWithBalances = accountMaxNumberOfMarketsWithBalances;
        emit LogSetAccountMaxNumberOfMarketsWithBalances(accountMaxNumberOfMarketsWithBalances);
    }

    // ============ Global Operator Functions ============

    function ownerSetGlobalOperator(
        Storage.State storage state,
        address operator,
        bool approved
    )
    public
    {
        state.globalOperators[operator] = approved;

        emit LogSetGlobalOperator(operator, approved);
    }

    function ownerSetAutoTraderSpecial(
        Storage.State storage state,
        address autoTrader,
        bool isSpecial
    )
    public
    {
        state.specialAutoTraders[autoTrader] = isSpecial;

        emit LogSetAutoTraderIsSpecial(autoTrader, isSpecial);
    }

    // ============ Private Functions ============

    function _setPriceOracle(
        Storage.State storage state,
        uint256 marketId,
        IPriceOracle priceOracle
    )
    private
    {
        // require oracle can return non-zero price
        address token = state.markets[marketId].token;

        Require.that(
            priceOracle.getPrice(token).value != 0,
            FILE,
            "Invalid oracle price"
        );

        state.markets[marketId].priceOracle = priceOracle;

        emit LogSetPriceOracle(marketId, address(priceOracle));
    }

    function _setInterestSetter(
        Storage.State storage state,
        uint256 marketId,
        IInterestSetter interestSetter
    )
    private
    {
        // ensure interestSetter can return a value without reverting
        address token = state.markets[marketId].token;
        interestSetter.getInterestRate(token, 0, 0);

        state.markets[marketId].interestSetter = interestSetter;

        emit LogSetInterestSetter(marketId, address(interestSetter));
    }

    function _setMarginPremium(
        Storage.State storage state,
        uint256 marketId,
        Decimal.D256 memory marginPremium
    )
    private
    {
        Require.that(
            marginPremium.value <= state.riskLimits.marginPremiumMax,
            FILE,
            "Margin premium too high"
        );
        state.markets[marketId].marginPremium = marginPremium;

        emit LogSetMarginPremium(marketId, marginPremium);
    }

    function _setSpreadPremium(
        Storage.State storage state,
        uint256 marketId,
        Decimal.D256 memory spreadPremium
    )
    private
    {
        Require.that(
            spreadPremium.value <= state.riskLimits.spreadPremiumMax,
            FILE,
            "Spread premium too high"
        );
        state.markets[marketId].spreadPremium = spreadPremium;

        emit LogSetSpreadPremium(marketId, spreadPremium);
    }

    function _setMaxWei(
        Storage.State storage state,
        uint256 marketId,
        uint256 maxWei
    )
    private
    {
        Types.Wei memory maxWeiStruct = Types.Wei(true, maxWei.to128());
        state.markets[marketId].maxWei = maxWeiStruct;

        emit LogSetMaxWei(marketId, maxWeiStruct);
    }

    function _requireNoMarket(
        Storage.State storage state,
        address token
    )
    private
    view
    {
        // not-found case is marketId of 0. 0 is a valid market ID so we need to check market ID 0's token equality.
        uint marketId = state.tokenToMarketId[token];
        bool marketExists = token == state.markets[marketId].token;

        Require.that(
            !marketExists,
            FILE,
            "Market exists"
        );
    }

    function _validateMarketId(
        Storage.State storage state,
        uint256 marketId
    )
    private
    view
    {
        Require.that(
            marketId < state.numMarkets && state.markets[marketId].token != address(0),
            FILE,
            "Invalid market",
            marketId
        );
    }
}

File 43 of 48 : State.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Storage } from "./lib/Storage.sol";


/**
 * @title State
 * @author dYdX
 *
 * Base-level contract that holds the state of DolomiteMargin
 */
contract State
{
    Storage.State internal g_state;
}

File 44 of 48 : Permission.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { State } from "./State.sol";
import { Types } from "./lib/Types.sol";


/**
 * @title Permission
 * @author dYdX
 *
 * Public function that allows other addresses to manage accounts
 */
contract Permission is
    State
{
    // ============ Events ============

    event LogOperatorSet(
        address indexed owner,
        address operator,
        bool trusted
    );

    // ============ Public Functions ============

    /**
     * Approves/disapproves any number of operators. An operator is an external address that has the
     * same permissions to manipulate an account as the owner of the account. Operators are simply
     * addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts.
     *
     * Operators are also able to act as AutoTrader contracts on behalf of the account owner if the
     * operator is a smart contract and implements the IAutoTrader interface.
     *
     * @param  args  A list of OperatorArgs which have an address and a boolean. The boolean value
     *               denotes whether to approve (true) or revoke approval (false) for that address.
     */
    function setOperators(
        Types.OperatorArg[] memory args
    )
        public
    {
        for (uint256 i = 0; i < args.length; i++) {
            address operator = args[i].operator;
            bool trusted = args[i].trusted;
            g_state.operators[msg.sender][operator] = trusted;
            emit LogOperatorSet(msg.sender, operator, trusted);
        }
    }
}

File 45 of 48 : Operation.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { State } from "./State.sol";
import { OperationImpl } from "./impl/OperationImpl.sol";
import { Account } from "./lib/Account.sol";
import { Actions } from "./lib/Actions.sol";


/**
 * @title Operation
 * @author dYdX
 *
 * Primary public function for allowing users and contracts to manage accounts within DolomiteMargin
 */
contract Operation is
    State,
    ReentrancyGuard
{
    // ============ Public Functions ============

    /**
     * The main entry-point to DolomiteMargin that allows users and contracts to manage accounts.
     * Take one or more actions on one or more accounts. The msg.sender must be the owner or
     * operator of all accounts except for those being liquidated, vaporized, or traded with.
     * One call to operate() is considered a singular "operation". Account collateralization is
     * ensured only after the completion of the entire operation.
     *
     * @param  accounts  A list of all accounts that will be used in this operation. Cannot contain
     *                   duplicates. In each action, the relevant account will be referred-to by its
     *                   index in the list.
     * @param  actions   An ordered list of all actions that will be taken in this operation. The
     *                   actions will be processed in order.
     */
    function operate(
        Account.Info[] memory accounts,
        Actions.ActionArgs[] memory actions
    )
        public
        nonReentrant
    {
        OperationImpl.operate(
            g_state,
            accounts,
            actions
        );
    }
}

File 46 of 48 : Getters.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { State } from "./State.sol";
import { IInterestSetter } from "./interfaces/IInterestSetter.sol";
import { IPriceOracle } from "./interfaces/IPriceOracle.sol";
import { Account } from "./lib/Account.sol";
import { Cache } from "./lib/Cache.sol";
import { Decimal } from "./lib/Decimal.sol";
import { EnumerableSet } from "./lib/EnumerableSet.sol";
import { Interest } from "./lib/Interest.sol";
import { Monetary } from "./lib/Monetary.sol";
import { Require } from "./lib/Require.sol";
import { Storage } from "./lib/Storage.sol";
import { Token } from "./lib/Token.sol";
import { Types } from "./lib/Types.sol";


/**
 * @title Getters
 * @author dYdX
 *
 * Public read-only functions that allow transparency into the state of DolomiteMargin
 */
contract Getters is
    State
{
    using Cache for Cache.MarketCache;
    using Storage for Storage.State;
    using Types for Types.Par;
    using EnumerableSet for EnumerableSet.Set;

    // ============ Constants ============

    bytes32 FILE = "Getters";

    // ============ Getters for Risk ============

    function getMarginRatio()
        public
        view
        returns (Decimal.D256 memory)
    {
        return g_state.riskParams.marginRatio;
    }

    function getLiquidationSpread()
        public
        view
        returns (Decimal.D256 memory)
    {
        return g_state.riskParams.liquidationSpread;
    }

    function getEarningsRate()
        public
        view
        returns (Decimal.D256 memory)
    {
        return g_state.riskParams.earningsRate;
    }

    function getMinBorrowedValue()
        public
        view
        returns (Monetary.Value memory)
    {
        return g_state.riskParams.minBorrowedValue;
    }

    function getAccountMaxNumberOfMarketsWithBalances()
        public
        view
        returns (uint256)
    {
        return g_state.riskParams.accountMaxNumberOfMarketsWithBalances;
    }

    function getRiskParams()
        public
        view
        returns (Storage.RiskParams memory)
    {
        return g_state.riskParams;
    }

    function getRiskLimits()
        public
        view
        returns (Storage.RiskLimits memory)
    {
        return g_state.riskLimits;
    }

    // ============ Getters for Markets ============

    function getNumMarkets()
        public
        view
        returns (uint256)
    {
        return g_state.numMarkets;
    }

    function getMarketTokenAddress(
        uint256 marketId
    )
        public
        view
        returns (address)
    {
        _requireValidMarket(marketId);
        return g_state.getToken(marketId);
    }

    function getMarketIdByTokenAddress(
        address token
    )
        public
        view
        returns (uint256)
    {
        _requireValidToken(token);
        return g_state.tokenToMarketId[token];
    }

    function getMarketTotalPar(
        uint256 marketId
    )
        public
        view
        returns (Types.TotalPar memory)
    {
        _requireValidMarket(marketId);
        return g_state.getTotalPar(marketId);
    }

    function getMarketCachedIndex(
        uint256 marketId
    )
        public
        view
        returns (Interest.Index memory)
    {
        _requireValidMarket(marketId);
        return g_state.getIndex(marketId);
    }

    function getMarketCurrentIndex(
        uint256 marketId
    )
        public
        view
        returns (Interest.Index memory)
    {
        _requireValidMarket(marketId);
        return g_state.fetchNewIndex(marketId, g_state.getIndex(marketId));
    }

    function getMarketPriceOracle(
        uint256 marketId
    )
        public
        view
        returns (IPriceOracle)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].priceOracle;
    }

    function getMarketInterestSetter(
        uint256 marketId
    )
        public
        view
        returns (IInterestSetter)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].interestSetter;
    }

    function getMarketMarginPremium(
        uint256 marketId
    )
        public
        view
        returns (Decimal.D256 memory)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].marginPremium;
    }

    function getMarketSpreadPremium(
        uint256 marketId
    )
        public
        view
        returns (Decimal.D256 memory)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].spreadPremium;
    }

    function getMarketMaxWei(
        uint256 marketId
    )
        public
        view
        returns (Types.Wei memory)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].maxWei;
    }

    function getMarketIsClosing(
        uint256 marketId
    )
        public
        view
        returns (bool)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].isClosing;
    }

    function getMarketIsRecyclable(
        uint256 marketId
    )
        public
        view
        returns (bool)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId].isRecyclable;
    }

    function getRecyclableMarkets(
        uint256 n
    )
        public
        view
        returns (uint[] memory)
    {
        uint counter = 0;
        uint[] memory markets = new uint[](n);
        uint pointer = g_state.recycledMarketIds[uint(-1)]; // uint(-1) is the HEAD_POINTER
        while (pointer != 0 && counter < n) {
            markets[counter++] = pointer;
            pointer = g_state.recycledMarketIds[pointer];
        }
        return markets;
    }

    function getMarketPrice(
        uint256 marketId
    )
        public
        view
        returns (Monetary.Price memory)
    {
        _requireValidMarket(marketId);
        return g_state.fetchPrice(marketId, g_state.getToken(marketId));
    }

    function getMarketInterestRate(
        uint256 marketId
    )
        public
        view
        returns (Interest.Rate memory)
    {
        _requireValidMarket(marketId);
        return g_state.fetchInterestRate(
            marketId,
            g_state.getIndex(marketId)
        );
    }

    function getLiquidationSpreadForPair(
        uint256 heldMarketId,
        uint256 owedMarketId
    )
        public
        view
        returns (Decimal.D256 memory)
    {
        _requireValidMarket(heldMarketId);
        _requireValidMarket(owedMarketId);
        return g_state.getLiquidationSpreadForPair(heldMarketId, owedMarketId);
    }

    function getMarket(
        uint256 marketId
    )
        public
        view
        returns (Storage.Market memory)
    {
        _requireValidMarket(marketId);
        return g_state.markets[marketId];
    }

    function getMarketWithInfo(
        uint256 marketId
    )
        public
        view
        returns (
            Storage.Market memory,
            Interest.Index memory,
            Monetary.Price memory,
            Interest.Rate memory
        )
    {
        _requireValidMarket(marketId);
        return (
            getMarket(marketId),
            getMarketCurrentIndex(marketId),
            getMarketPrice(marketId),
            getMarketInterestRate(marketId)
        );
    }

    function getNumExcessTokens(
        uint256 marketId
    )
        public
        view
        returns (Types.Wei memory)
    {
        _requireValidMarket(marketId);
        return g_state.getNumExcessTokens(marketId);
    }

    function getAccountPar(
        Account.Info memory account,
        uint256 marketId
    )
        public
        view
        returns (Types.Par memory)
    {
        _requireValidMarket(marketId);
        return g_state.getPar(account, marketId);
    }

    function getAccountParNoMarketCheck(
        Account.Info memory account,
        uint256 marketId
    )
        public
        view
        returns (Types.Par memory)
    {
        return g_state.getPar(account, marketId);
    }

    function getAccountWei(
        Account.Info memory account,
        uint256 marketId
    )
        public
        view
        returns (Types.Wei memory)
    {
        _requireValidMarket(marketId);
        return Interest.parToWei(
            g_state.getPar(account, marketId),
            g_state.fetchNewIndex(marketId, g_state.getIndex(marketId))
        );
    }

    function getAccountStatus(
        Account.Info memory account
    )
        public
        view
        returns (Account.Status)
    {
        return g_state.getStatus(account);
    }

    function getAccountMarketsWithBalances(
        Account.Info memory account
    )
        public
        view
        returns (uint256[] memory)
    {
        return g_state.getMarketsWithBalances(account);
    }

    function getAccountNumberOfMarketsWithBalances(
        Account.Info memory account
    )
        public
        view
        returns (uint256)
    {
        return g_state.getNumberOfMarketsWithBalances(account);
    }

    function getAccountMarketWithBalanceAtIndex(
        Account.Info memory account,
        uint256 index
    )
        public
        view
        returns (uint256)
    {
        return g_state.getAccountMarketWithBalanceAtIndex(account, index);
    }

    function getAccountNumberOfMarketsWithDebt(
        Account.Info memory account
    )
        public
        view
        returns (uint256)
    {
        return g_state.getAccountNumberOfMarketsWithDebt(account);
    }

    function getAccountValues(
        Account.Info memory account
    )
        public
        view
        returns (Monetary.Value memory, Monetary.Value memory)
    {
        return _getAccountValuesInternal(account, /* adjustForLiquidity = */ false);
    }

    function getAdjustedAccountValues(
        Account.Info memory account
    )
        public
        view
        returns (Monetary.Value memory, Monetary.Value memory)
    {
        return _getAccountValuesInternal(account, /* adjustForLiquidity = */ true);
    }

    function getAccountBalances(
        Account.Info memory account
    )
        public
        view
        returns (
            uint[] memory,
            address[] memory,
            Types.Par[] memory,
            Types.Wei[] memory
        )
    {
        uint256[] memory markets = g_state.getMarketsWithBalances(account);
        address[] memory tokens = new address[](markets.length);
        Types.Par[] memory pars = new Types.Par[](markets.length);
        Types.Wei[] memory weis = new Types.Wei[](markets.length);

        for (uint256 i = 0; i < markets.length; i++) {
            tokens[i] = getMarketTokenAddress(markets[i]);
            pars[i] = getAccountPar(account, markets[i]);
            weis[i] = getAccountWei(account, markets[i]);
        }

        return (
            markets,
            tokens,
            pars,
            weis
        );
    }

    function getIsLocalOperator(
        address owner,
        address operator
    )
        public
        view
        returns (bool)
    {
        return g_state.isLocalOperator(owner, operator);
    }

    function getIsGlobalOperator(
        address operator
    )
        public
        view
        returns (bool)
    {
        return g_state.isGlobalOperator(operator);
    }

    function getIsAutoTraderSpecial(
        address autoTrader
    )
        public
        view
        returns (bool)
    {
        return g_state.isAutoTraderSpecial(autoTrader);
    }

    // ============ Internal/Private Helper Functions ============

    /**
     * Revert if marketId is invalid.
     */
    function _requireValidMarket(
        uint256 marketId
    )
        internal
        view
    {
        Require.that(
            marketId < g_state.numMarkets && g_state.markets[marketId].token != address(0),
            FILE,
            "Invalid market"
        );
    }

    function _requireValidToken(
        address token
    )
        private
        view
    {
        Require.that(
            token == g_state.markets[g_state.tokenToMarketId[token]].token,
            FILE,
            "Invalid token"
        );
    }

    /**
     * Private helper for getting the monetary values of an account.
     */
    function _getAccountValuesInternal(
        Account.Info memory account,
        bool adjustForLiquidity
    )
        private
        view
        returns (Monetary.Value memory, Monetary.Value memory)
    {
        uint256[] memory markets = g_state.getMarketsWithBalances(account);

        // populate cache
        Cache.MarketCache memory cache = Cache.create(markets.length);
        for (uint256 i = 0; i < markets.length; i++) {
            cache.set(markets[i]);
        }
        g_state.initializeCache(cache);

        return g_state.getAccountValues(account, cache, adjustForLiquidity);
    }
}

File 47 of 48 : ReentrancyGuard.sol
pragma solidity ^0.5.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * _Since v2.5.0:_ this module is now much more gas efficient, given net gas
 * metering changes introduced in the Istanbul hardfork.
 */
contract ReentrancyGuard {
    bool private _notEntered;

    constructor () internal {
        // Storing an initial 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 percetange 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.
        _notEntered = true;
    }

    /**
     * @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(_notEntered, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _notEntered = false;

        _;

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

File 48 of 48 : Admin.sol
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;

import { Ownable } from "@openzeppelin/contracts/ownership/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { State } from "./State.sol";
import { AdminImpl } from "./impl/AdminImpl.sol";
import { IInterestSetter } from "./interfaces/IInterestSetter.sol";
import { IPriceOracle } from "./interfaces/IPriceOracle.sol";
import { Decimal } from "./lib/Decimal.sol";
import { Interest } from "./lib/Interest.sol";
import { Monetary } from "./lib/Monetary.sol";
import { Token } from "./lib/Token.sol";


/**
 * @title Admin
 * @author dYdX
 *
 * Public functions that allow the privileged owner address to manage DolomiteMargin
 */
contract Admin is
    State,
    Ownable,
    ReentrancyGuard
{
    // ============ Token Functions ============

    /**
     * Withdraw an ERC20 token for which there is an associated market. Only excess tokens can be withdrawn. The number
     * of excess tokens is calculated by taking the current number of tokens held in DolomiteMargin, adding the number
     * of tokens owed to DolomiteMargin by borrowers, and subtracting the number of tokens owed to suppliers by
     * DolomiteMargin.
     */
    function ownerWithdrawExcessTokens(
        uint256 marketId,
        address recipient
    )
        public
        onlyOwner
        nonReentrant
        returns (uint256)
    {
        return AdminImpl.ownerWithdrawExcessTokens(
            g_state,
            marketId,
            recipient
        );
    }

    /**
     * Withdraw an ERC20 token for which there is no associated market.
     */
    function ownerWithdrawUnsupportedTokens(
        address token,
        address recipient
    )
        public
        onlyOwner
        nonReentrant
        returns (uint256)
    {
        return AdminImpl.ownerWithdrawUnsupportedTokens(
            g_state,
            token,
            recipient
        );
    }

    // ============ Market Functions ============

    /**
     * Sets the number of non-zero balances an account may have within the same `accountIndex`. This ensures a user
     * cannot DOS the system by filling their account with non-zero balances (which linearly increases gas costs when
     * checking collateralization) and disallowing themselves to close the position, because the number of gas units
     * needed to process their transaction exceed the block's gas limit. In turn, this would  prevent the user from also
     * being liquidated, causing the all of the capital to be "stuck" in the position.
     *
     * Lowering this number does not "freeze" user accounts that have more than the new limit of balances, because this
     * variable is enforced by checking the users number of non-zero balances against the max or if it sizes down before
     * each transaction finishes.
     */
    function ownerSetAccountMaxNumberOfMarketsWithBalances(
        uint256 accountMaxNumberOfMarketsWithBalances
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetAccountMaxNumberOfMarketsWithBalances(
            g_state,
            accountMaxNumberOfMarketsWithBalances
        );
    }

    /**
     * Add a new market to DolomiteMargin. Must be for a previously-unsupported ERC20 token.
     */
    function ownerAddMarket(
        address token,
        IPriceOracle priceOracle,
        IInterestSetter interestSetter,
        Decimal.D256 memory marginPremium,
        Decimal.D256 memory spreadPremium,
        uint256 maxWei,
        bool isClosing,
        bool isRecyclable
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerAddMarket(
            g_state,
            token,
            priceOracle,
            interestSetter,
            marginPremium,
            spreadPremium,
            maxWei,
            isClosing,
            isRecyclable
        );
    }

    /**
     * Removes a market from DolomiteMargin, sends any remaining tokens in this contract to `salvager` and invokes the
     * recyclable callback
     */
    function ownerRemoveMarkets(
        uint[] memory marketIds,
        address salvager
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerRemoveMarkets(
            g_state,
            marketIds,
            salvager
        );
    }

    /**
     * Set (or unset) the status of a market to "closing". The borrowedValue of a market cannot increase while its
     * status is "closing".
     */
    function ownerSetIsClosing(
        uint256 marketId,
        bool isClosing
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetIsClosing(
            g_state,
            marketId,
            isClosing
        );
    }

    /**
     * Set the price oracle for a market.
     */
    function ownerSetPriceOracle(
        uint256 marketId,
        IPriceOracle priceOracle
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetPriceOracle(
            g_state,
            marketId,
            priceOracle
        );
    }

    /**
     * Set the interest-setter for a market.
     */
    function ownerSetInterestSetter(
        uint256 marketId,
        IInterestSetter interestSetter
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetInterestSetter(
            g_state,
            marketId,
            interestSetter
        );
    }

    /**
     * Set a premium on the minimum margin-ratio for a market. This makes it so that any positions that include this
     * market require a higher collateralization to avoid being liquidated.
     */
    function ownerSetMarginPremium(
        uint256 marketId,
        Decimal.D256 memory marginPremium
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetMarginPremium(
            g_state,
            marketId,
            marginPremium
        );
    }

    function ownerSetMaxWei(
        uint256 marketId,
        uint256 maxWei
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetMaxWei(
            g_state,
            marketId,
            maxWei
        );
    }

    /**
     * Set a premium on the liquidation spread for a market. This makes it so that any liquidations that include this
     * market have a higher spread than the global default.
     */
    function ownerSetSpreadPremium(
        uint256 marketId,
        Decimal.D256 memory spreadPremium
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetSpreadPremium(
            g_state,
            marketId,
            spreadPremium
        );
    }

    // ============ Risk Functions ============

    /**
     * Set the global minimum margin-ratio that every position must maintain to prevent being liquidated.
     */
    function ownerSetMarginRatio(
        Decimal.D256 memory ratio
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetMarginRatio(
            g_state,
            ratio
        );
    }

    /**
     * Set the global liquidation spread. This is the spread between oracle prices that incentivizes the liquidation of
     * risky positions.
     */
    function ownerSetLiquidationSpread(
        Decimal.D256 memory spread
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetLiquidationSpread(
            g_state,
            spread
        );
    }

    /**
     * Set the global earnings-rate variable that determines what percentage of the interest paid by borrowers gets
     * passed-on to suppliers.
     */
    function ownerSetEarningsRate(
        Decimal.D256 memory earningsRate
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetEarningsRate(
            g_state,
            earningsRate
        );
    }

    /**
     * Set the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
     */
    function ownerSetMinBorrowedValue(
        Monetary.Value memory minBorrowedValue
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetMinBorrowedValue(
            g_state,
            minBorrowedValue
        );
    }

    // ============ Global Operator Functions ============

    /**
     * Approve (or disapprove) an address that is permissioned to be an operator for all accounts in DolomiteMargin.
     * Intended only to approve smart-contracts.
     */
    function ownerSetGlobalOperator(
        address operator,
        bool approved
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetGlobalOperator(
            g_state,
            operator,
            approved
        );
    }

    /**
     * Approve (or disapprove) an auto trader that can only be called by a global operator. IE for expirations
     */
    function ownerSetAutoTraderSpecial(
        address autoTrader,
        bool special
    )
        public
        onlyOwner
        nonReentrant
    {
        AdminImpl.ownerSetAutoTraderSpecial(
            g_state,
            autoTrader,
            special
        );
    }
}

Settings
{
  "remappings": [],
  "optimizer": {
    "enabled": true,
    "runs": 10000
  },
  "evmVersion": "istanbul",
  "libraries": {
    "/home/cdc218/projects/dolomite-protocol-v2/contracts/protocol/impl/AdminImpl.sol": {
      "AdminImpl": "0xb04CCB2d3850Bf08eCA8a9FF7dB7d018FA17cfC9"
    },
    "/home/cdc218/projects/dolomite-protocol-v2/contracts/protocol/impl/OperationImpl.sol": {
      "OperationImpl": "0x7908b447Ed2050043bb32dAffab0673970124527"
    }
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract ABI

[{"inputs":[{"components":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"marginRatio","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"liquidationSpread","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"earningsRate","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"minBorrowedValue","type":"tuple"},{"internalType":"uint256","name":"accountMaxNumberOfMarketsWithBalances","type":"uint256"}],"internalType":"struct Storage.RiskParams","name":"riskParams","type":"tuple"},{"components":[{"internalType":"uint64","name":"marginRatioMax","type":"uint64"},{"internalType":"uint64","name":"liquidationSpreadMax","type":"uint64"},{"internalType":"uint64","name":"earningsRateMax","type":"uint64"},{"internalType":"uint64","name":"marginPremiumMax","type":"uint64"},{"internalType":"uint64","name":"spreadPremiumMax","type":"uint64"},{"internalType":"uint128","name":"minBorrowedValueMax","type":"uint128"}],"internalType":"struct Storage.RiskLimits","name":"riskLimits","type":"tuple"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"trusted","type":"bool"}],"name":"LogOperatorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAccountBalances","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"address[]","name":"","type":"address[]"},{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint128","name":"value","type":"uint128"}],"internalType":"struct Types.Par[]","name":"","type":"tuple[]"},{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.Wei[]","name":"","type":"tuple[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getAccountMarketWithBalanceAtIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAccountMarketsWithBalances","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAccountMaxNumberOfMarketsWithBalances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAccountNumberOfMarketsWithBalances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAccountNumberOfMarketsWithDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"},{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getAccountPar","outputs":[{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint128","name":"value","type":"uint128"}],"internalType":"struct Types.Par","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"},{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getAccountParNoMarketCheck","outputs":[{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint128","name":"value","type":"uint128"}],"internalType":"struct Types.Par","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAccountStatus","outputs":[{"internalType":"enum Account.Status","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAccountValues","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"},{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getAccountWei","outputs":[{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.Wei","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info","name":"account","type":"tuple"}],"name":"getAdjustedAccountValues","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getEarningsRate","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"autoTrader","type":"address"}],"name":"getIsAutoTraderSpecial","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"getIsGlobalOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"getIsLocalOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getLiquidationSpread","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"heldMarketId","type":"uint256"},{"internalType":"uint256","name":"owedMarketId","type":"uint256"}],"name":"getLiquidationSpreadForPair","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMarginRatio","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarket","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"isClosing","type":"bool"},{"internalType":"bool","name":"isRecyclable","type":"bool"},{"components":[{"internalType":"uint128","name":"borrow","type":"uint128"},{"internalType":"uint128","name":"supply","type":"uint128"}],"internalType":"struct Types.TotalPar","name":"totalPar","type":"tuple"},{"components":[{"internalType":"uint96","name":"borrow","type":"uint96"},{"internalType":"uint96","name":"supply","type":"uint96"},{"internalType":"uint32","name":"lastUpdate","type":"uint32"}],"internalType":"struct Interest.Index","name":"index","type":"tuple"},{"internalType":"contract IPriceOracle","name":"priceOracle","type":"address"},{"internalType":"contract IInterestSetter","name":"interestSetter","type":"address"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"marginPremium","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"spreadPremium","type":"tuple"},{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.Wei","name":"maxWei","type":"tuple"}],"internalType":"struct Storage.Market","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketCachedIndex","outputs":[{"components":[{"internalType":"uint96","name":"borrow","type":"uint96"},{"internalType":"uint96","name":"supply","type":"uint96"},{"internalType":"uint32","name":"lastUpdate","type":"uint32"}],"internalType":"struct Interest.Index","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketCurrentIndex","outputs":[{"components":[{"internalType":"uint96","name":"borrow","type":"uint96"},{"internalType":"uint96","name":"supply","type":"uint96"},{"internalType":"uint32","name":"lastUpdate","type":"uint32"}],"internalType":"struct Interest.Index","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getMarketIdByTokenAddress","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketInterestRate","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Interest.Rate","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketInterestSetter","outputs":[{"internalType":"contract IInterestSetter","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketIsClosing","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketIsRecyclable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketMarginPremium","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketMaxWei","outputs":[{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.Wei","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketPrice","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Price","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketPriceOracle","outputs":[{"internalType":"contract IPriceOracle","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketSpreadPremium","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketTokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketTotalPar","outputs":[{"components":[{"internalType":"uint128","name":"borrow","type":"uint128"},{"internalType":"uint128","name":"supply","type":"uint128"}],"internalType":"struct Types.TotalPar","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getMarketWithInfo","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"isClosing","type":"bool"},{"internalType":"bool","name":"isRecyclable","type":"bool"},{"components":[{"internalType":"uint128","name":"borrow","type":"uint128"},{"internalType":"uint128","name":"supply","type":"uint128"}],"internalType":"struct Types.TotalPar","name":"totalPar","type":"tuple"},{"components":[{"internalType":"uint96","name":"borrow","type":"uint96"},{"internalType":"uint96","name":"supply","type":"uint96"},{"internalType":"uint32","name":"lastUpdate","type":"uint32"}],"internalType":"struct Interest.Index","name":"index","type":"tuple"},{"internalType":"contract IPriceOracle","name":"priceOracle","type":"address"},{"internalType":"contract IInterestSetter","name":"interestSetter","type":"address"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"marginPremium","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"spreadPremium","type":"tuple"},{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.Wei","name":"maxWei","type":"tuple"}],"internalType":"struct Storage.Market","name":"","type":"tuple"},{"components":[{"internalType":"uint96","name":"borrow","type":"uint96"},{"internalType":"uint96","name":"supply","type":"uint96"},{"internalType":"uint32","name":"lastUpdate","type":"uint32"}],"internalType":"struct Interest.Index","name":"","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Price","name":"","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Interest.Rate","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMinBorrowedValue","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"getNumExcessTokens","outputs":[{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.Wei","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getNumMarkets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"n","type":"uint256"}],"name":"getRecyclableMarkets","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getRiskLimits","outputs":[{"components":[{"internalType":"uint64","name":"marginRatioMax","type":"uint64"},{"internalType":"uint64","name":"liquidationSpreadMax","type":"uint64"},{"internalType":"uint64","name":"earningsRateMax","type":"uint64"},{"internalType":"uint64","name":"marginPremiumMax","type":"uint64"},{"internalType":"uint64","name":"spreadPremiumMax","type":"uint64"},{"internalType":"uint128","name":"minBorrowedValueMax","type":"uint128"}],"internalType":"struct Storage.RiskLimits","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getRiskParams","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"marginRatio","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"liquidationSpread","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"earningsRate","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"minBorrowedValue","type":"tuple"},{"internalType":"uint256","name":"accountMaxNumberOfMarketsWithBalances","type":"uint256"}],"internalType":"struct Storage.RiskParams","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct Account.Info[]","name":"accounts","type":"tuple[]"},{"components":[{"internalType":"enum Actions.ActionType","name":"actionType","type":"uint8"},{"internalType":"uint256","name":"accountId","type":"uint256"},{"components":[{"internalType":"bool","name":"sign","type":"bool"},{"internalType":"enum Types.AssetDenomination","name":"denomination","type":"uint8"},{"internalType":"enum Types.AssetReference","name":"ref","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Types.AssetAmount","name":"amount","type":"tuple"},{"internalType":"uint256","name":"primaryMarketId","type":"uint256"},{"internalType":"uint256","name":"secondaryMarketId","type":"uint256"},{"internalType":"address","name":"otherAddress","type":"address"},{"internalType":"uint256","name":"otherAccountId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct Actions.ActionArgs[]","name":"actions","type":"tuple[]"}],"name":"operate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"contract IPriceOracle","name":"priceOracle","type":"address"},{"internalType":"contract IInterestSetter","name":"interestSetter","type":"address"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"marginPremium","type":"tuple"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"spreadPremium","type":"tuple"},{"internalType":"uint256","name":"maxWei","type":"uint256"},{"internalType":"bool","name":"isClosing","type":"bool"},{"internalType":"bool","name":"isRecyclable","type":"bool"}],"name":"ownerAddMarket","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256[]","name":"marketIds","type":"uint256[]"},{"internalType":"address","name":"salvager","type":"address"}],"name":"ownerRemoveMarkets","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"accountMaxNumberOfMarketsWithBalances","type":"uint256"}],"name":"ownerSetAccountMaxNumberOfMarketsWithBalances","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"autoTrader","type":"address"},{"internalType":"bool","name":"special","type":"bool"}],"name":"ownerSetAutoTraderSpecial","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"earningsRate","type":"tuple"}],"name":"ownerSetEarningsRate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"ownerSetGlobalOperator","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"contract IInterestSetter","name":"interestSetter","type":"address"}],"name":"ownerSetInterestSetter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"bool","name":"isClosing","type":"bool"}],"name":"ownerSetIsClosing","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"spread","type":"tuple"}],"name":"ownerSetLiquidationSpread","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"marginPremium","type":"tuple"}],"name":"ownerSetMarginPremium","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"ratio","type":"tuple"}],"name":"ownerSetMarginRatio","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"uint256","name":"maxWei","type":"uint256"}],"name":"ownerSetMaxWei","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Value","name":"minBorrowedValue","type":"tuple"}],"name":"ownerSetMinBorrowedValue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"contract IPriceOracle","name":"priceOracle","type":"address"}],"name":"ownerSetPriceOracle","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Decimal.D256","name":"spreadPremium","type":"tuple"}],"name":"ownerSetSpreadPremium","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"ownerWithdrawExcessTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"recipient","type":"address"}],"name":"ownerWithdrawUnsupportedTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"trusted","type":"bool"}],"internalType":"struct Types.OperatorArg[]","name":"args","type":"tuple[]"}],"name":"setOperators","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]

6080604052664765747465727360c81b6010553480156200001f57600080fd5b5060405162005e2c38038062005e2c833981016040819052620000429162000342565b6000620000576001600160e01b03620001a316565b600f80546001600160a01b0319166001600160a01b038316908117909155604051919250906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a350600f8054600160a01b60ff60a01b199091161790558151516008556020808301515160095560408084015151600a5560608085015151600b55608094850151600c558351600d80549486015193860151928601516001600160401b03199586166001600160401b0393841617600160401b600160801b03191668010000000000000000958416860217600160801b600160c01b031916600160801b94841694909402939093176001600160c01b0316600160c01b938316939093029290921790915593830151600e805460a09095015194909316941693909317600160401b600160c01b0319166001600160801b03909216909202179055620003f4565b3390565b600060208284031215620001ba57600080fd5b620001c6602062000382565b90506000620001d6848462000328565b82525092915050565b600060c08284031215620001f257600080fd5b620001fe60c062000382565b905060006200020e848462000335565b8252506020620002218484830162000335565b6020830152506040620002378482850162000335565b60408301525060606200024d8482850162000335565b6060830152506080620002638482850162000335565b60808301525060a0620002798482850162000315565b60a08301525092915050565b600060a082840312156200029857600080fd5b620002a460a062000382565b90506000620002b48484620001a7565b8252506020620002c784848301620001a7565b6020830152506040620002dd84828501620001a7565b6040830152506060620002f384828501620001a7565b6060830152506080620003098482850162000328565b60808301525092915050565b80516200032281620003c4565b92915050565b80516200032281620003de565b80516200032281620003e9565b60008061016083850312156200035757600080fd5b600062000365858562000285565b92505060a06200037885828601620001df565b9150509250929050565b6040518181016001600160401b0381118282101715620003a157600080fd5b604052919050565b6001600160801b031690565b90565b6001600160401b031690565b620003cf81620003a9565b8114620003db57600080fd5b50565b620003cf81620003b5565b620003cf81620003b8565b615a2880620004046000396000f3fe608060405234801561001057600080fd5b50600436106103d05760003560e01c80638da5cb5b116101ff578063d93c95911161011a578063ec6e3987116100ad578063f2fde38b1161007c578063f2fde38b146108bf578063f9416052146108d2578063fd04b606146108e5578063fd47eda6146108f8576103d0565b8063ec6e398714610873578063ef6957d014610886578063f1061ba814610899578063f2901ae2146108ac576103d0565b8063e5520228116100e9578063e552022814610823578063e8e72f751461082b578063eb1c6e6b1461083e578063eb44fdd314610853576103d0565b8063d93c9591146107ca578063deec053d146107dd578063e0e48d19146107f0578063e51bfcb414610803576103d0565b8063c0e044fc11610192578063cb04a34c11610161578063cb04a34c14610771578063d24c48bc14610791578063d36cca90146107a4578063d5ecf7c5146107b7576103d0565b8063c0e044fc1461072e578063c146094214610736578063c190c2ec1461073e578063c8e188261461075e576103d0565b806397bcdfb9116101ce57806397bcdfb9146106d2578063a67a6a45146106e5578063b548b892146106f8578063c0bb72b71461071b576103d0565b80638da5cb5b1461069c5780638f32d59b146106a45780638f6bc659146106ac5780638fae3be1146106bf576103d0565b80633063bce2116102ef5780635735a43011610282578063715018a611610251578063715018a6146106665780637e9eaf411461066e57806385b53fc8146106765780638928378e14610689576103d0565b80635735a430146106085780635ac7d17c1461061b578063697947951461062e5780636a8194e714610643576103d0565b80634be87414116102be5780634be87414146105ba5780634f3c1542146105cd5780634f4d66f6146105d557806356ea84b2146105e8576103d0565b80633063bce214610561578063387a498a146105745780633a031bf01461058757806347d1b53c1461059a576103d0565b8063124f914c116103675780631a7777bb116103365780631a7777bb14610513578063295c39a5146105335780632a5608451461053b5780632e822af31461054e576103d0565b8063124f914c1461049f57806313368364146104c057806317b50525146104e0578063197f0f0514610500576103d0565b80630781d820116103a35780630781d820146104535780630cd30a0e146104665780630f47fab014610479578063121fb72f1461048c576103d0565b80630339a0c4146103d5578063042069d6146103fe578063052f72d714610413578063062bd3e914610433575b600080fd5b6103e86103e3366004614923565b61090b565b6040516103f591906153cf565b60405180910390f35b61041161040c3660046149cd565b6109e0565b005b610426610421366004614697565b610adf565b6040516103f5919061542d565b610446610441366004614923565b610af7565b6040516103f5919061537e565b610411610461366004614923565b610b13565b6104116104743660046149fd565b610c06565b6103e86104873660046148b7565b610cb5565b61041161049a36600461499d565b610cc8565b6104b26104ad3660046148b7565b610d77565b6040516103f5929190615757565b6104d36104ce366004614923565b610d9b565b6040516103f5919061543b565b6104f36104ee3660046148b7565b610dd2565b6040516103f59190615773565b6104d361050e366004614923565b610de4565b610526610521366004614923565b610e1b565b6040516103f591906154b8565b6104f3610e52565b6104f36105493660046146b5565b610e58565b61041161055c366004614899565b610f74565b61041161056f366004614899565b611021565b610411610582366004614899565b6110ce565b6104266105953660046146b5565b61117b565b6105ad6105a83660046148d5565b611195565b6040516103f5919061551c565b6104116105c83660046149cd565b6111b8565b610526611267565b6104f36105e33660046148b7565b611283565b6105fb6105f6366004614923565b611295565b6040516103f591906154c6565b610426610616366004614923565b6112ca565b610426610629366004614923565b611304565b61063661132c565b6040516103f59190615538565b6106566106513660046148b7565b611390565b6040516103f594939291906153e0565b610411611547565b6105266115da565b61041161068436600461482e565b6115f6565b610526610697366004614923565b6116dd565b610446611712565b61042661172e565b6104f36106ba36600461495f565b61176e565b6104f36106cd366004614697565b61181f565b6104116106e036600461471f565b611853565b6104116106f33660046147cf565b61195b565b61070b610706366004614923565b6119e6565b6040516103f594939291906154e3565b610411610729366004614899565b611a42565b6104f3611aef565b610526611af5565b61075161074c3660046148d5565b611b11565b6040516103f59190615765565b6105ad61076c3660046148d5565b611b51565b61078461077f366004614923565b611b59565b6040516103f59190615749565b61052661079f3660046149fd565b611b7b565b6104116107b2366004614863565b611ba7565b6107516107c5366004614923565b611c56565b6107516107d8366004614923565b611c78565b6105fb6107eb366004614923565b611cbb565b6104f36107fe3660046148d5565b611cdd565b6108166108113660046148b7565b611cf0565b6040516103f59190615449565b610526611d02565b61041161083936600461499d565b611d1e565b610846611dcd565b6040516103f5919061552a565b610866610861366004614923565b611e6f565b6040516103f591906154d4565b6104116108813660046146ef565b611ff9565b61041161089436600461497e565b6120a8565b6104266108a7366004614697565b612157565b6104116108ba3660046146ef565b612169565b6104116108cd366004614697565b612218565b6104b26108e03660046148b7565b612248565b6105266108f3366004614923565b612263565b610526610906366004614923565b61229a565b6060600080905060608360405190808252806020026020018201604052801561093e578160200160208202803883390190505b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60005260036020527fb1ee3b3d0d99532dd9f14b22c0b908d4eec0e052c3827bbed2d6c3986954d08c549091505b801580159061099c57508483105b156109d657808284806001019550815181106109b457fe5b602090810291909101810191909152600091825260039052604090205461098e565b509150505b919050565b6109e861172e565b610a0d5760405162461bcd60e51b8152600401610a0490615498565b60405180910390fd5b600f54600160a01b900460ff16610a365760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f8854ab3e00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990638854ab3e90610a989060009086908690600401615713565b60006040518083038186803b158015610ab057600080fd5b505af4158015610ac4573d6000803e3d6000fd5b5050600f805460ff60a01b1916600160a01b17905550505050565b6000610af1818363ffffffff6122cf16565b92915050565b6000610b02826122fe565b610af160008363ffffffff61235f16565b610b1b61172e565b610b375760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610b605760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f70b6151c00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc9906370b6151c90610bc090600090859060040161569a565b60006040518083038186803b158015610bd857600080fd5b505af4158015610bec573d6000803e3d6000fd5b5050600f805460ff60a01b1916600160a01b179055505050565b610c0e61172e565b610c2a5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610c535760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f5eeabe3900000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990635eeabe3990610a98906000908690869060040161573b565b6060610af160008363ffffffff61238b16565b610cd061172e565b610cec5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610d155760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517faa92e34800000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063aa92e34890610a9890600090869086906004016156eb565b610d7f614075565b610d87614075565b610d928360006123d0565b91509150915091565b6000610da6826122fe565b5060009081526001602052604090206003015473ffffffffffffffffffffffffffffffffffffffff1690565b6000610af1818363ffffffff61247516565b6000610def826122fe565b5060009081526001602052604090206004015473ffffffffffffffffffffffffffffffffffffffff1690565b610e23614075565b610e2c826122fe565b506000908152600160209081526040918290208251918201909252600690910154815290565b60005490565b6000610e6261172e565b610e7e5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610ea75760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fdd32998a00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063dd32998a90610f099060009087908790600401615546565b60206040518083038186803b158015610f2157600080fd5b505af4158015610f35573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610f599190810190614941565b9050600f805460ff60a01b1916600160a01b17905592915050565b610f7c61172e565b610f985760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610fc15760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517ff9cacc4c00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063f9cacc4c90610bc090600090859060040161567f565b61102961172e565b6110455760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff1661106e5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f0f44e6bc00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990630f44e6bc90610bc090600090859060040161567f565b6110d661172e565b6110f25760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff1661111b5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f311401d000000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063311401d090610bc090600090859060040161567f565b600061118e81848463ffffffff6124bc16565b9392505050565b61119d614088565b6111a6826122fe565b61118e6000848463ffffffff6124f916565b6111c061172e565b6111dc5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166112055760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f7335079b00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990637335079b90610a989060009086908690600401615713565b61126f614075565b506040805160208101909152600854815290565b6000610af1818363ffffffff61257816565b61129d61409f565b6112a6826122fe565b610af1826112bb60008263ffffffff6125ba16565b6000919063ffffffff61263e16565b60006112d5826122fe565b506000908152600160205260409020547501000000000000000000000000000000000000000000900460ff1690565b600061130f826122fe565b50600090815260016020526040902054600160a01b900460ff1690565b6113346140bf565b506040805160c08101825260085460a08201908152815281516020818101845260095482528083019190915282518082018452600a548152828401528251908101909252600b5482526060810191909152600c54608082015290565b6060808080806113a760008763ffffffff61238b16565b9050606081516040519080825280602002602001820160405280156113d6578160200160208202803883390190505b5090506060825160405190808252806020026020018201604052801561141657816020015b611403614088565b8152602001906001900390816113fb5790505b5090506060835160405190808252806020026020018201604052801561145657816020015b611443614088565b81526020019060019003908161143b5790505b50905060005b84518110156115375761148185828151811061147457fe5b6020026020010151610af7565b84828151811061148d57fe5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250506114e48a8683815181106114d757fe5b6020026020010151611195565b8382815181106114f057fe5b60200260200101819052506115188a86838151811061150b57fe5b6020026020010151611b11565b82828151811061152457fe5b602090810291909101015260010161145c565b5092989197509550909350915050565b61154f61172e565b61156b5760405162461bcd60e51b8152600401610a0490615498565b600f5460405160009173ffffffffffffffffffffffffffffffffffffffff16907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600f80547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b6115e2614075565b506040805160208101909152600b54815290565b60005b81518110156116d957600082828151811061161057fe5b6020026020010151600001519050600083838151811061162c57fe5b60209081029190910181015181015133600081815260058452604080822073ffffffffffffffffffffffffffffffffffffffff8816835290945283902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001683151517905591519092507f4d7f317d2088d039c2a95a09fcbf9cc9191fad5905f883c937cc3d317c4a6327906116c7908590859061538c565b60405180910390a250506001016115f9565b5050565b6116e5614075565b6116ee826122fe565b610af18261170360008263ffffffff61235f16565b6000919063ffffffff61269616565b600f5473ffffffffffffffffffffffffffffffffffffffff1690565b600f5460009073ffffffffffffffffffffffffffffffffffffffff166117526127c5565b73ffffffffffffffffffffffffffffffffffffffff1614905090565b600061177861172e565b6117945760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166117bd5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fb25328e000000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063b25328e090610f0990600090879087906004016156b5565b600061182a826127c9565b5073ffffffffffffffffffffffffffffffffffffffff1660009081526002602052604090205490565b61185b61172e565b6118775760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166118a05760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f526ebb2700000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063526ebb279061190e906000908c908c908c908c908c908c908c908c90600401615596565b60006040518083038186803b15801561192657600080fd5b505af415801561193a573d6000803e3d6000fd5b5050600f805460ff60a01b1916600160a01b17905550505050505050505050565b600f54600160a01b900460ff166119845760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fbd76ecfd000000000000000000000000000000000000000000000000000000008152737908b447ed2050043bb32daffab06739701245279063bd76ecfd90610a98906000908690869060040161561c565b6119ee614106565b6119f661409f565b6119fe614075565b611a06614075565b611a0f856122fe565b611a1885611e6f565b611a2186611295565b611a2a876116dd565b611a338861229a565b93509350935093509193509193565b611a4a61172e565b611a665760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16611a8f5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f54dd351600000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc9906354dd351690610bc090600090859060040161567f565b600c5490565b611afd614075565b506040805160208101909152600954815290565b611b19614088565b611b22826122fe565b61118e611b376000858563ffffffff6124f916565b611b4c846112bb60008263ffffffff6125ba16565b612832565b6111a6614088565b611b61614088565b611b6a826122fe565b610af160008363ffffffff6128e316565b611b83614075565b611b8c836122fe565b611b95826122fe565b61118e6000848463ffffffff61294316565b611baf61172e565b611bcb5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16611bf45760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fd963729100000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063d963729190610a989060009086908690600401615650565b611c5e614088565b611c67826122fe565b610af160008363ffffffff6129da16565b611c80614088565b611c89826122fe565b506000908152600160209081526040918290208251808401909352600781015460ff1615158352600801549082015290565b611cc361409f565b611ccc826122fe565b610af160008363ffffffff6125ba16565b600061118e81848463ffffffff612b3516565b6000610af1818363ffffffff612b8616565b611d0a614075565b506040805160208101909152600a54815290565b611d2661172e565b611d425760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16611d6b5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f8c5dabd100000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990638c5dabd190610a9890600090869086906004016156eb565b611dd5614177565b506040805160c081018252600d5467ffffffffffffffff808216835268010000000000000000808304821660208501527001000000000000000000000000000000008304821694840194909452780100000000000000000000000000000000000000000000000090910481166060830152600e549081166080830152919091046fffffffffffffffffffffffffffffffff1660a082015290565b611e77614106565b611e80826122fe565b50600090815260016020818152604092839020835161014081018552815473ffffffffffffffffffffffffffffffffffffffff8082168352600160a01b820460ff9081161515848701527501000000000000000000000000000000000000000000909204821615158388015286518088018852958401546fffffffffffffffffffffffffffffffff808216885270010000000000000000000000000000000090910416868601526060808401969096528651958601875260028401546bffffffffffffffffffffffff80821688526c01000000000000000000000000820416878701527801000000000000000000000000000000000000000000000000900463ffffffff168688015260808301959095526003830154851660a0830152600483015490941660c0820152845180840186526005830154815260e082015284518084018652600683015481526101008201528451808601909552600782015490931615158452600801549083015261012081019190915290565b61200161172e565b61201d5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166120465760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f3c0c9ddc00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990633c0c9ddc90610a98906000908690869060040161556e565b6120b061172e565b6120cc5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166120f55760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f10c87b0600000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc9906310c87b0690610a9890600090869086906004016156d0565b6000610af1818363ffffffff612bc516565b61217161172e565b61218d5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166121b65760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fe80f802400000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063e80f802490610a98906000908690869060040161556e565b61222061172e565b61223c5760405162461bcd60e51b8152600401610a0490615498565b61224581612bf4565b50565b612250614075565b612258614075565b610d928360016123d0565b61226b614075565b612274826122fe565b506000908152600160209081526040918290208251918201909252600590910154815290565b6122a2614075565b6122ab826122fe565b610af1826122c060008263ffffffff6125ba16565b6000919063ffffffff612cb516565b73ffffffffffffffffffffffffffffffffffffffff166000908152600691909101602052604090205460ff1690565b6000546122459082108015612336575060008281526001602052604090205473ffffffffffffffffffffffffffffffffffffffff1615155b6010547f496e76616c6964206d61726b6574000000000000000000000000000000000000612dc0565b6000908152600191909101602052604090205473ffffffffffffffffffffffffffffffffffffffff1690565b805173ffffffffffffffffffffffffffffffffffffffff1660009081526004830160209081526040808320828501518452909152902060609061118e90600101612e53565b6123d8614075565b6123e0614075565b60606123f360008663ffffffff61238b16565b90506123fd6141ac565b6124078251612eaf565b905060005b82518110156124435761243b83828151811061242457fe5b602002602001015183612f0e90919063ffffffff16565b60010161240c565b5061245560008263ffffffff612f7816565b612468600087838863ffffffff61317a16565b9350935050509250929050565b805173ffffffffffffffffffffffffffffffffffffffff16600090815260049290920160209081526040808420928201518452919052902054610100900463ffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff9182166000908152600593909301602090815260408085209290931684525290205460ff1690565b612501614088565b50815173ffffffffffffffffffffffffffffffffffffffff1660009081526004840160209081526040808320828601518452825280832084845260030182529182902082518084019093525460ff8116151583526fffffffffffffffffffffffffffffffff61010090910416908201529392505050565b805173ffffffffffffffffffffffffffffffffffffffff1660009081526004830160209081526040808320828501518452909152812061118e906001016132f2565b6125c261409f565b506000908152600191909101602090815260409182902082516060810184526002909101546bffffffffffffffffffffffff80821683526c0100000000000000000000000082041692820192909252780100000000000000000000000000000000000000000000000090910463ffffffff169181019190915290565b61264661409f565b61264e614075565b61265f85858563ffffffff612cb516565b905061268d8382612676888863ffffffff6128e316565b6040805160208101909152600a8a015481526132f6565b95945050505050565b61269e614075565b600083815260018501602052604090206003015473ffffffffffffffffffffffffffffffffffffffff166126d0614075565b6040517f41976e0900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8316906341976e099061272290879060040161537e565b60206040518083038186803b15801561273a57600080fd5b505afa15801561274e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506127729190810190614905565b805190915061268d9015157f53746f72616765000000000000000000000000000000000000000000000000007f50726963652063616e6e6f74206265207a65726f00000000000000000000000088613460565b3390565b73ffffffffffffffffffffffffffffffffffffffff808216600081815260026020908152604080832054835260019091529020546010546122459391909116909114907f496e76616c696420746f6b656e00000000000000000000000000000000000000612dc0565b61283a614088565b602083015183516fffffffffffffffffffffffffffffffff90911690156128a65760408051808201909152600181526020848101519082019061289b9084906bffffffffffffffffffffffff16670de0b6b3a764000063ffffffff6134fe16565b815250915050610af1565b60408051808201909152600081528351602082019061289b9084906bffffffffffffffffffffffff16670de0b6b3a764000063ffffffff6134fe16565b6128eb614088565b506000818152600180840160209081526040928390208351808501909452909101546fffffffffffffffffffffffffffffffff8082168452700100000000000000000000000000000000909104169082015292915050565b61294b614075565b600984015460008481526001860160209081526040918290208251918201909252600690910154815261298890829061298390613592565b6135c9565b90506129c381612983876001016000878152602001908152602001600020600601604051806020016040529081600082015481525050613592565b604080516020810190915290815295945050505050565b6129e2614088565b6129ea61409f565b6129fa848463ffffffff6125ba16565b9050612a04614088565b612a14858563ffffffff6128e316565b90506000612a28868663ffffffff61235f16565b9050612a32614088565b6040805180820182526001815290517f70a08231000000000000000000000000000000000000000000000000000000008152602082019073ffffffffffffffffffffffffffffffffffffffff8516906370a0823190612a9590309060040161537e565b60206040518083038186803b158015612aad57600080fd5b505afa158015612ac1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612ae59190810190614941565b90529050612af1614088565b612af9614088565b612b0385876135e2565b9092509050612b2882612b1c858463ffffffff61368a16565b9063ffffffff61368a16565b9998505050505050505050565b815173ffffffffffffffffffffffffffffffffffffffff16600090815260048401602090815260408083208286015184529091528120612b7e906001018363ffffffff6136a416565b949350505050565b805173ffffffffffffffffffffffffffffffffffffffff1660009081526004929092016020908152604080842092820151845291905290205460ff1690565b73ffffffffffffffffffffffffffffffffffffffff166000908152600791909101602052604090205460ff1690565b73ffffffffffffffffffffffffffffffffffffffff8116612c275760405162461bcd60e51b8152600401610a0490615468565b600f5460405173ffffffffffffffffffffffffffffffffffffffff8084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3600f80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b612cbd614075565b612cc5614088565b612cd5858563ffffffff6128e316565b9050612cdf614088565b612ce7614088565b612cf183866135e2565b91509150612cfd614075565b600087815260018901602052604090206004015473ffffffffffffffffffffffffffffffffffffffff1663e8177dcf612d3c8a8a63ffffffff61235f16565b846020015186602001516040518463ffffffff1660e01b8152600401612d64939291906153a7565b60206040518083038186803b158015612d7c57600080fd5b505afa158015612d90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612db49190810190614905565b98975050505050505050565b82612e4e57612dce826136c8565b7f3a20000000000000000000000000000000000000000000000000000000000000612df8836136c8565b604051602001612e0a9392919061527c565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529082905262461bcd60e51b8252610a0491600401615457565b505050565b606081600001805480602002602001604051908101604052809291908181526020018280548015612ea357602002820191906000526020600020905b815481526020019060010190808311612e8f575b50505050509050919050565b612eb76141ac565b604080516000606082018181526080830190935290918291612eef565b612edc6141cd565b815260200190600190039081612ed45790505b508152602001612efe8461379c565b8152600060209091015292915050565b815151612f5d90157f43616368650000000000000000000000000000000000000000000000000000007f616c726561647920696e697469616c697a656400000000000000000000000000612dc0565b612f6b8260200151826137d6565b5060400180516001019052565b8060400151604051908082528060200260200182016040528015612fb657816020015b612fa36141cd565b815260200190600190039081612f9b5790505b5081526000805b82602001515181101561312057600083602001518281518110612fdc57fe5b602002602001015190505b8015613105576000612ff88261380c565b9050600061300684836139e3565b9050600061301a888363ffffffff61235f16565b9050613024614088565b613034898463ffffffff6128e316565b6040805160e08101825285815273ffffffffffffffffffffffffffffffffffffffff8516602080830191909152600087815260018e01825283902054600160a01b900460ff1615159282019290925282516fffffffffffffffffffffffffffffffff908116606083015291830151909116608082015290915060a081016130bb8b866125ba565b81526020016130d18b868663ffffffff61269616565b90528851805160018a01999081106130e557fe5b60200260200101819052506130fa85856139ee565b945050505050612fe7565b83604001518314156131175750613120565b50600101612fbd565b506040820151825151612e4e91808414917f53746f7261676500000000000000000000000000000000000000000000000000917f636163686520696e697469616c697a656420696d70726f7065726c7900000000916139f7565b613182614075565b61318a614075565b613192614075565b61319a614075565b60006131a587613ac2565b905060005b818110156132e3576131ba614088565b6131f28a6131ce8b8563ffffffff613ac716565b516131df8c8663ffffffff613ac716565b60a001518e92919063ffffffff613b4316565b90506131fd81613b98565b1561320857506132db565b600061323361321d8b8563ffffffff613ac716565b60c001515160208401519063ffffffff613ba016565b905061323d614075565b613245613bda565b905089156132905761328d60018e0160006132668e8863ffffffff613ac716565b51815260208082019290925260409081016000208151928301909152600501548152613592565b90505b8251156132b9576132b26132a48383613bfc565b88519063ffffffff613c1516565b87526132d7565b6132d46132c683836135c9565b87519063ffffffff613c1516565b86525b5050505b6001016131aa565b50919890975095505050505050565b5490565b6132fe61409f565b613306614088565b61330e614088565b61331885886135e2565b915091506000613326613c3a565b9050600061335e6133508a6040015163ffffffff168463ffffffff16613c4a90919063ffffffff16565b89519063ffffffff613ba016565b9050600061336b85613b98565b15613378575060006133aa565b61338282886135c9565b90508460200151846020015110156133aa576133a78185602001518760200151613c8c565b90505b818111156133b457fe5b60408051606081019091528a5181906133fd906133f8906bffffffffffffffffffffffff166133ec8188670de0b6b3a7640000613c8c565b9063ffffffff613c1516565b613ca2565b6bffffffffffffffffffffffff908116825260208d810151920191613434916133f891166133ec8187670de0b6b3a7640000613c8c565b6bffffffffffffffffffffffff1681526020018463ffffffff1681525095505050505050949350505050565b836134f85761346e836136c8565b7f3a20000000000000000000000000000000000000000000000000000000000000613498846136c8565b7f203c0000000000000000000000000000000000000000000000000000000000006134c285613d01565b604051612e0a9594939291907f3e00000000000000000000000000000000000000000000000000000000000000906020016152a4565b50505050565b600083158061350b575082155b156135225761351b600083613e10565b905061118e565b6000613534858563ffffffff613ba016565b905061268d61355f60016133ec6002613553888463ffffffff613c4a16565b9063ffffffff613e1016565b61356f838663ffffffff613e5216565b101561357c57600061357f565b60015b60ff166133ec838663ffffffff613e1016565b61359a614075565b6040805160208101909152825181906135c190670de0b6b3a764000063ffffffff613c1516565b905292915050565b600061118e838360000151670de0b6b3a7640000613c8c565b6135ea614088565b6135f2614088565b6135fa614088565b5060408051808201909152600181526020858101516fffffffffffffffffffffffffffffffff169082015261362d614088565b50604080518082019091526000815285516fffffffffffffffffffffffffffffffff16602082015261365d614088565b6136678387612832565b9050613671614088565b61367b8388612832565b91989197509095505050505050565b613692614088565b61118e8361369f84613e94565b613ebb565b60008260000182815481106136b557fe5b9060005260206000200154905092915050565b606080826040516020016136dc9190615267565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152919052905060205b80156137855781517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9091019082908290811061374857fe5b01602001517fff00000000000000000000000000000000000000000000000000000000000000161561378057600101815290506109db565b61370f565b505060408051600081526020810190915292915050565b606060016101008304016040519080825280602002602001820160405280156137cf578160200160208202803883390190505b5092915050565b815161010082049060ff8316906001821b908590849081106137f457fe5b60200260200101818151179150818152505050505050565b600060ff6fffffffffffffffffffffffffffffffff83161561384f577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8001613857565b608083901c92505b67ffffffffffffffff83161561388e577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc001613896565b604083901c92505b63ffffffff8316156138c9577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0016138d1565b602083901c92505b61ffff831615613902577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00161390a565b601083901c92505b60ff83161561393a577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff801613942565b600883901c92505b600f831615613972577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc0161397a565b600483901c92505b60038316156139aa577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016139b2565b600283901c92505b6001831615610af1577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0192915050565b610100919091020190565b6001901b900390565b84613abb57613a05846136c8565b7f3a20000000000000000000000000000000000000000000000000000000000000613a2f856136c8565b7f203c000000000000000000000000000000000000000000000000000000000000613a5986613d01565b7f2c20000000000000000000000000000000000000000000000000000000000000613a8387613d01565b604051612e0a97969594939291907f3e0000000000000000000000000000000000000000000000000000000000000090602001615302565b5050505050565b515190565b613acf6141cd565b825151613b2590808410907f4361636865000000000000000000000000000000000000000000000000000000907f696e76616c696420696e646578000000000000000000000000000000000000009086906139f7565b8251805183908110613b3357fe5b6020026020010151905092915050565b613b4b614088565b613b53614088565b613b6486868663ffffffff6124f916565b9050613b6f81613f4d565b15613b8457613b7c613f67565b915050612b7e565b613b8e8184612832565b9695505050505050565b602001511590565b600082613baf57506000610af1565b82820282848281613bbc57fe5b041461118e5760405162461bcd60e51b8152600401610a0490615488565b613be2614075565b506040805160208101909152670de0b6b3a7640000815290565b600061118e83670de0b6b3a76400008460000151613c8c565b60008282018381101561118e5760405162461bcd60e51b8152600401610a0490615478565b6000613c4542613f87565b905090565b600061118e83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613fde565b6000612b7e82613553868663ffffffff613ba016565b600081610af16bffffffffffffffffffffffff821682147f4d617468000000000000000000000000000000000000000000000000000000007f556e73616665206361737420746f2075696e743936000000000000000000000084613460565b606081613d42575060408051808201909152600181527f300000000000000000000000000000000000000000000000000000000000000060208201526109db565b8160005b8115613d5a57600101600a82049150613d46565b6060816040519080825280601f01601f191660200182016040528015613d87576020820181803883390190505b508593509050815b8015613e07577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600a840660300160f81b828281518110613dcd57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84049350613d8f565b50949350505050565b600061118e83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061400a565b600061118e83836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f0000000000000000815250614041565b613e9c614088565b5060408051808201909152815115815260208083015190820152919050565b613ec3614088565b613ecb614088565b8251845115159015151415613efe5783511515815260208085015190840151613ef49190613c15565b602082015261118e565b8260200151846020015110613f275783511515815260208085015190840151613ef49190613c4a565b82511515815260208084015190850151613f419190613c4a565b60208201529392505050565b602001516fffffffffffffffffffffffffffffffff161590565b613f6f614088565b50604080518082019091526000808252602082015290565b600081610af163ffffffff821682147f4d617468000000000000000000000000000000000000000000000000000000007f556e73616665206361737420746f2075696e743332000000000000000000000084613460565b600081848411156140025760405162461bcd60e51b8152600401610a049190615457565b505050900390565b6000818361402b5760405162461bcd60e51b8152600401610a049190615457565b50600083858161403757fe5b0495945050505050565b600081836140625760405162461bcd60e51b8152600401610a049190615457565b5082848161406c57fe5b06949350505050565b6040518060200160405280600081525090565b604080518082019091526000808252602082015290565b604080516060810182526000808252602082018190529181019190915290565b6040518060a001604052806140d2614075565b81526020016140df614075565b81526020016140ec614075565b81526020016140f9614075565b8152602001600081525090565b60408051610140810182526000808252602082018190529181019190915260608101614130614088565b815260200161413d61409f565b81526000602082018190526040820152606001614158614075565b8152602001614165614075565b8152602001614172614088565b905290565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b60405180606001604052806060815260200160608152602001600081525090565b6040805160e08101825260008082526020820181905291810182905260608101829052608081019190915260a0810161420461409f565b8152602001614172614075565b8035610af18161599c565b600082601f83011261422d57600080fd5b813561424061423b826157a8565b615781565b81815260209384019390925082018360005b8381101561427e57813586016142688882614457565b8452506020928301929190910190600101614252565b5050505092915050565b600082601f83011261429957600080fd5b81356142a761423b826157a8565b915081818352602084019350602081019050838560408402820111156142cc57600080fd5b60005b8381101561427e57816142e288826145d5565b845250602090920191604091909101906001016142cf565b600082601f83011261430b57600080fd5b813561431961423b826157a8565b9150818183526020840193506020810190508385604084028201111561433e57600080fd5b60005b8381101561427e5781614354888261461c565b84525060209092019160409190910190600101614341565b600082601f83011261437d57600080fd5b813561438b61423b826157a8565b915081818352602084019350602081019050838560208402820111156143b057600080fd5b60005b8381101561427e57816143c68882614681565b84525060209283019291909101906001016143b3565b8035610af1816159b0565b600082601f8301126143f857600080fd5b813561440661423b826157c9565b9150808252602083016020830185838301111561442257600080fd5b61442d83828461591e565b50505092915050565b8035610af1816159b9565b8035610af1816159c2565b8035610af1816159cf565b6000610160828403121561446a57600080fd5b614475610100615781565b905060006144838484614441565b825250602061449484848301614681565b60208301525060406144a884828501614533565b60408301525060c06144bc84828501614681565b60608301525060e06144d084828501614681565b6080830152506101006144e584828501614211565b60a0830152506101206144fa84828501614681565b60c08301525061014082013567ffffffffffffffff81111561451b57600080fd5b614527848285016143e7565b60e08301525092915050565b60006080828403121561454557600080fd5b61454f6080615781565b9050600061455d84846143dc565b825250602061456e8484830161444c565b60208301525060406145828482850161444c565b604083015250606061459684828501614681565b60608301525092915050565b6000602082840312156145b457600080fd5b6145be6020615781565b905060006145cc8484614681565b82525092915050565b6000604082840312156145e757600080fd5b6145f16040615781565b905060006145ff8484614211565b825250602061461084848301614681565b60208301525092915050565b60006040828403121561462e57600080fd5b6146386040615781565b905060006146468484614211565b8252506020614610848483016143dc565b60006020828403121561466957600080fd5b6146736020615781565b905060006145cc848461468c565b8035610af1816159dc565b8051610af1816159dc565b6000602082840312156146a957600080fd5b6000612b7e8484614211565b600080604083850312156146c857600080fd5b60006146d48585614211565b92505060206146e585828601614211565b9150509250929050565b6000806040838503121561470257600080fd5b600061470e8585614211565b92505060206146e5858286016143dc565b600080600080600080600080610100898b03121561473c57600080fd5b60006147488b8b614211565b98505060206147598b828c01614436565b975050604061476a8b828c01614436565b965050606061477b8b828c016145a2565b955050608061478c8b828c016145a2565b94505060a061479d8b828c01614681565b93505060c06147ae8b828c016143dc565b92505060e06147bf8b828c016143dc565b9150509295985092959890939650565b600080604083850312156147e257600080fd5b823567ffffffffffffffff8111156147f957600080fd5b61480585828601614288565b925050602083013567ffffffffffffffff81111561482257600080fd5b6146e58582860161421c565b60006020828403121561484057600080fd5b813567ffffffffffffffff81111561485757600080fd5b612b7e848285016142fa565b6000806040838503121561487657600080fd5b823567ffffffffffffffff81111561488d57600080fd5b6146d48582860161436c565b6000602082840312156148ab57600080fd5b6000612b7e84846145a2565b6000604082840312156148c957600080fd5b6000612b7e84846145d5565b600080606083850312156148e857600080fd5b60006148f485856145d5565b92505060406146e585828601614681565b60006020828403121561491757600080fd5b6000612b7e8484614657565b60006020828403121561493557600080fd5b6000612b7e8484614681565b60006020828403121561495357600080fd5b6000612b7e848461468c565b6000806040838503121561497257600080fd5b60006146d48585614681565b6000806040838503121561499157600080fd5b600061470e8585614681565b600080604083850312156149b057600080fd5b60006149bc8585614681565b92505060206146e585828601614436565b600080604083850312156149e057600080fd5b60006149ec8585614681565b92505060206146e5858286016145a2565b60008060408385031215614a1057600080fd5b6000614a1c8585614681565b92505060206146e585828601614681565b6000614a398383614a85565b505060200190565b600061118e8383614f07565b6000614a59838361503b565b505060400190565b6000614a598383615123565b6000614a598383615229565b6000614a398383615243565b614a8e81615822565b82525050565b6000614a9f82615815565b614aa98185615819565b9350614ab48361580f565b8060005b83811015614ae2578151614acc8882614a2d565b9750614ad78361580f565b925050600101614ab8565b509495945050505050565b6000614af882615815565b614b028185615819565b935083602082028501614b148561580f565b8060005b85811015614b4e5784840389528151614b318582614a41565b9450614b3c8361580f565b60209a909a0199925050600101614b18565b5091979650505050505050565b6000614b6682615815565b614b708185615819565b9350614b7b8361580f565b8060005b83811015614ae2578151614b938882614a4d565b9750614b9e8361580f565b925050600101614b7f565b6000614bb482615815565b614bbe8185615819565b9350614bc98361580f565b8060005b83811015614ae2578151614be18882614a61565b9750614bec8361580f565b925050600101614bcd565b6000614c0282615815565b614c0c8185615819565b9350614c178361580f565b8060005b83811015614ae2578151614c2f8882614a6d565b9750614c3a8361580f565b925050600101614c1b565b6000614c5082615815565b614c5a8185615819565b9350614c658361580f565b8060005b83811015614ae2578151614c7d8882614a79565b9750614c888361580f565b925050600101614c69565b6000614c9e82615815565b614ca88185615819565b9350614cb38361580f565b8060005b83811015614ae2578151614ccb8882614a79565b9750614cd68361580f565b925050600101614cb7565b614a8e8161582d565b614a8e614cf682615832565b61587c565b614a8e614cf682615857565b614a8e614cf68261587c565b6000614d1e82615815565b614d2881856109db565b9350614d3881856020860161592a565b9290920192915050565b6000614d4d82615815565b614d578185615819565b9350614d6781856020860161592a565b614d7081615956565b9093019392505050565b614a8e8161587f565b614a8e816158fd565b614a8e81615908565b614a8e81615913565b6000614dab602683615819565b7f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206181527f6464726573730000000000000000000000000000000000000000000000000000602082015260400192915050565b6000614e0a601b83615819565b7f536166654d6174683a206164646974696f6e206f766572666c6f770000000000815260200192915050565b6000614e43602183615819565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f81527f7700000000000000000000000000000000000000000000000000000000000000602082015260400192915050565b6000614ea2602083615819565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572815260200192915050565b6000614edb601f83615819565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00815260200192915050565b8051600090610160840190614f1c8582614d83565b506020830151614f2f6020860182615243565b506040830151614f426040860182614fa9565b506060830151614f5560c0860182615243565b506080830151614f6860e0860182615243565b5060a0830151614f7c610100860182614a85565b5060c0830151614f90610120860182615243565b5060e083015184820361014086015261268d8282614d42565b80516080830190614fba8482614ce1565b506020820151614fcd6020850182614d8c565b506040820151614fe06040850182614d8c565b5060608201516134f86060850182615243565b805160208301906134f88482615243565b80516060830190615015848261525e565b506020820151615028602085018261525e565b5060408201516134f8604085018261524c565b8051604083019061504c8482614a85565b5060208201516134f86020850182615243565b80516101c08301906150718482614a85565b5060208201516150846020850182614ce1565b5060408201516150976040850182614ce1565b5060608201516150aa6060850182615218565b5060808201516150bd60a0850182615004565b5060a08201516150d1610100850182614d7a565b5060c08201516150e5610120850182614d7a565b5060e08201516150f9610140850182614ff3565b5061010082015161510e610160850182614ff3565b506101208201516134f8610180850182615229565b805160408301906151348482614ce1565b5060208201516134f8602085018261523a565b805160c08301906151588482615255565b50602082015161516b6020850182615255565b50604082015161517e6040850182615255565b5060608201516151916060850182615255565b5060808201516151a46080850182615255565b5060a08201516134f860a085018261523a565b805160a08301906151c88482614ff3565b5060208201516151db6020850182614ff3565b5060408201516151ee6040850182614ff3565b5060608201516152016060850182614ff3565b5060808201516134f86080850182615243565b9052565b80516040830190615134848261523a565b8051604083019061504c8482614ce1565b614a8e816158a8565b614a8e8161587c565b614a8e816158d6565b614a8e816158df565b614a8e816158ec565b60006152738284614d07565b50602001919050565b60006152888286614d13565b91506152948285614cfb565b60028201915061268d8284614d13565b60006152b08289614d13565b91506152bc8288614cfb565b6002820191506152cc8287614d13565b91506152d88286614cfb565b6002820191506152e88285614d13565b91506152f48284614cea565b506001019695505050505050565b600061530e828b614d13565b915061531a828a614cfb565b60028201915061532a8289614d13565b91506153368288614cfb565b6002820191506153468287614d13565b91506153528286614cfb565b6002820191506153628285614d13565b915061536e8284614cea565b5060010198975050505050505050565b60208101610af18284614a85565b6040810161539a8285614a85565b61118e6020830184614ce1565b606081016153b58286614a85565b6153c26020830185615243565b612b7e6040830184615243565b6020808252810161118e8184614c45565b608080825281016153f18187614c45565b905081810360208301526154058186614a94565b905081810360408301526154198185614ba9565b90508181036060830152613b8e8184614bf7565b60208101610af18284614ce1565b60208101610af18284614d7a565b60208101610af18284614d95565b6020808252810161118e8184614d42565b60208082528101610af181614d9e565b60208082528101610af181614dfd565b60208082528101610af181614e36565b60208082528101610af181614e95565b60208082528101610af181614ece565b60208101610af18284614ff3565b60608101610af18284615004565b6101c08101610af1828461505f565b61026081016154f2828761505f565b6155006101c0830186615004565b61550e610220830185614ff3565b61268d610240830184614ff3565b60408101610af18284615123565b60c08101610af18284615147565b60a08101610af182846151b7565b606081016155548286615214565b6155616020830185614a85565b612b7e6040830184614a85565b6060810161557c8286615214565b6155896020830185614a85565b612b7e6040830184614ce1565b61012081016155a5828c615214565b6155b2602083018b614a85565b6155bf604083018a614d7a565b6155cc6060830189614d7a565b6155d96080830188614ff3565b6155e660a0830187614ff3565b6155f360c0830186615243565b61560060e0830185614ce1565b61560e610100830184614ce1565b9a9950505050505050505050565b6060810161562a8286615214565b818103602083015261563c8185614b5b565b9050818103604083015261268d8184614aed565b6060810161565e8286615214565b81810360208301526156708185614c93565b9050612b7e6040830184614a85565b6040810161568d8285615214565b61118e6020830184614ff3565b604081016156a88285615214565b61118e6020830184615243565b606081016156c38286615214565b6155616020830185615243565b606081016156de8286615214565b6155896020830185615243565b606081016156f98286615214565b6157066020830185615243565b612b7e6040830184614d7a565b606081016157218286615214565b61572e6020830185615243565b612b7e6040830184614ff3565b606081016153b58286615214565b60408101610af18284615218565b6040810161568d8285614ff3565b60408101610af18284615229565b60208101610af18284615243565b60405181810167ffffffffffffffff811182821017156157a057600080fd5b604052919050565b600067ffffffffffffffff8211156157bf57600080fd5b5060209081020190565b600067ffffffffffffffff8211156157e057600080fd5b506020601f919091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0160190565b60200190565b5190565b90815260200190565b6000610af1826158bd565b151590565b7fff000000000000000000000000000000000000000000000000000000000000001690565b7fffff0000000000000000000000000000000000000000000000000000000000001690565b90565b6000610af182615822565b806109db8161597e565b806109db81615988565b806109db81615992565b6fffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b63ffffffff1690565b67ffffffffffffffff1690565b6bffffffffffffffffffffffff1690565b6000610af18261588a565b6000610af182615894565b6000610af18261589e565b82818337506000910152565b60005b8381101561594557818101518382015260200161592d565b838111156134f85750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b6009811061224557fe5b6002811061224557fe5b6003811061224557fe5b6159a581615822565b811461224557600080fd5b6159a58161582d565b6159a58161587f565b6009811061224557600080fd5b6002811061224557600080fd5b6159a58161587c56fea365627a7a723158207ce20ac0655675b3ab3ddcb1af3df44e9b83138155c22751c3c91249399d7de16c6578706572696d656e74616cf564736f6c634300051000400000000000000000000000000000000000000000000000000214e8348c4f000000000000000000000000000000000000000000000000000000b1a2bc2ec500000000000000000000000000000000000000000000000000000c7d713b49da0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000001bc16d674ec8000000000000000000000000000000000000000000000000000006f05b59d3b200000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000001bc16d674ec800000000000000000000000000000000000000000000000000001bc16d674ec800000000000000000000000000000000000000000000000000056bc75e2d63100000

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106103d05760003560e01c80638da5cb5b116101ff578063d93c95911161011a578063ec6e3987116100ad578063f2fde38b1161007c578063f2fde38b146108bf578063f9416052146108d2578063fd04b606146108e5578063fd47eda6146108f8576103d0565b8063ec6e398714610873578063ef6957d014610886578063f1061ba814610899578063f2901ae2146108ac576103d0565b8063e5520228116100e9578063e552022814610823578063e8e72f751461082b578063eb1c6e6b1461083e578063eb44fdd314610853576103d0565b8063d93c9591146107ca578063deec053d146107dd578063e0e48d19146107f0578063e51bfcb414610803576103d0565b8063c0e044fc11610192578063cb04a34c11610161578063cb04a34c14610771578063d24c48bc14610791578063d36cca90146107a4578063d5ecf7c5146107b7576103d0565b8063c0e044fc1461072e578063c146094214610736578063c190c2ec1461073e578063c8e188261461075e576103d0565b806397bcdfb9116101ce57806397bcdfb9146106d2578063a67a6a45146106e5578063b548b892146106f8578063c0bb72b71461071b576103d0565b80638da5cb5b1461069c5780638f32d59b146106a45780638f6bc659146106ac5780638fae3be1146106bf576103d0565b80633063bce2116102ef5780635735a43011610282578063715018a611610251578063715018a6146106665780637e9eaf411461066e57806385b53fc8146106765780638928378e14610689576103d0565b80635735a430146106085780635ac7d17c1461061b578063697947951461062e5780636a8194e714610643576103d0565b80634be87414116102be5780634be87414146105ba5780634f3c1542146105cd5780634f4d66f6146105d557806356ea84b2146105e8576103d0565b80633063bce214610561578063387a498a146105745780633a031bf01461058757806347d1b53c1461059a576103d0565b8063124f914c116103675780631a7777bb116103365780631a7777bb14610513578063295c39a5146105335780632a5608451461053b5780632e822af31461054e576103d0565b8063124f914c1461049f57806313368364146104c057806317b50525146104e0578063197f0f0514610500576103d0565b80630781d820116103a35780630781d820146104535780630cd30a0e146104665780630f47fab014610479578063121fb72f1461048c576103d0565b80630339a0c4146103d5578063042069d6146103fe578063052f72d714610413578063062bd3e914610433575b600080fd5b6103e86103e3366004614923565b61090b565b6040516103f591906153cf565b60405180910390f35b61041161040c3660046149cd565b6109e0565b005b610426610421366004614697565b610adf565b6040516103f5919061542d565b610446610441366004614923565b610af7565b6040516103f5919061537e565b610411610461366004614923565b610b13565b6104116104743660046149fd565b610c06565b6103e86104873660046148b7565b610cb5565b61041161049a36600461499d565b610cc8565b6104b26104ad3660046148b7565b610d77565b6040516103f5929190615757565b6104d36104ce366004614923565b610d9b565b6040516103f5919061543b565b6104f36104ee3660046148b7565b610dd2565b6040516103f59190615773565b6104d361050e366004614923565b610de4565b610526610521366004614923565b610e1b565b6040516103f591906154b8565b6104f3610e52565b6104f36105493660046146b5565b610e58565b61041161055c366004614899565b610f74565b61041161056f366004614899565b611021565b610411610582366004614899565b6110ce565b6104266105953660046146b5565b61117b565b6105ad6105a83660046148d5565b611195565b6040516103f5919061551c565b6104116105c83660046149cd565b6111b8565b610526611267565b6104f36105e33660046148b7565b611283565b6105fb6105f6366004614923565b611295565b6040516103f591906154c6565b610426610616366004614923565b6112ca565b610426610629366004614923565b611304565b61063661132c565b6040516103f59190615538565b6106566106513660046148b7565b611390565b6040516103f594939291906153e0565b610411611547565b6105266115da565b61041161068436600461482e565b6115f6565b610526610697366004614923565b6116dd565b610446611712565b61042661172e565b6104f36106ba36600461495f565b61176e565b6104f36106cd366004614697565b61181f565b6104116106e036600461471f565b611853565b6104116106f33660046147cf565b61195b565b61070b610706366004614923565b6119e6565b6040516103f594939291906154e3565b610411610729366004614899565b611a42565b6104f3611aef565b610526611af5565b61075161074c3660046148d5565b611b11565b6040516103f59190615765565b6105ad61076c3660046148d5565b611b51565b61078461077f366004614923565b611b59565b6040516103f59190615749565b61052661079f3660046149fd565b611b7b565b6104116107b2366004614863565b611ba7565b6107516107c5366004614923565b611c56565b6107516107d8366004614923565b611c78565b6105fb6107eb366004614923565b611cbb565b6104f36107fe3660046148d5565b611cdd565b6108166108113660046148b7565b611cf0565b6040516103f59190615449565b610526611d02565b61041161083936600461499d565b611d1e565b610846611dcd565b6040516103f5919061552a565b610866610861366004614923565b611e6f565b6040516103f591906154d4565b6104116108813660046146ef565b611ff9565b61041161089436600461497e565b6120a8565b6104266108a7366004614697565b612157565b6104116108ba3660046146ef565b612169565b6104116108cd366004614697565b612218565b6104b26108e03660046148b7565b612248565b6105266108f3366004614923565b612263565b610526610906366004614923565b61229a565b6060600080905060608360405190808252806020026020018201604052801561093e578160200160208202803883390190505b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60005260036020527fb1ee3b3d0d99532dd9f14b22c0b908d4eec0e052c3827bbed2d6c3986954d08c549091505b801580159061099c57508483105b156109d657808284806001019550815181106109b457fe5b602090810291909101810191909152600091825260039052604090205461098e565b509150505b919050565b6109e861172e565b610a0d5760405162461bcd60e51b8152600401610a0490615498565b60405180910390fd5b600f54600160a01b900460ff16610a365760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f8854ab3e00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990638854ab3e90610a989060009086908690600401615713565b60006040518083038186803b158015610ab057600080fd5b505af4158015610ac4573d6000803e3d6000fd5b5050600f805460ff60a01b1916600160a01b17905550505050565b6000610af1818363ffffffff6122cf16565b92915050565b6000610b02826122fe565b610af160008363ffffffff61235f16565b610b1b61172e565b610b375760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610b605760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f70b6151c00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc9906370b6151c90610bc090600090859060040161569a565b60006040518083038186803b158015610bd857600080fd5b505af4158015610bec573d6000803e3d6000fd5b5050600f805460ff60a01b1916600160a01b179055505050565b610c0e61172e565b610c2a5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610c535760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f5eeabe3900000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990635eeabe3990610a98906000908690869060040161573b565b6060610af160008363ffffffff61238b16565b610cd061172e565b610cec5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610d155760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517faa92e34800000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063aa92e34890610a9890600090869086906004016156eb565b610d7f614075565b610d87614075565b610d928360006123d0565b91509150915091565b6000610da6826122fe565b5060009081526001602052604090206003015473ffffffffffffffffffffffffffffffffffffffff1690565b6000610af1818363ffffffff61247516565b6000610def826122fe565b5060009081526001602052604090206004015473ffffffffffffffffffffffffffffffffffffffff1690565b610e23614075565b610e2c826122fe565b506000908152600160209081526040918290208251918201909252600690910154815290565b60005490565b6000610e6261172e565b610e7e5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610ea75760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fdd32998a00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063dd32998a90610f099060009087908790600401615546565b60206040518083038186803b158015610f2157600080fd5b505af4158015610f35573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610f599190810190614941565b9050600f805460ff60a01b1916600160a01b17905592915050565b610f7c61172e565b610f985760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16610fc15760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517ff9cacc4c00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063f9cacc4c90610bc090600090859060040161567f565b61102961172e565b6110455760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff1661106e5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f0f44e6bc00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990630f44e6bc90610bc090600090859060040161567f565b6110d661172e565b6110f25760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff1661111b5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f311401d000000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063311401d090610bc090600090859060040161567f565b600061118e81848463ffffffff6124bc16565b9392505050565b61119d614088565b6111a6826122fe565b61118e6000848463ffffffff6124f916565b6111c061172e565b6111dc5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166112055760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f7335079b00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990637335079b90610a989060009086908690600401615713565b61126f614075565b506040805160208101909152600854815290565b6000610af1818363ffffffff61257816565b61129d61409f565b6112a6826122fe565b610af1826112bb60008263ffffffff6125ba16565b6000919063ffffffff61263e16565b60006112d5826122fe565b506000908152600160205260409020547501000000000000000000000000000000000000000000900460ff1690565b600061130f826122fe565b50600090815260016020526040902054600160a01b900460ff1690565b6113346140bf565b506040805160c08101825260085460a08201908152815281516020818101845260095482528083019190915282518082018452600a548152828401528251908101909252600b5482526060810191909152600c54608082015290565b6060808080806113a760008763ffffffff61238b16565b9050606081516040519080825280602002602001820160405280156113d6578160200160208202803883390190505b5090506060825160405190808252806020026020018201604052801561141657816020015b611403614088565b8152602001906001900390816113fb5790505b5090506060835160405190808252806020026020018201604052801561145657816020015b611443614088565b81526020019060019003908161143b5790505b50905060005b84518110156115375761148185828151811061147457fe5b6020026020010151610af7565b84828151811061148d57fe5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250506114e48a8683815181106114d757fe5b6020026020010151611195565b8382815181106114f057fe5b60200260200101819052506115188a86838151811061150b57fe5b6020026020010151611b11565b82828151811061152457fe5b602090810291909101015260010161145c565b5092989197509550909350915050565b61154f61172e565b61156b5760405162461bcd60e51b8152600401610a0490615498565b600f5460405160009173ffffffffffffffffffffffffffffffffffffffff16907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600f80547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b6115e2614075565b506040805160208101909152600b54815290565b60005b81518110156116d957600082828151811061161057fe5b6020026020010151600001519050600083838151811061162c57fe5b60209081029190910181015181015133600081815260058452604080822073ffffffffffffffffffffffffffffffffffffffff8816835290945283902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001683151517905591519092507f4d7f317d2088d039c2a95a09fcbf9cc9191fad5905f883c937cc3d317c4a6327906116c7908590859061538c565b60405180910390a250506001016115f9565b5050565b6116e5614075565b6116ee826122fe565b610af18261170360008263ffffffff61235f16565b6000919063ffffffff61269616565b600f5473ffffffffffffffffffffffffffffffffffffffff1690565b600f5460009073ffffffffffffffffffffffffffffffffffffffff166117526127c5565b73ffffffffffffffffffffffffffffffffffffffff1614905090565b600061177861172e565b6117945760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166117bd5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fb25328e000000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063b25328e090610f0990600090879087906004016156b5565b600061182a826127c9565b5073ffffffffffffffffffffffffffffffffffffffff1660009081526002602052604090205490565b61185b61172e565b6118775760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166118a05760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f526ebb2700000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063526ebb279061190e906000908c908c908c908c908c908c908c908c90600401615596565b60006040518083038186803b15801561192657600080fd5b505af415801561193a573d6000803e3d6000fd5b5050600f805460ff60a01b1916600160a01b17905550505050505050505050565b600f54600160a01b900460ff166119845760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fbd76ecfd000000000000000000000000000000000000000000000000000000008152737908b447ed2050043bb32daffab06739701245279063bd76ecfd90610a98906000908690869060040161561c565b6119ee614106565b6119f661409f565b6119fe614075565b611a06614075565b611a0f856122fe565b611a1885611e6f565b611a2186611295565b611a2a876116dd565b611a338861229a565b93509350935093509193509193565b611a4a61172e565b611a665760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16611a8f5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f54dd351600000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc9906354dd351690610bc090600090859060040161567f565b600c5490565b611afd614075565b506040805160208101909152600954815290565b611b19614088565b611b22826122fe565b61118e611b376000858563ffffffff6124f916565b611b4c846112bb60008263ffffffff6125ba16565b612832565b6111a6614088565b611b61614088565b611b6a826122fe565b610af160008363ffffffff6128e316565b611b83614075565b611b8c836122fe565b611b95826122fe565b61118e6000848463ffffffff61294316565b611baf61172e565b611bcb5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16611bf45760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fd963729100000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063d963729190610a989060009086908690600401615650565b611c5e614088565b611c67826122fe565b610af160008363ffffffff6129da16565b611c80614088565b611c89826122fe565b506000908152600160209081526040918290208251808401909352600781015460ff1615158352600801549082015290565b611cc361409f565b611ccc826122fe565b610af160008363ffffffff6125ba16565b600061118e81848463ffffffff612b3516565b6000610af1818363ffffffff612b8616565b611d0a614075565b506040805160208101909152600a54815290565b611d2661172e565b611d425760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff16611d6b5760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f8c5dabd100000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990638c5dabd190610a9890600090869086906004016156eb565b611dd5614177565b506040805160c081018252600d5467ffffffffffffffff808216835268010000000000000000808304821660208501527001000000000000000000000000000000008304821694840194909452780100000000000000000000000000000000000000000000000090910481166060830152600e549081166080830152919091046fffffffffffffffffffffffffffffffff1660a082015290565b611e77614106565b611e80826122fe565b50600090815260016020818152604092839020835161014081018552815473ffffffffffffffffffffffffffffffffffffffff8082168352600160a01b820460ff9081161515848701527501000000000000000000000000000000000000000000909204821615158388015286518088018852958401546fffffffffffffffffffffffffffffffff808216885270010000000000000000000000000000000090910416868601526060808401969096528651958601875260028401546bffffffffffffffffffffffff80821688526c01000000000000000000000000820416878701527801000000000000000000000000000000000000000000000000900463ffffffff168688015260808301959095526003830154851660a0830152600483015490941660c0820152845180840186526005830154815260e082015284518084018652600683015481526101008201528451808601909552600782015490931615158452600801549083015261012081019190915290565b61200161172e565b61201d5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166120465760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f3c0c9ddc00000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc990633c0c9ddc90610a98906000908690869060040161556e565b6120b061172e565b6120cc5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166120f55760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517f10c87b0600000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc9906310c87b0690610a9890600090869086906004016156d0565b6000610af1818363ffffffff612bc516565b61217161172e565b61218d5760405162461bcd60e51b8152600401610a0490615498565b600f54600160a01b900460ff166121b65760405162461bcd60e51b8152600401610a04906154a8565b600f805460ff60a01b191690556040517fe80f802400000000000000000000000000000000000000000000000000000000815273b04ccb2d3850bf08eca8a9ff7db7d018fa17cfc99063e80f802490610a98906000908690869060040161556e565b61222061172e565b61223c5760405162461bcd60e51b8152600401610a0490615498565b61224581612bf4565b50565b612250614075565b612258614075565b610d928360016123d0565b61226b614075565b612274826122fe565b506000908152600160209081526040918290208251918201909252600590910154815290565b6122a2614075565b6122ab826122fe565b610af1826122c060008263ffffffff6125ba16565b6000919063ffffffff612cb516565b73ffffffffffffffffffffffffffffffffffffffff166000908152600691909101602052604090205460ff1690565b6000546122459082108015612336575060008281526001602052604090205473ffffffffffffffffffffffffffffffffffffffff1615155b6010547f496e76616c6964206d61726b6574000000000000000000000000000000000000612dc0565b6000908152600191909101602052604090205473ffffffffffffffffffffffffffffffffffffffff1690565b805173ffffffffffffffffffffffffffffffffffffffff1660009081526004830160209081526040808320828501518452909152902060609061118e90600101612e53565b6123d8614075565b6123e0614075565b60606123f360008663ffffffff61238b16565b90506123fd6141ac565b6124078251612eaf565b905060005b82518110156124435761243b83828151811061242457fe5b602002602001015183612f0e90919063ffffffff16565b60010161240c565b5061245560008263ffffffff612f7816565b612468600087838863ffffffff61317a16565b9350935050509250929050565b805173ffffffffffffffffffffffffffffffffffffffff16600090815260049290920160209081526040808420928201518452919052902054610100900463ffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff9182166000908152600593909301602090815260408085209290931684525290205460ff1690565b612501614088565b50815173ffffffffffffffffffffffffffffffffffffffff1660009081526004840160209081526040808320828601518452825280832084845260030182529182902082518084019093525460ff8116151583526fffffffffffffffffffffffffffffffff61010090910416908201529392505050565b805173ffffffffffffffffffffffffffffffffffffffff1660009081526004830160209081526040808320828501518452909152812061118e906001016132f2565b6125c261409f565b506000908152600191909101602090815260409182902082516060810184526002909101546bffffffffffffffffffffffff80821683526c0100000000000000000000000082041692820192909252780100000000000000000000000000000000000000000000000090910463ffffffff169181019190915290565b61264661409f565b61264e614075565b61265f85858563ffffffff612cb516565b905061268d8382612676888863ffffffff6128e316565b6040805160208101909152600a8a015481526132f6565b95945050505050565b61269e614075565b600083815260018501602052604090206003015473ffffffffffffffffffffffffffffffffffffffff166126d0614075565b6040517f41976e0900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8316906341976e099061272290879060040161537e565b60206040518083038186803b15801561273a57600080fd5b505afa15801561274e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506127729190810190614905565b805190915061268d9015157f53746f72616765000000000000000000000000000000000000000000000000007f50726963652063616e6e6f74206265207a65726f00000000000000000000000088613460565b3390565b73ffffffffffffffffffffffffffffffffffffffff808216600081815260026020908152604080832054835260019091529020546010546122459391909116909114907f496e76616c696420746f6b656e00000000000000000000000000000000000000612dc0565b61283a614088565b602083015183516fffffffffffffffffffffffffffffffff90911690156128a65760408051808201909152600181526020848101519082019061289b9084906bffffffffffffffffffffffff16670de0b6b3a764000063ffffffff6134fe16565b815250915050610af1565b60408051808201909152600081528351602082019061289b9084906bffffffffffffffffffffffff16670de0b6b3a764000063ffffffff6134fe16565b6128eb614088565b506000818152600180840160209081526040928390208351808501909452909101546fffffffffffffffffffffffffffffffff8082168452700100000000000000000000000000000000909104169082015292915050565b61294b614075565b600984015460008481526001860160209081526040918290208251918201909252600690910154815261298890829061298390613592565b6135c9565b90506129c381612983876001016000878152602001908152602001600020600601604051806020016040529081600082015481525050613592565b604080516020810190915290815295945050505050565b6129e2614088565b6129ea61409f565b6129fa848463ffffffff6125ba16565b9050612a04614088565b612a14858563ffffffff6128e316565b90506000612a28868663ffffffff61235f16565b9050612a32614088565b6040805180820182526001815290517f70a08231000000000000000000000000000000000000000000000000000000008152602082019073ffffffffffffffffffffffffffffffffffffffff8516906370a0823190612a9590309060040161537e565b60206040518083038186803b158015612aad57600080fd5b505afa158015612ac1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612ae59190810190614941565b90529050612af1614088565b612af9614088565b612b0385876135e2565b9092509050612b2882612b1c858463ffffffff61368a16565b9063ffffffff61368a16565b9998505050505050505050565b815173ffffffffffffffffffffffffffffffffffffffff16600090815260048401602090815260408083208286015184529091528120612b7e906001018363ffffffff6136a416565b949350505050565b805173ffffffffffffffffffffffffffffffffffffffff1660009081526004929092016020908152604080842092820151845291905290205460ff1690565b73ffffffffffffffffffffffffffffffffffffffff166000908152600791909101602052604090205460ff1690565b73ffffffffffffffffffffffffffffffffffffffff8116612c275760405162461bcd60e51b8152600401610a0490615468565b600f5460405173ffffffffffffffffffffffffffffffffffffffff8084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3600f80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b612cbd614075565b612cc5614088565b612cd5858563ffffffff6128e316565b9050612cdf614088565b612ce7614088565b612cf183866135e2565b91509150612cfd614075565b600087815260018901602052604090206004015473ffffffffffffffffffffffffffffffffffffffff1663e8177dcf612d3c8a8a63ffffffff61235f16565b846020015186602001516040518463ffffffff1660e01b8152600401612d64939291906153a7565b60206040518083038186803b158015612d7c57600080fd5b505afa158015612d90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612db49190810190614905565b98975050505050505050565b82612e4e57612dce826136c8565b7f3a20000000000000000000000000000000000000000000000000000000000000612df8836136c8565b604051602001612e0a9392919061527c565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529082905262461bcd60e51b8252610a0491600401615457565b505050565b606081600001805480602002602001604051908101604052809291908181526020018280548015612ea357602002820191906000526020600020905b815481526020019060010190808311612e8f575b50505050509050919050565b612eb76141ac565b604080516000606082018181526080830190935290918291612eef565b612edc6141cd565b815260200190600190039081612ed45790505b508152602001612efe8461379c565b8152600060209091015292915050565b815151612f5d90157f43616368650000000000000000000000000000000000000000000000000000007f616c726561647920696e697469616c697a656400000000000000000000000000612dc0565b612f6b8260200151826137d6565b5060400180516001019052565b8060400151604051908082528060200260200182016040528015612fb657816020015b612fa36141cd565b815260200190600190039081612f9b5790505b5081526000805b82602001515181101561312057600083602001518281518110612fdc57fe5b602002602001015190505b8015613105576000612ff88261380c565b9050600061300684836139e3565b9050600061301a888363ffffffff61235f16565b9050613024614088565b613034898463ffffffff6128e316565b6040805160e08101825285815273ffffffffffffffffffffffffffffffffffffffff8516602080830191909152600087815260018e01825283902054600160a01b900460ff1615159282019290925282516fffffffffffffffffffffffffffffffff908116606083015291830151909116608082015290915060a081016130bb8b866125ba565b81526020016130d18b868663ffffffff61269616565b90528851805160018a01999081106130e557fe5b60200260200101819052506130fa85856139ee565b945050505050612fe7565b83604001518314156131175750613120565b50600101612fbd565b506040820151825151612e4e91808414917f53746f7261676500000000000000000000000000000000000000000000000000917f636163686520696e697469616c697a656420696d70726f7065726c7900000000916139f7565b613182614075565b61318a614075565b613192614075565b61319a614075565b60006131a587613ac2565b905060005b818110156132e3576131ba614088565b6131f28a6131ce8b8563ffffffff613ac716565b516131df8c8663ffffffff613ac716565b60a001518e92919063ffffffff613b4316565b90506131fd81613b98565b1561320857506132db565b600061323361321d8b8563ffffffff613ac716565b60c001515160208401519063ffffffff613ba016565b905061323d614075565b613245613bda565b905089156132905761328d60018e0160006132668e8863ffffffff613ac716565b51815260208082019290925260409081016000208151928301909152600501548152613592565b90505b8251156132b9576132b26132a48383613bfc565b88519063ffffffff613c1516565b87526132d7565b6132d46132c683836135c9565b87519063ffffffff613c1516565b86525b5050505b6001016131aa565b50919890975095505050505050565b5490565b6132fe61409f565b613306614088565b61330e614088565b61331885886135e2565b915091506000613326613c3a565b9050600061335e6133508a6040015163ffffffff168463ffffffff16613c4a90919063ffffffff16565b89519063ffffffff613ba016565b9050600061336b85613b98565b15613378575060006133aa565b61338282886135c9565b90508460200151846020015110156133aa576133a78185602001518760200151613c8c565b90505b818111156133b457fe5b60408051606081019091528a5181906133fd906133f8906bffffffffffffffffffffffff166133ec8188670de0b6b3a7640000613c8c565b9063ffffffff613c1516565b613ca2565b6bffffffffffffffffffffffff908116825260208d810151920191613434916133f891166133ec8187670de0b6b3a7640000613c8c565b6bffffffffffffffffffffffff1681526020018463ffffffff1681525095505050505050949350505050565b836134f85761346e836136c8565b7f3a20000000000000000000000000000000000000000000000000000000000000613498846136c8565b7f203c0000000000000000000000000000000000000000000000000000000000006134c285613d01565b604051612e0a9594939291907f3e00000000000000000000000000000000000000000000000000000000000000906020016152a4565b50505050565b600083158061350b575082155b156135225761351b600083613e10565b905061118e565b6000613534858563ffffffff613ba016565b905061268d61355f60016133ec6002613553888463ffffffff613c4a16565b9063ffffffff613e1016565b61356f838663ffffffff613e5216565b101561357c57600061357f565b60015b60ff166133ec838663ffffffff613e1016565b61359a614075565b6040805160208101909152825181906135c190670de0b6b3a764000063ffffffff613c1516565b905292915050565b600061118e838360000151670de0b6b3a7640000613c8c565b6135ea614088565b6135f2614088565b6135fa614088565b5060408051808201909152600181526020858101516fffffffffffffffffffffffffffffffff169082015261362d614088565b50604080518082019091526000815285516fffffffffffffffffffffffffffffffff16602082015261365d614088565b6136678387612832565b9050613671614088565b61367b8388612832565b91989197509095505050505050565b613692614088565b61118e8361369f84613e94565b613ebb565b60008260000182815481106136b557fe5b9060005260206000200154905092915050565b606080826040516020016136dc9190615267565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152919052905060205b80156137855781517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9091019082908290811061374857fe5b01602001517fff00000000000000000000000000000000000000000000000000000000000000161561378057600101815290506109db565b61370f565b505060408051600081526020810190915292915050565b606060016101008304016040519080825280602002602001820160405280156137cf578160200160208202803883390190505b5092915050565b815161010082049060ff8316906001821b908590849081106137f457fe5b60200260200101818151179150818152505050505050565b600060ff6fffffffffffffffffffffffffffffffff83161561384f577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8001613857565b608083901c92505b67ffffffffffffffff83161561388e577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc001613896565b604083901c92505b63ffffffff8316156138c9577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0016138d1565b602083901c92505b61ffff831615613902577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00161390a565b601083901c92505b60ff83161561393a577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff801613942565b600883901c92505b600f831615613972577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc0161397a565b600483901c92505b60038316156139aa577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016139b2565b600283901c92505b6001831615610af1577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0192915050565b610100919091020190565b6001901b900390565b84613abb57613a05846136c8565b7f3a20000000000000000000000000000000000000000000000000000000000000613a2f856136c8565b7f203c000000000000000000000000000000000000000000000000000000000000613a5986613d01565b7f2c20000000000000000000000000000000000000000000000000000000000000613a8387613d01565b604051612e0a97969594939291907f3e0000000000000000000000000000000000000000000000000000000000000090602001615302565b5050505050565b515190565b613acf6141cd565b825151613b2590808410907f4361636865000000000000000000000000000000000000000000000000000000907f696e76616c696420696e646578000000000000000000000000000000000000009086906139f7565b8251805183908110613b3357fe5b6020026020010151905092915050565b613b4b614088565b613b53614088565b613b6486868663ffffffff6124f916565b9050613b6f81613f4d565b15613b8457613b7c613f67565b915050612b7e565b613b8e8184612832565b9695505050505050565b602001511590565b600082613baf57506000610af1565b82820282848281613bbc57fe5b041461118e5760405162461bcd60e51b8152600401610a0490615488565b613be2614075565b506040805160208101909152670de0b6b3a7640000815290565b600061118e83670de0b6b3a76400008460000151613c8c565b60008282018381101561118e5760405162461bcd60e51b8152600401610a0490615478565b6000613c4542613f87565b905090565b600061118e83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613fde565b6000612b7e82613553868663ffffffff613ba016565b600081610af16bffffffffffffffffffffffff821682147f4d617468000000000000000000000000000000000000000000000000000000007f556e73616665206361737420746f2075696e743936000000000000000000000084613460565b606081613d42575060408051808201909152600181527f300000000000000000000000000000000000000000000000000000000000000060208201526109db565b8160005b8115613d5a57600101600a82049150613d46565b6060816040519080825280601f01601f191660200182016040528015613d87576020820181803883390190505b508593509050815b8015613e07577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600a840660300160f81b828281518110613dcd57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84049350613d8f565b50949350505050565b600061118e83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061400a565b600061118e83836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f0000000000000000815250614041565b613e9c614088565b5060408051808201909152815115815260208083015190820152919050565b613ec3614088565b613ecb614088565b8251845115159015151415613efe5783511515815260208085015190840151613ef49190613c15565b602082015261118e565b8260200151846020015110613f275783511515815260208085015190840151613ef49190613c4a565b82511515815260208084015190850151613f419190613c4a565b60208201529392505050565b602001516fffffffffffffffffffffffffffffffff161590565b613f6f614088565b50604080518082019091526000808252602082015290565b600081610af163ffffffff821682147f4d617468000000000000000000000000000000000000000000000000000000007f556e73616665206361737420746f2075696e743332000000000000000000000084613460565b600081848411156140025760405162461bcd60e51b8152600401610a049190615457565b505050900390565b6000818361402b5760405162461bcd60e51b8152600401610a049190615457565b50600083858161403757fe5b0495945050505050565b600081836140625760405162461bcd60e51b8152600401610a049190615457565b5082848161406c57fe5b06949350505050565b6040518060200160405280600081525090565b604080518082019091526000808252602082015290565b604080516060810182526000808252602082018190529181019190915290565b6040518060a001604052806140d2614075565b81526020016140df614075565b81526020016140ec614075565b81526020016140f9614075565b8152602001600081525090565b60408051610140810182526000808252602082018190529181019190915260608101614130614088565b815260200161413d61409f565b81526000602082018190526040820152606001614158614075565b8152602001614165614075565b8152602001614172614088565b905290565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b60405180606001604052806060815260200160608152602001600081525090565b6040805160e08101825260008082526020820181905291810182905260608101829052608081019190915260a0810161420461409f565b8152602001614172614075565b8035610af18161599c565b600082601f83011261422d57600080fd5b813561424061423b826157a8565b615781565b81815260209384019390925082018360005b8381101561427e57813586016142688882614457565b8452506020928301929190910190600101614252565b5050505092915050565b600082601f83011261429957600080fd5b81356142a761423b826157a8565b915081818352602084019350602081019050838560408402820111156142cc57600080fd5b60005b8381101561427e57816142e288826145d5565b845250602090920191604091909101906001016142cf565b600082601f83011261430b57600080fd5b813561431961423b826157a8565b9150818183526020840193506020810190508385604084028201111561433e57600080fd5b60005b8381101561427e5781614354888261461c565b84525060209092019160409190910190600101614341565b600082601f83011261437d57600080fd5b813561438b61423b826157a8565b915081818352602084019350602081019050838560208402820111156143b057600080fd5b60005b8381101561427e57816143c68882614681565b84525060209283019291909101906001016143b3565b8035610af1816159b0565b600082601f8301126143f857600080fd5b813561440661423b826157c9565b9150808252602083016020830185838301111561442257600080fd5b61442d83828461591e565b50505092915050565b8035610af1816159b9565b8035610af1816159c2565b8035610af1816159cf565b6000610160828403121561446a57600080fd5b614475610100615781565b905060006144838484614441565b825250602061449484848301614681565b60208301525060406144a884828501614533565b60408301525060c06144bc84828501614681565b60608301525060e06144d084828501614681565b6080830152506101006144e584828501614211565b60a0830152506101206144fa84828501614681565b60c08301525061014082013567ffffffffffffffff81111561451b57600080fd5b614527848285016143e7565b60e08301525092915050565b60006080828403121561454557600080fd5b61454f6080615781565b9050600061455d84846143dc565b825250602061456e8484830161444c565b60208301525060406145828482850161444c565b604083015250606061459684828501614681565b60608301525092915050565b6000602082840312156145b457600080fd5b6145be6020615781565b905060006145cc8484614681565b82525092915050565b6000604082840312156145e757600080fd5b6145f16040615781565b905060006145ff8484614211565b825250602061461084848301614681565b60208301525092915050565b60006040828403121561462e57600080fd5b6146386040615781565b905060006146468484614211565b8252506020614610848483016143dc565b60006020828403121561466957600080fd5b6146736020615781565b905060006145cc848461468c565b8035610af1816159dc565b8051610af1816159dc565b6000602082840312156146a957600080fd5b6000612b7e8484614211565b600080604083850312156146c857600080fd5b60006146d48585614211565b92505060206146e585828601614211565b9150509250929050565b6000806040838503121561470257600080fd5b600061470e8585614211565b92505060206146e5858286016143dc565b600080600080600080600080610100898b03121561473c57600080fd5b60006147488b8b614211565b98505060206147598b828c01614436565b975050604061476a8b828c01614436565b965050606061477b8b828c016145a2565b955050608061478c8b828c016145a2565b94505060a061479d8b828c01614681565b93505060c06147ae8b828c016143dc565b92505060e06147bf8b828c016143dc565b9150509295985092959890939650565b600080604083850312156147e257600080fd5b823567ffffffffffffffff8111156147f957600080fd5b61480585828601614288565b925050602083013567ffffffffffffffff81111561482257600080fd5b6146e58582860161421c565b60006020828403121561484057600080fd5b813567ffffffffffffffff81111561485757600080fd5b612b7e848285016142fa565b6000806040838503121561487657600080fd5b823567ffffffffffffffff81111561488d57600080fd5b6146d48582860161436c565b6000602082840312156148ab57600080fd5b6000612b7e84846145a2565b6000604082840312156148c957600080fd5b6000612b7e84846145d5565b600080606083850312156148e857600080fd5b60006148f485856145d5565b92505060406146e585828601614681565b60006020828403121561491757600080fd5b6000612b7e8484614657565b60006020828403121561493557600080fd5b6000612b7e8484614681565b60006020828403121561495357600080fd5b6000612b7e848461468c565b6000806040838503121561497257600080fd5b60006146d48585614681565b6000806040838503121561499157600080fd5b600061470e8585614681565b600080604083850312156149b057600080fd5b60006149bc8585614681565b92505060206146e585828601614436565b600080604083850312156149e057600080fd5b60006149ec8585614681565b92505060206146e5858286016145a2565b60008060408385031215614a1057600080fd5b6000614a1c8585614681565b92505060206146e585828601614681565b6000614a398383614a85565b505060200190565b600061118e8383614f07565b6000614a59838361503b565b505060400190565b6000614a598383615123565b6000614a598383615229565b6000614a398383615243565b614a8e81615822565b82525050565b6000614a9f82615815565b614aa98185615819565b9350614ab48361580f565b8060005b83811015614ae2578151614acc8882614a2d565b9750614ad78361580f565b925050600101614ab8565b509495945050505050565b6000614af882615815565b614b028185615819565b935083602082028501614b148561580f565b8060005b85811015614b4e5784840389528151614b318582614a41565b9450614b3c8361580f565b60209a909a0199925050600101614b18565b5091979650505050505050565b6000614b6682615815565b614b708185615819565b9350614b7b8361580f565b8060005b83811015614ae2578151614b938882614a4d565b9750614b9e8361580f565b925050600101614b7f565b6000614bb482615815565b614bbe8185615819565b9350614bc98361580f565b8060005b83811015614ae2578151614be18882614a61565b9750614bec8361580f565b925050600101614bcd565b6000614c0282615815565b614c0c8185615819565b9350614c178361580f565b8060005b83811015614ae2578151614c2f8882614a6d565b9750614c3a8361580f565b925050600101614c1b565b6000614c5082615815565b614c5a8185615819565b9350614c658361580f565b8060005b83811015614ae2578151614c7d8882614a79565b9750614c888361580f565b925050600101614c69565b6000614c9e82615815565b614ca88185615819565b9350614cb38361580f565b8060005b83811015614ae2578151614ccb8882614a79565b9750614cd68361580f565b925050600101614cb7565b614a8e8161582d565b614a8e614cf682615832565b61587c565b614a8e614cf682615857565b614a8e614cf68261587c565b6000614d1e82615815565b614d2881856109db565b9350614d3881856020860161592a565b9290920192915050565b6000614d4d82615815565b614d578185615819565b9350614d6781856020860161592a565b614d7081615956565b9093019392505050565b614a8e8161587f565b614a8e816158fd565b614a8e81615908565b614a8e81615913565b6000614dab602683615819565b7f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206181527f6464726573730000000000000000000000000000000000000000000000000000602082015260400192915050565b6000614e0a601b83615819565b7f536166654d6174683a206164646974696f6e206f766572666c6f770000000000815260200192915050565b6000614e43602183615819565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f81527f7700000000000000000000000000000000000000000000000000000000000000602082015260400192915050565b6000614ea2602083615819565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572815260200192915050565b6000614edb601f83615819565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00815260200192915050565b8051600090610160840190614f1c8582614d83565b506020830151614f2f6020860182615243565b506040830151614f426040860182614fa9565b506060830151614f5560c0860182615243565b506080830151614f6860e0860182615243565b5060a0830151614f7c610100860182614a85565b5060c0830151614f90610120860182615243565b5060e083015184820361014086015261268d8282614d42565b80516080830190614fba8482614ce1565b506020820151614fcd6020850182614d8c565b506040820151614fe06040850182614d8c565b5060608201516134f86060850182615243565b805160208301906134f88482615243565b80516060830190615015848261525e565b506020820151615028602085018261525e565b5060408201516134f8604085018261524c565b8051604083019061504c8482614a85565b5060208201516134f86020850182615243565b80516101c08301906150718482614a85565b5060208201516150846020850182614ce1565b5060408201516150976040850182614ce1565b5060608201516150aa6060850182615218565b5060808201516150bd60a0850182615004565b5060a08201516150d1610100850182614d7a565b5060c08201516150e5610120850182614d7a565b5060e08201516150f9610140850182614ff3565b5061010082015161510e610160850182614ff3565b506101208201516134f8610180850182615229565b805160408301906151348482614ce1565b5060208201516134f8602085018261523a565b805160c08301906151588482615255565b50602082015161516b6020850182615255565b50604082015161517e6040850182615255565b5060608201516151916060850182615255565b5060808201516151a46080850182615255565b5060a08201516134f860a085018261523a565b805160a08301906151c88482614ff3565b5060208201516151db6020850182614ff3565b5060408201516151ee6040850182614ff3565b5060608201516152016060850182614ff3565b5060808201516134f86080850182615243565b9052565b80516040830190615134848261523a565b8051604083019061504c8482614ce1565b614a8e816158a8565b614a8e8161587c565b614a8e816158d6565b614a8e816158df565b614a8e816158ec565b60006152738284614d07565b50602001919050565b60006152888286614d13565b91506152948285614cfb565b60028201915061268d8284614d13565b60006152b08289614d13565b91506152bc8288614cfb565b6002820191506152cc8287614d13565b91506152d88286614cfb565b6002820191506152e88285614d13565b91506152f48284614cea565b506001019695505050505050565b600061530e828b614d13565b915061531a828a614cfb565b60028201915061532a8289614d13565b91506153368288614cfb565b6002820191506153468287614d13565b91506153528286614cfb565b6002820191506153628285614d13565b915061536e8284614cea565b5060010198975050505050505050565b60208101610af18284614a85565b6040810161539a8285614a85565b61118e6020830184614ce1565b606081016153b58286614a85565b6153c26020830185615243565b612b7e6040830184615243565b6020808252810161118e8184614c45565b608080825281016153f18187614c45565b905081810360208301526154058186614a94565b905081810360408301526154198185614ba9565b90508181036060830152613b8e8184614bf7565b60208101610af18284614ce1565b60208101610af18284614d7a565b60208101610af18284614d95565b6020808252810161118e8184614d42565b60208082528101610af181614d9e565b60208082528101610af181614dfd565b60208082528101610af181614e36565b60208082528101610af181614e95565b60208082528101610af181614ece565b60208101610af18284614ff3565b60608101610af18284615004565b6101c08101610af1828461505f565b61026081016154f2828761505f565b6155006101c0830186615004565b61550e610220830185614ff3565b61268d610240830184614ff3565b60408101610af18284615123565b60c08101610af18284615147565b60a08101610af182846151b7565b606081016155548286615214565b6155616020830185614a85565b612b7e6040830184614a85565b6060810161557c8286615214565b6155896020830185614a85565b612b7e6040830184614ce1565b61012081016155a5828c615214565b6155b2602083018b614a85565b6155bf604083018a614d7a565b6155cc6060830189614d7a565b6155d96080830188614ff3565b6155e660a0830187614ff3565b6155f360c0830186615243565b61560060e0830185614ce1565b61560e610100830184614ce1565b9a9950505050505050505050565b6060810161562a8286615214565b818103602083015261563c8185614b5b565b9050818103604083015261268d8184614aed565b6060810161565e8286615214565b81810360208301526156708185614c93565b9050612b7e6040830184614a85565b6040810161568d8285615214565b61118e6020830184614ff3565b604081016156a88285615214565b61118e6020830184615243565b606081016156c38286615214565b6155616020830185615243565b606081016156de8286615214565b6155896020830185615243565b606081016156f98286615214565b6157066020830185615243565b612b7e6040830184614d7a565b606081016157218286615214565b61572e6020830185615243565b612b7e6040830184614ff3565b606081016153b58286615214565b60408101610af18284615218565b6040810161568d8285614ff3565b60408101610af18284615229565b60208101610af18284615243565b60405181810167ffffffffffffffff811182821017156157a057600080fd5b604052919050565b600067ffffffffffffffff8211156157bf57600080fd5b5060209081020190565b600067ffffffffffffffff8211156157e057600080fd5b506020601f919091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0160190565b60200190565b5190565b90815260200190565b6000610af1826158bd565b151590565b7fff000000000000000000000000000000000000000000000000000000000000001690565b7fffff0000000000000000000000000000000000000000000000000000000000001690565b90565b6000610af182615822565b806109db8161597e565b806109db81615988565b806109db81615992565b6fffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b63ffffffff1690565b67ffffffffffffffff1690565b6bffffffffffffffffffffffff1690565b6000610af18261588a565b6000610af182615894565b6000610af18261589e565b82818337506000910152565b60005b8381101561594557818101518382015260200161592d565b838111156134f85750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b6009811061224557fe5b6002811061224557fe5b6003811061224557fe5b6159a581615822565b811461224557600080fd5b6159a58161582d565b6159a58161587f565b6009811061224557600080fd5b6002811061224557600080fd5b6159a58161587c56fea365627a7a723158207ce20ac0655675b3ab3ddcb1af3df44e9b83138155c22751c3c91249399d7de16c6578706572696d656e74616cf564736f6c63430005100040

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

0000000000000000000000000000000000000000000000000214e8348c4f000000000000000000000000000000000000000000000000000000b1a2bc2ec500000000000000000000000000000000000000000000000000000c7d713b49da0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000001bc16d674ec8000000000000000000000000000000000000000000000000000006f05b59d3b200000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000001bc16d674ec800000000000000000000000000000000000000000000000000001bc16d674ec800000000000000000000000000000000000000000000000000056bc75e2d63100000

-----Decoded View---------------
Arg [0] : riskParams (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]
Arg [1] : riskLimits (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]

-----Encoded View---------------
11 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000214e8348c4f0000
Arg [1] : 00000000000000000000000000000000000000000000000000b1a2bc2ec50000
Arg [2] : 0000000000000000000000000000000000000000000000000c7d713b49da0000
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [5] : 0000000000000000000000000000000000000000000000001bc16d674ec80000
Arg [6] : 00000000000000000000000000000000000000000000000006f05b59d3b20000
Arg [7] : 0000000000000000000000000000000000000000000000000de0b6b3a7640000
Arg [8] : 0000000000000000000000000000000000000000000000001bc16d674ec80000
Arg [9] : 0000000000000000000000000000000000000000000000001bc16d674ec80000
Arg [10] : 0000000000000000000000000000000000000000000000056bc75e2d63100000


Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.