ETH Price: $3,234.76 (+1.63%)

Contract

0xDfB6BAA334712cBBeb26B7537f62B81C2a87B1E8

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Withdraw Wei Fro...191697252025-01-15 5:01:053 hrs ago1736917265IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000008760.0385
Withdraw Wei Fro...191611652025-01-14 21:12:0811 hrs ago1736889128IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.00002340.1
Withdraw ETH Fro...191556282025-01-14 16:07:2416 hrs ago1736870844IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000062310.24
Withdraw ETH Fro...191548202025-01-14 15:21:0216 hrs ago1736868062IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000061890.25949953
Withdraw Wei Fro...191548172025-01-14 15:20:5116 hrs ago1736868051IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000060730.25949953
Withdraw ETH Fro...191516722025-01-14 12:26:5419 hrs ago1736857614IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.00003410.143
Deposit ETH Into...191516492025-01-14 12:25:3319 hrs ago1736857533IN
0xDfB6BAA3...C2a87B1E8
0.026 ETH0.000034030.119
Withdraw Wei Fro...191399042025-01-14 0:35:5831 hrs ago1736814958IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000010930.0504
Withdraw ETH Fro...191317992025-01-13 16:59:3639 hrs ago1736787576IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000025040.105
Withdraw ETH Fro...191295422025-01-13 14:53:4241 hrs ago1736780022IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000421740.70375
Deposit Wei Into...191293802025-01-13 14:44:2241 hrs ago1736779462IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000308170.647
Withdraw Wei Fro...191291732025-01-13 14:31:3841 hrs ago1736778698IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000038210.162
Deposit ETH Into...191275472025-01-13 13:01:2243 hrs ago1736773282IN
0xDfB6BAA3...C2a87B1E8
0.011 ETH0.000060580.162
Withdraw Wei Fro...191274392025-01-13 12:55:1743 hrs ago1736772917IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000055240.156
Withdraw Wei Fro...191273002025-01-13 12:47:3543 hrs ago1736772455IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000075070.212
Deposit Wei Into...191232102025-01-13 8:59:3847 hrs ago1736758778IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000018120.06
Deposit ETH Into...191210332025-01-13 6:59:452 days ago1736751585IN
0xDfB6BAA3...C2a87B1E8
0.0001 ETH0.000009880.0408
Deposit ETH Into...191205852025-01-13 6:34:072 days ago1736750047IN
0xDfB6BAA3...C2a87B1E8
0.015 ETH0.000097050.25949953
Deposit Wei Into...191169452025-01-13 3:13:142 days ago1736737994IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000016560.06
Withdraw ETH Fro...191166562025-01-13 2:57:032 days ago1736737023IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000009510.0399
Withdraw ETH Fro...191166472025-01-13 2:56:322 days ago1736736992IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000009850.0413
Withdraw ETH Fro...191166142025-01-13 2:54:372 days ago1736736877IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000010320.0433
Withdraw ETH Fro...191166052025-01-13 2:54:072 days ago1736736847IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000010250.043
Withdraw ETH Fro...191165972025-01-13 2:53:412 days ago1736736821IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000011250.0472
Withdraw ETH Fro...191165892025-01-13 2:53:152 days ago1736736795IN
0xDfB6BAA3...C2a87B1E8
0 ETH0.000011090.0465

Latest 25 internal transactions (View All)

Parent Transaction Hash Block From To
191556282025-01-14 16:07:2416 hrs ago1736870844
0xDfB6BAA3...C2a87B1E8
0.015 ETH
191556282025-01-14 16:07:2416 hrs ago1736870844
0xDfB6BAA3...C2a87B1E8
0.015 ETH
191548202025-01-14 15:21:0216 hrs ago1736868062
0xDfB6BAA3...C2a87B1E8
0.01030453 ETH
191548202025-01-14 15:21:0216 hrs ago1736868062
0xDfB6BAA3...C2a87B1E8
0.01030453 ETH
191516722025-01-14 12:26:5419 hrs ago1736857614
0xDfB6BAA3...C2a87B1E8
0.026 ETH
191516722025-01-14 12:26:5419 hrs ago1736857614
0xDfB6BAA3...C2a87B1E8
0.026 ETH
191516492025-01-14 12:25:3319 hrs ago1736857533
0xDfB6BAA3...C2a87B1E8
0.026 ETH
191317992025-01-13 16:59:3639 hrs ago1736787576
0xDfB6BAA3...C2a87B1E8
0.02461205 ETH
191317992025-01-13 16:59:3639 hrs ago1736787576
0xDfB6BAA3...C2a87B1E8
0.02461205 ETH
191295422025-01-13 14:53:4241 hrs ago1736780022
0xDfB6BAA3...C2a87B1E8
10.0000002 ETH
191295422025-01-13 14:53:4241 hrs ago1736780022
0xDfB6BAA3...C2a87B1E8
10.0000002 ETH
191275472025-01-13 13:01:2243 hrs ago1736773282
0xDfB6BAA3...C2a87B1E8
0.011 ETH
191210332025-01-13 6:59:452 days ago1736751585
0xDfB6BAA3...C2a87B1E8
0.0001 ETH
191205852025-01-13 6:34:072 days ago1736750047
0xDfB6BAA3...C2a87B1E8
0.015 ETH
191166562025-01-13 2:57:032 days ago1736737023
0xDfB6BAA3...C2a87B1E8
0.00300147 ETH
191166562025-01-13 2:57:032 days ago1736737023
0xDfB6BAA3...C2a87B1E8
0.00300147 ETH
191166472025-01-13 2:56:322 days ago1736736992
0xDfB6BAA3...C2a87B1E8
0.00600294 ETH
191166472025-01-13 2:56:322 days ago1736736992
0xDfB6BAA3...C2a87B1E8
0.00600294 ETH
191166142025-01-13 2:54:372 days ago1736736877
0xDfB6BAA3...C2a87B1E8
0.00900441 ETH
191166142025-01-13 2:54:372 days ago1736736877
0xDfB6BAA3...C2a87B1E8
0.00900441 ETH
191166052025-01-13 2:54:072 days ago1736736847
0xDfB6BAA3...C2a87B1E8
0.00800392 ETH
191166052025-01-13 2:54:072 days ago1736736847
0xDfB6BAA3...C2a87B1E8
0.00800392 ETH
191165972025-01-13 2:53:412 days ago1736736821
0xDfB6BAA3...C2a87B1E8
0.00700343 ETH
191165972025-01-13 2:53:412 days ago1736736821
0xDfB6BAA3...C2a87B1E8
0.00700343 ETH
191165892025-01-13 2:53:152 days ago1736736795
0xDfB6BAA3...C2a87B1E8
0.00480235 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
DepositWithdrawalProxy

Compiler Version
v0.5.16+commit.9c3226ce

Optimization Enabled:
Yes with 10000 runs

Other Settings:
default evmVersion
File 1 of 31 : DepositWithdrawalProxy.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 { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";

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

import { OnlyDolomiteMargin } from "../helpers/OnlyDolomiteMargin.sol";
import { AccountActionLib } from "../lib/AccountActionLib.sol";
import { AccountBalanceLib } from "../lib/AccountBalanceLib.sol";

import { IDepositWithdrawalProxy } from "../interfaces/IDepositWithdrawalProxy.sol";
import { IWETH } from "../interfaces/IWETH.sol";


/**
 * @title DepositWithdrawalProxy
 * @author Dolomite
 *
 * @dev Contract for depositing or withdrawing to/from Dolomite easily. This lowers gas costs on Arbitrum by minimizing
 *      callData
 */
contract DepositWithdrawalProxy is IDepositWithdrawalProxy, OnlyDolomiteMargin, ReentrancyGuard {
    using Address for address payable;

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

    bytes32 private constant FILE = "DepositWithdrawalProxy";

    // ============ Field Variables ============

    IWETH WETH;
    uint256 ETH_MARKET_ID;
    bool g_initialized;

    // ============ Modifiers ============

    modifier requireIsInitialized() {
        Require.that(
            g_initialized,
            FILE,
            "not initialized"
        );
        _;
    }

    // ============ Constructor ============

    constructor (
        address _dolomiteMargin
    )
    public
    OnlyDolomiteMargin(_dolomiteMargin)
    {}

    // ============ External Functions ============

    function() external payable {
        Require.that(
            msg.sender == address(WETH),
            FILE,
            "invalid ETH sender"
        );
    }

    function initializeETHMarket(
        address payable _weth
    ) external {
        Require.that(
            !g_initialized,
            FILE,
            "already initialized"
        );
        g_initialized = true;
        WETH = IWETH(_weth);
        ETH_MARKET_ID = DOLOMITE_MARGIN.getMarketIdByTokenAddress(_weth);
        WETH.approve(address(DOLOMITE_MARGIN), uint(-1));
    }

    function depositWei(
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountWei
    )
    external
    nonReentrant {
        AccountActionLib.deposit(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccount = */ msg.sender, // solium-disable-line indentation
            _toAccountNumber,
            _marketId,
            Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: _amountWei == uint(-1) ? _getSenderBalance(_marketId) : _amountWei
            })
        );
    }

    function depositETH(
        uint256 _toAccountNumber
    )
    external
    payable
    requireIsInitialized
    nonReentrant {
        _wrap();
        AccountActionLib.deposit(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccount = */ address(this), // solium-disable-line indentation
            _toAccountNumber,
            ETH_MARKET_ID,
            Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: msg.value
            })
        );
    }

    function depositWeiIntoDefaultAccount(
        uint256 _marketId,
        uint256 _amountWei
    )
    external
    nonReentrant {
        AccountActionLib.deposit(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccount = */ msg.sender, // solium-disable-line indentation
            /* _toAccountNumber = */ 0, // solium-disable-line indentation
            _marketId,
            Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: _amountWei == uint(-1) ? _getSenderBalance(_marketId) : _amountWei
            })
        );
    }

    function depositETHIntoDefaultAccount()
    external
    payable
    requireIsInitialized
    nonReentrant {
        _wrap();
        AccountActionLib.deposit(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccount = */ address(this), // solium-disable-line indentation
            /* _toAccountNumber = */ 0, // solium-disable-line indentation
            ETH_MARKET_ID,
            Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: msg.value
            })
        );
    }

    function withdrawWei(
        uint256 _fromAccountNumber,
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    )
    external
    nonReentrant {
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            _fromAccountNumber,
            /* _toAccount = */ msg.sender, // solium-disable-line indentation
            _marketId,
            Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: _amountWei == uint(-1) ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountWei == uint(-1) ? 0 : _amountWei
            }),
            _balanceCheckFlag
        );
    }

    function withdrawETH(
        uint256 _fromAccountNumber,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    )
    external
    requireIsInitialized
    nonReentrant {
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            _fromAccountNumber,
            /* _toAccount = */ address(this), // solium-disable-line indentation
            ETH_MARKET_ID,
            Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: _amountWei == uint(-1) ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountWei == uint(-1) ? 0 : _amountWei
            }),
            _balanceCheckFlag
        );
        _unwrapAndSend();
    }

    function withdrawWeiFromDefaultAccount(
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    )
    external
    nonReentrant {
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccountNumber = */ 0, // solium-disable-line indentation
            /* _toAccount = */ msg.sender, // solium-disable-line indentation
            _marketId,
            Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: _amountWei == uint(-1) ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountWei == uint(-1) ? 0 : _amountWei
            }),
            _balanceCheckFlag
        );
    }

    function withdrawETHFromDefaultAccount(
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    )
    external
    requireIsInitialized
    nonReentrant {
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccountNumber = */ 0, // solium-disable-line indentation
            /* _toAccount = */ address(this), // solium-disable-line indentation
            ETH_MARKET_ID,
            Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: _amountWei == uint(-1) ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountWei == uint(-1) ? 0 : _amountWei
            }),
            _balanceCheckFlag
        );
        _unwrapAndSend();
    }

    // ========================= Par Functions =========================

    function depositPar(
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountPar
    )
    external
    nonReentrant {
        AccountActionLib.deposit(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccount = */ msg.sender, // solium-disable-line indentation
            _toAccountNumber,
            _marketId,
            Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Par,
                ref: Types.AssetReference.Delta,
                value: _amountPar
            })
        );
    }

    function depositParIntoDefaultAccount(
        uint256 _marketId,
        uint256 _amountPar
    )
    external
    nonReentrant {
        AccountActionLib.deposit(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccount = */ msg.sender, // solium-disable-line indentation
            /* _toAccountNumber = */ 0, // solium-disable-line indentation
            _marketId,
            Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Par,
                ref: Types.AssetReference.Delta,
                value: _amountPar
            })
        );
    }

    function withdrawPar(
        uint256 _fromAccountNumber,
        uint256 _marketId,
        uint256 _amountPar,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    )
    external
    nonReentrant {
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            _fromAccountNumber,
            /* _toAccount = */ msg.sender, // solium-disable-line indentation
            _marketId,
            Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Par,
                ref: _amountPar == uint(-1) ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountPar == uint(-1) ? 0 : _amountPar
            }),
            _balanceCheckFlag
        );
    }

    function withdrawParFromDefaultAccount(
        uint256 _marketId,
        uint256 _amountPar,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    )
    external
    nonReentrant {
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN,
            /* _accountOwner = */ msg.sender, // solium-disable-line indentation
            /* _fromAccountNumber = */ 0, // solium-disable-line indentation
            /* _toAccount = */ msg.sender, // solium-disable-line indentation
            _marketId,
            Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Par,
                ref: _amountPar == uint(-1) ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountPar == uint(-1) ? 0 : _amountPar
            }),
            _balanceCheckFlag
        );
    }

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

    function _wrap() internal {
        WETH.deposit.value(msg.value)();
    }

    function _unwrapAndSend() internal {
        IWETH _WETH = WETH;
        uint amount = _WETH.balanceOf(address(this));
        _WETH.withdraw(amount);
        msg.sender.sendValue(amount);
    }

    function _getSenderBalance(uint256 _marketId) internal view returns (uint) {
        return IERC20(DOLOMITE_MARGIN.getMarketTokenAddress(_marketId)).balanceOf(msg.sender);
    }
}

File 2 of 31 : 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 ============

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

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

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

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

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

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

    function unsetBit(
        uint256 bitmap,
        uint256 bit
    ) internal pure returns (uint256) {
        return bitmap & ~(ONE << bit);
    }

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

        uint256 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 3 of 31 : 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 31 : 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 5 of 31 : 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) ============

    struct TotalWei {
        uint128 borrow;
        uint128 supply;
    }

    // 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 6 of 31 : 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 7 of 31 : 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 8 of 31 : 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 { IAccountRiskOverrideSetter } from "../interfaces/IAccountRiskOverrideSetter.sol";
import { IERC20Detailed } from "../interfaces/IERC20Detailed.sol";
import { IInterestSetter } from "../interfaces/IInterestSetter.sol";
import { IOracleSentinel } from "../interfaces/IOracleSentinel.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 private 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;

        // 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 liquidationSpreadPremium;

        // 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 maxSupplyWei;

        // The maximum amount that can be borrowed 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 greater than 0.
        Types.Wei maxBorrowWei;

        // The percentage of interest paid that is passed along from borrowers to suppliers. Setting this to 0 will
        // default to RiskParams.earningsRate.
        Decimal.D256 earningsRateOverride;
    }

    // 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 oracle sentinel used to disable borrowing/liquidations if the sequencer goes down
        IOracleSentinel oracleSentinel;

        // The gas limit used for making callbacks via `IExternalCallback::onInternalBalanceChange` to smart contract
        // wallets. Setting to 0 will effectively disable callbacks; setting it super large is not desired since it
        // could lead to DOS attacks on the protocol; however, hard coding a max value isn't preferred since some chains
        // can calculate gas usage differently (like ArbGas before Arbitrum rolled out nitro)
        uint256 callbackGasLimit;

        // The default account risk override setter. By default, we ping this for any overrides in risk controls,
        // if the `accountRiskOverrideSetterMap` resolves to 0x0. If this value is set to `0x0` there is no default.
        IAccountRiskOverrideSetter defaultAccountRiskOverrideSetter;

        // Certain addresses are allowed to borrow with different LTV requirements. When an account's risk is overrode,
        // the global risk parameters are ignored and the account's risk parameters are used instead.
        mapping(address => IAccountRiskOverrideSetter) accountRiskOverrideSetterMap;
    }

    // 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 liquidationSpreadPremiumMax;
        // The highest that the borrow interest rate can ever be. If the rate returned is ever higher, the rate is
        // capped at this value instead of reverting. The goal is to keep Dolomite operational under all circumstances
        // instead of inadvertently DOS'ing the protocol.
        uint96 interestRateMax;
        // The highest that the minBorrowedValue can be. This is the minimum amount of value that must be borrowed.
        // Typically a value of $100 (100 * 1e18) is more than sufficient.
        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;

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

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

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

        // Addresses of auto traders that can only be called by global operators. IE for expirations
        mapping (address => uint256) 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 getMaxSupplyWei(
        Storage.State storage state,
        uint256 marketId
    )
        internal
        view
        returns (Types.Wei memory)
    {
        return state.markets[marketId].maxSupplyWei;
    }

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

    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 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 getLiquidationSpreadForAccountAndPair(
        Storage.State storage state,
        Account.Info memory account,
        uint256 heldMarketId,
        uint256 owedMarketId
    )
        internal
        view
        returns (Decimal.D256 memory)
    {
        (, Decimal.D256 memory liquidationSpreadOverride) = getAccountRiskOverride(state, account);
        if (liquidationSpreadOverride.value != 0) {
            return liquidationSpreadOverride;
        }

        uint256 result = state.riskParams.liquidationSpread.value;
        result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].liquidationSpreadPremium));
        result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].liquidationSpreadPremium));
        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);

        Decimal.D256 memory earningsRate = state.markets[marketId].earningsRateOverride;
        if (earningsRate.value == 0) {
            // The earnings rate was not override, fall back to the global one
            earningsRate = state.riskParams.earningsRate;
        }

        return Interest.calculateNewIndex(
            index,
            rate,
            state.getTotalPar(marketId),
            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
        );

        if (rate.value > state.riskLimits.interestRateMax) {
            // Cap the interest rate at the max instead of reverting. We don't want to DOS the protocol
            rate.value = state.riskLimits.interestRateMax;
        }

        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;
    }

    // solium-disable-next-line security/no-assign-params
    function getAccountValues(
        Storage.State storage state,
        Account.Info memory account,
        Cache.MarketCache memory cache,
        bool adjustForLiquidity,
        Decimal.D256 memory marginRatioOverride
    )
        internal
        view
        returns (Monetary.Value memory, Monetary.Value memory)
    {
        Monetary.Value memory supplyValue;
        Monetary.Value memory borrowValue;

        // Only adjust for liquidity if prompted AND if there is no override
        adjustForLiquidity = adjustForLiquidity && marginRatioOverride.value == 0;

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

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

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

            uint256 assetValue = userWei.value.mul(cache.getAtIndex(i).price.value);
            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, if there isn't a margin ratio override)
        (Decimal.D256 memory marginRatio,) = getAccountRiskOverride(state, account);
        (
            Monetary.Value memory supplyValue,
            Monetary.Value memory borrowValue
        ) = state.getAccountValues(
            account,
            cache,
            /* adjustForLiquidity = */ true,
            marginRatio
        );

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

        if (marginRatio.value == 0) {
            marginRatio = state.riskParams.marginRatio;
        }

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

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

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

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

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

    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
        );
    }

    function getAccountRiskOverride(
        Storage.State storage state,
        Account.Info memory account
    )
        internal
        view
        returns (Decimal.D256 memory marginRatioOverride, Decimal.D256 memory liquidationSpreadOverride)
    {
        IAccountRiskOverrideSetter riskOverrideSetter = state.riskParams.accountRiskOverrideSetterMap[account.owner];
        if (address(riskOverrideSetter) != address(0)) {
            (marginRatioOverride, liquidationSpreadOverride) = riskOverrideSetter.getAccountRiskOverride(account);
            validateAccountRiskOverrideValues(state, marginRatioOverride, liquidationSpreadOverride);
            return (marginRatioOverride, liquidationSpreadOverride);
        }

        riskOverrideSetter = state.riskParams.defaultAccountRiskOverrideSetter;
        if (address(riskOverrideSetter) != address(0)) {
            (marginRatioOverride, liquidationSpreadOverride) = riskOverrideSetter.getAccountRiskOverride(account);
            validateAccountRiskOverrideValues(state, marginRatioOverride, liquidationSpreadOverride);
            return (marginRatioOverride, liquidationSpreadOverride);
        } else {
            marginRatioOverride = Decimal.zero();
            liquidationSpreadOverride = Decimal.zero();
            return (marginRatioOverride, liquidationSpreadOverride);
        }
    }

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

    function validateAccountRiskOverrideValues(
        Storage.State storage state,
        Decimal.D256 memory marginRatioOverride,
        Decimal.D256 memory liquidationSpreadOverride
    ) internal view {
        Require.that(
            marginRatioOverride.value <= state.riskLimits.marginRatioMax,
            FILE,
            "Ratio too high"
        );
        Require.that(
            liquidationSpreadOverride.value <= state.riskLimits.liquidationSpreadMax,
            FILE,
            "Spread too high"
        );

        if (marginRatioOverride.value != 0 && liquidationSpreadOverride.value != 0) {
            Require.that(
                liquidationSpreadOverride.value < marginRatioOverride.value,
                FILE,
                "Spread cannot be >= ratio"
            );
        } else {
            Require.that(
                liquidationSpreadOverride.value == 0 && marginRatioOverride.value == 0,
                FILE,
                "Spread and ratio must both be 0"
            );
        }
    }

    // =============== 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,
        bool fetchFreshIndex
    ) internal view {
        cache.markets = new Cache.MarketInfo[](cache.marketsLength);

        // 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
        uint256 marketBitmapsLength = cache.marketBitmaps.length;
        for (uint256 i; i < marketBitmapsLength; ++i) {
            uint256 bitmap = cache.marketBitmaps[i];
            while (bitmap != 0) {
                uint256 nextSetBit = Bits.getLeastSignificantBit(bitmap);
                uint256 marketId = Bits.getMarketIdFromBit(i, nextSetBit);
                address token = state.getToken(marketId);
                Types.TotalPar memory totalPar = state.getTotalPar(marketId);
                Interest.Index memory index = state.getIndex(marketId);
                cache.markets[cache.counter++] = Cache.MarketInfo({
                    marketId: marketId,
                    token: token,
                    isClosing: state.markets[marketId].isClosing,
                    borrowPar: totalPar.borrow,
                    supplyPar: totalPar.supply,
                    index: fetchFreshIndex ? state.fetchNewIndex(marketId, index) : index,
                    price: state.fetchPrice(marketId, token)
                });

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

        assert(cache.marketsLength == cache.counter);
    }
}

File 9 of 31 : 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
    )
        internal
        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; 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; 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 10 of 31 : 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 11 of 31 : 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 private constant FILE = "Interest";
    uint64 constant BASE = 10**18;

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

    struct Rate {
        uint256 value;
    }

    struct Index {
        uint112 borrow;
        uint112 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).to112(),
            supply: DolomiteMarginMath.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to112(),
            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 12 of 31 : 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 13 of 31 : 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 private 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 to112(
        uint256 number
    )
        internal
        pure
        returns (uint112)
    {
        uint112 result = uint112(number);
        Require.that(
            result == number,
            FILE,
            "Unsafe cast to uint112",
            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 14 of 31 : 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 zero()
        internal
        pure
        returns (D256 memory)
    {
        return D256({ value: 0 });
    }

    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 15 of 31 : 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 private 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 counter; // used for iterating through the bitmaps and incrementing
        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),
            counter: 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 >> 1);
        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 16 of 31 : 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 17 of 31 : 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 private 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;
        bool calculateAmountWithMakerAccount;
        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)
    {
        (bool calculateAmountWithMakerAccount, bytes memory tradeData) = abi.decode(args.data, (bool, bytes));
        return TradeArgs({
            amount: args.amount,
            calculateAmountWithMakerAccount: calculateAmountWithMakerAccount,
            takerAccount: accounts[args.accountId],
            makerAccount: accounts[args.otherAccountId],
            inputMarket: args.primaryMarketId,
            outputMarket: args.secondaryMarketId,
            autoTrader: args.otherAddress,
            tradeData: tradeData
        });
    }

    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 18 of 31 : 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 19 of 31 : 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 20 of 31 : IOracleSentinel.sol
/*

    Copyright 2023 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;


/**
 * @title IOracleSentinel
 * @author Dolomite
 *
 * Interface that Dolomite pings to check if the Blockchain or L2 is alive, if liquidations should be processed, and if
 * markets should are in size-down only mode.
 */
contract IOracleSentinel {

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

    event GracePeriodSet(
        uint256 gracePeriod
    );

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

    /**
     * @dev Allows the owner to set the grace period duration, which specifies how long the system will disallow
     *      liquidations after sequencer is back online. Only callable by the owner.
     *
     * @param _gracePeriod  The new duration of the grace period
     */
    function ownerSetGracePeriod(
        uint256 _gracePeriod
    )
        external;

    /**
     * @return True if new borrows should be allowed, false otherwise
     */
    function isBorrowAllowed() external view returns (bool);

    /**
     * @return True if liquidations should be allowed, false otherwise
     */
    function isLiquidationAllowed() external view returns (bool);

    /**
     * @return  The duration between when the feed comes back online and when the system will allow liquidations to be
     *          processed normally
     */
    function gracePeriod() external view returns (uint256);
}

File 21 of 31 : 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 22 of 31 : 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 23 of 31 : 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 { IAccountRiskOverrideSetter } from "../interfaces/IAccountRiskOverrideSetter.sol";
import { IInterestSetter } from "../interfaces/IInterestSetter.sol";
import { IOracleSentinel } from "../interfaces/IOracleSentinel.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 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 minimum margin-ratio that every position must maintain to prevent being
     * liquidated.
     *
     * @param account       The account whose margin ratio is being queried. This is used to determine if there is an
     *                      override that supersedes the global minimum.
     * @return  The margin ratio for this account
     */
    function getMarginRatioForAccount(Account.Info calldata account) 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.
     *
     * Assumes the pair is not in e-mode. Backwards compatible with V1.
     *
     * @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 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.
     *
     * If the pair is in e-mode and has a liquidation spread override, then the override is used instead.
     *
     * @param  account      The account whose liquidation spread is being queried. This is used to determine if there is
     *                      an override in place.
     * @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 getLiquidationSpreadForAccountAndPair(
        Account.Info calldata account,
        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 the maximum number of assets an account owner can hold in an account number.
     *
     * @return  The maximum number of assets an account owner can hold in an account number.
     */
    function getAccountMaxNumberOfMarketsWithBalances() external view returns (uint256);

    /**
     * Gets the oracle sentinel, which is responsible for checking if the Blockchain or L2 is alive, if liquidations
     * should be processed, and if markets should are in size-down only mode.
     *
     * @return The oracle sentinel for DolomiteMargin
     */
    function getOracleSentinel() external view returns (IOracleSentinel);

    /**
     * @return True if borrowing is globally allowed according to the Oracle Sentinel or false if it is not
     */
    function getIsBorrowAllowed() external view returns (bool);

    /**
     * @return True if liquidations are globally allowed according to the Oracle Sentinel or false if they are not
     */
    function getIsLiquidationAllowed() external view returns (bool);

    /**
     * @return  The gas limit used for making callbacks via `IExternalCallback::onInternalBalanceChange` to smart
     *          contract wallets.
     */
    function getCallbackGasLimit() external view returns (uint256);

    /**
     * Get the account risk override getter for global use. This contract enables e-mode based on the assets held in a
     * position.
     *
     * @return  The contract that contains risk override information for any account that does NOT have an account-
     *          specific override.
     */
    function getDefaultAccountRiskOverrideSetter() external view returns (IAccountRiskOverrideSetter);

    /**
     * Get the account risk override getter for an account owner. This contract enables e-mode for certain isolation
     * mode vaults.
     *
     * @param accountOwner  The address of the account to check if there is a margin ratio override.
     * @return  The contract that contains risk override information for this account.
     */
    function getAccountRiskOverrideSetterByAccountOwner(
        address accountOwner
    ) external view returns (IAccountRiskOverrideSetter);

    /**
     * Get the margin ratio override for an account owner. Used to enable e-mode for certain isolation mode vaults.
     *
     * @param account                       The account to check if there is a risk override.
     * @return marginRatioOverride          The margin ratio override for an account owner. Defaults to 0 if there's no
     *                                      override in place.
     * @return liquidationSpreadOverride    The margin ratio override for an account owner. Defaults to 0 if there's no
     *                                      override in place.
     */
    function getAccountRiskOverrideByAccount(
        Account.Info calldata account
    )
    external
    view
    returns (Decimal.D256 memory marginRatioOverride, Decimal.D256 memory liquidationSpreadOverride);

    /**
     * Get the margin ratio override for an account. Used to enable e-mode for certain accounts/positions.
     *
     * @param account   The account to check if there is a margin ratio override.
     * @return  The margin ratio override for an account owner. Defaults to 0 if there's no override in place.
     */
    function getMarginRatioOverrideByAccount(Account.Info calldata account) external view returns (Decimal.D256 memory);

    /**
     * Get the liquidation reward override for an account owner. Used to enable e-mode for certain isolation mode
     * vaults.
     *
     * @param account   The account to check if there is a liquidation spread override.
     * @return  The liquidation spread override for an account owner. Defaults to 0 if there's no override in place.
     */
    function getLiquidationSpreadOverrideByAccount(
        Account.Info calldata account
    ) external view returns (Decimal.D256 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);

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

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

    /**
     * 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 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 total principal amounts (borrowed and supplied) for a market.
     *
     * @param  marketId  The market to query
     * @return           The total principal amounts
     */
    function getMarketTotalWei(
        uint256 marketId
    ) external view returns (Types.TotalWei 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 getMarketLiquidationSpreadPremium(
        uint256 marketId
    ) external view returns (Decimal.D256 memory);

    /**
     * Same as getMarketLiquidationSpreadPremium. Added for backwards-compatibility.
     *
     * @param  marketId  The market to query
     * @return           The market's spread premium
     */
    function getMarketSpreadPremium(
        uint256 marketId
    ) external view returns (Decimal.D256 memory);

    /**
     * Same as getMarketMaxSupplyWei. Added for backwards-compatibility.
     *
     * @param  marketId  The market to query
     * @return           The max amount of the market that can be supplied. Always 0 or positive.
     */
    function getMarketMaxWei(
        uint256 marketId
    )
    external
    view
    returns (Types.Wei memory);

    /**
     * Get the max supply amount for a a market.
     *
     * @param  marketId  The market to query
     * @return           The market's max supply amount. Always 0 or positive.
     */
    function getMarketMaxSupplyWei(
        uint256 marketId
    )
    external
    view
    returns (Types.Wei memory);

    /**
     * Get the max borrow amount for a a market.
     *
     * @param  marketId  The market to query
     * @return           The market's max borrow amount. Always negative or 0.
     */
    function getMarketMaxBorrowWei(
        uint256 marketId
    )
    external
    view
    returns (Types.Wei memory);

    /**
     * Get the market-specific earnings that determines what percentage of the interest paid by borrowers gets passed-on
     * to suppliers. If the value is set to 0, the override is not set.
     *
     * @return  The market-specific earnings rate
     */
    function getMarketEarningsRateOverride(
        uint256 marketId
    )
    external
    view
    returns (Decimal.D256 memory);

    /**
     * Get the current borrow interest rate for a market. The value is denominated as interest paid per second, and the
     * number is scaled to have 18 decimals. To get APR, multiply the number returned by 31536000 (seconds in a year).
     *
     * @param  marketId  The market to query
     * @return           The current borrow interest rate
     */
    function getMarketBorrowInterestRatePerSecond(
        uint256 marketId
    ) external view returns (Interest.Rate memory);

    /**
     * Same as getMarketBorrowInterestRatePerSecond. Added for backwards-compatibility.
     *
     * @param  marketId  The market to query
     * @return           The current borrow interest rate
     */
    function getMarketInterestRate(
        uint256 marketId
    ) external view returns (Interest.Rate memory);

    /**
     * Get the current borrow interest rate for a market. The value is denominated as interest paid per year, and the
     * number is scaled to have 18 decimals.
     *
     * @param  marketId  The market to query
     * @return           The current supply interest rate
     */
    function getMarketBorrowInterestRateApr(
        uint256 marketId
    ) external view returns (Interest.Rate memory);

    /**
     * Get the current supply interest rate for a market.
     *
     * @param  marketId  The market to query
     * @return           The current supply interest rate
     */
    function getMarketSupplyInterestRateApr(
        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 borrow interest rate per second
     */
    function getMarketWithInfo(
        uint256 marketId
    )
    external
    view
    returns (
        Storage.Market memory,
        Interest.Index memory,
        Monetary.Price memory,
        Interest.Rate memory
    );

    /**
     * Get the number of tokens that are owed to the `owner` of DolomiteMargin. 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 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 number of markets with a 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 market ID in the provided index 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 number of markets with a negative balance for this 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);

    // ============ 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;

    // =========================================
    // ============ Owner Functions ============
    // =========================================

    // ============ 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
    )
    external
    returns (uint256);

    /**
     * Withdraw an ERC20 token for which there is no associated market.
     */
    function ownerWithdrawUnsupportedTokens(
        address token,
        address recipient
    )
    external
    returns (uint256);

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

    /**
     * Add a new market to DolomiteMargin. Must be for a previously-unsupported ERC20 token.
     */
    function ownerAddMarket(
        address token,
        IPriceOracle priceOracle,
        IInterestSetter interestSetter,
        Decimal.D256 calldata marginPremium,
        Decimal.D256 calldata spreadPremium,
        uint256 maxSupplyWei,
        uint256 maxBorrowWei,
        Decimal.D256 calldata earningsRateOverride,
        bool isClosing
    )
    external;

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

    /**
     * Set the price oracle for a market.
     */
    function ownerSetPriceOracle(
        uint256 marketId,
        IPriceOracle priceOracle
    )
    external;

    /**
     * Set the interest-setter for a market.
     */
    function ownerSetInterestSetter(
        uint256 marketId,
        IInterestSetter interestSetter
    )
    external;

    /**
     * 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 calldata marginPremium
    )
    external;

    /**
     * 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 ownerSetLiquidationSpreadPremium(
        uint256 marketId,
        Decimal.D256 calldata liquidationSpreadPremium
    )
    external;

    /**
     * Sets the maximum supply wei for a given `marketId`.
     */
    function ownerSetMaxSupplyWei(
        uint256 marketId,
        uint256 maxSupplyWei
    )
    external;

    /**
     * Sets the maximum borrow wei for a given `marketId`.
     */
    function ownerSetMaxBorrowWei(
        uint256 marketId,
        uint256 maxBorrowWei
    )
    external;

    /**
     * Sets the earnings rate override for a given `marketId`. Set it to 0 unset the override.
     */
    function ownerSetEarningsRateOverride(
        uint256 marketId,
        Decimal.D256 calldata earningsRateOverride
    )
    external;

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

    /**
     * Set the global minimum margin-ratio that every position must maintain to prevent being liquidated.
     */
    function ownerSetMarginRatio(
        Decimal.D256 calldata ratio
    )
    external;

    /**
     * Set the global liquidation spread. This is the spread between oracle prices that incentivizes the liquidation of
     * risky positions.
     */
    function ownerSetLiquidationSpread(
        Decimal.D256 calldata spread
    )
    external;

    /**
     * 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 calldata earningsRate
    )
    external;

    /**
     * Set the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
     */
    function ownerSetMinBorrowedValue(
        Monetary.Value calldata minBorrowedValue
    )
    external;

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

    /**
     * Sets the current oracle sentinel used to report if borrowing and liquidations are enabled.
     */
    function ownerSetOracleSentinel(
        IOracleSentinel oracleSentinel
    )
    external;

    /**
     * Sets the gas limit that's passed to any of the callback functions
     */
    function ownerSetCallbackGasLimit(
        uint256 callbackGasLimit
    )
    external;

    /**
     * Sets the account risk override setter by default for any account
     */
    function ownerSetDefaultAccountRiskOverride(
        IAccountRiskOverrideSetter accountRiskOverrideSetter
    )
    external;

    /**
     * Sets the account risk override setter for a given wallet
     */
    function ownerSetAccountRiskOverride(
        address accountOwner,
        IAccountRiskOverrideSetter accountRiskOverrideSetter
    )
    external;

    // ============ 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
    )
    external;

    /**
     * Approve (or disapprove) an auto trader that can only be called by a global operator. IE for expirations
     */
    function ownerSetAutoTraderSpecial(
        address autoTrader,
        bool special
    )
    external;

    // ============ Owner Functions ============

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() external view returns (address);

    /**
     * @dev Returns true if the caller is the current owner.
     */
    function isOwner() external view returns (bool);

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

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

File 24 of 31 : IAccountRiskOverrideSetter.sol
/*

    Copyright 2023 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 { Account } from "../lib/Account.sol";
import { Decimal } from "../lib/Decimal.sol";


/**
 * @title IAccountRiskOverrideSetter
 * @author Dolomite
 *
 * @notice Interface that can be implemented by any contract that needs to implement risk overrides for an account.
 */
interface IAccountRiskOverrideSetter {

    /**
     * @notice  Gets the risk overrides for a given account owner.
     *
     * @param   _account                    The account whose risk override should be retrieved.
     * @return  marginRatioOverride         The margin ratio override for this account.
     * @return  liquidationSpreadOverride   The liquidation spread override for this account.
     */
    function getAccountRiskOverride(
        Account.Info calldata _account
    )
        external
        view
        returns
    (
        Decimal.D256 memory marginRatioOverride,
        Decimal.D256 memory liquidationSpreadOverride
    );
}

File 25 of 31 : 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 26 of 31 : AccountBalanceLib.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 { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";

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


/**
 * @title AccountBalanceLib
 * @author Dolomite
 *
 * Library contract that checks a user's balance after an operation to be non-negative
 */
library AccountBalanceLib {
    using Types for Types.Par;

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

    bytes32 private constant FILE = "AccountBalanceLib";

    // ============ Types ============

    /// Checks that either BOTH, FROM, or TO accounts do not have negative balances
    enum BalanceCheckFlag {
        Both,
        From,
        To,
        None
    }

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

    /**
     *  Checks that the account's balance is non-negative. Reverts if the check fails
     */
    function verifyBalanceIsNonNegative(
        IDolomiteMargin dolomiteMargin,
        address _owner,
        uint256 _accountIndex,
        uint256 _marketId
    ) internal view {
        Account.Info memory account = Account.Info(_owner, _accountIndex);
        Types.Par memory par = dolomiteMargin.getAccountPar(account, _marketId);
        Require.that(
            par.isPositive() || par.isZero(),
            FILE,
            "account cannot go negative",
            _owner,
            _accountIndex,
            _marketId
        );
    }
}

File 27 of 31 : AccountActionLib.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 { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";

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

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

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


/**
 * @title AccountActionLib
 * @author Dolomite
 *
 * Library contract that makes specific actions easy to call
 */
library AccountActionLib {

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

    bytes32 private constant FILE = "AccountActionLib";

    uint256 constant ALL = uint256(-1);

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

    function all() internal pure returns (uint256) {
        return ALL;
    }

    // ========================= Operation Functions =========================

    function deposit(
        IDolomiteMargin _dolomiteMargin,
        address _accountOwner,
        address _fromAccount,
        uint256 _toAccountNumber,
        uint256 _marketId,
        Types.AssetAmount memory _amount
    ) internal {
        Account.Info[] memory accounts = new Account.Info[](1);
        accounts[0] = Account.Info({
            owner: _accountOwner,
            number: _toAccountNumber
        });

        Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
        actions[0] = encodeDepositAction(
            /* _accountId = */ 0, // solium-disable-line indentation
            _marketId,
            _amount,
            _fromAccount
        );

        _dolomiteMargin.operate(accounts, actions);
    }

    /**
     *  Withdraws `_marketId` from `_fromAccount` to `_toAccount`
     */
    function withdraw(
        IDolomiteMargin _dolomiteMargin,
        address _accountOwner,
        uint256 _fromAccountNumber,
        address _toAccount,
        uint256 _marketId,
        Types.AssetAmount memory _amount,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) internal {
        Account.Info[] memory accounts = new Account.Info[](1);
        accounts[0] = Account.Info({
            owner: _accountOwner,
            number: _fromAccountNumber
        });

        Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
        actions[0] = encodeWithdrawalAction(
            /* _accountId = */ 0, // solium-disable-line indentation
            _marketId,
            _amount,
            _toAccount
        );

        _dolomiteMargin.operate(accounts, actions);

        if (
            _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.From
        ) {
            AccountBalanceLib.verifyBalanceIsNonNegative(
                _dolomiteMargin,
                accounts[0].owner,
                _fromAccountNumber,
                _marketId
            );
        }
    }

    /**
     * Transfers `_marketId` from `_fromAccount` to `_toAccount`
     */
    function transfer(
        IDolomiteMargin _dolomiteMargin,
        address _fromAccountOwner,
        uint256 _fromAccountNumber,
        address _toAccountOwner,
        uint256 _toAccountNumber,
        uint256 _marketId,
        Types.AssetAmount memory _amount,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) internal {
        Account.Info[] memory accounts = new Account.Info[](2);
        accounts[0] = Account.Info({
            owner: _fromAccountOwner,
            number: _fromAccountNumber
        });
        accounts[1] = Account.Info({
            owner: _toAccountOwner,
            number: _toAccountNumber
        });

        Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
        actions[0] = Actions.ActionArgs({
            actionType: Actions.ActionType.Transfer,
            accountId: 0,
            amount: _amount,
            primaryMarketId: _marketId,
            secondaryMarketId: 0,
            otherAddress: address(0),
            otherAccountId: 1,
            data: bytes("")
        });

        _dolomiteMargin.operate(accounts, actions);

        if (
            _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.From
        ) {
            AccountBalanceLib.verifyBalanceIsNonNegative(
                _dolomiteMargin,
                _fromAccountOwner,
                _fromAccountNumber,
                _marketId
            );
        }

        if (
            _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.To
        ) {
            AccountBalanceLib.verifyBalanceIsNonNegative(
                _dolomiteMargin,
                _toAccountOwner,
                _toAccountNumber,
                _marketId
            );
        }
    }

    // ========================= Encoding Functions =========================

    function encodeCallAction(
        uint256 _accountId,
        address _callee,
        bytes memory _callData
    ) internal pure returns (Actions.ActionArgs memory) {
        return Actions.ActionArgs({
            actionType : Actions.ActionType.Call,
            accountId : _accountId,
            amount : Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: 0
            }),
            primaryMarketId : 0,
            secondaryMarketId : 0,
            otherAddress : _callee,
            otherAccountId : 0,
            data : _callData
        });
    }

    function encodeDepositAction(
        uint256 _accountId,
        uint256 _marketId,
        Types.AssetAmount memory _amount,
        address _fromAccount
    ) internal pure returns (Actions.ActionArgs memory) {
        return Actions.ActionArgs({
            actionType: Actions.ActionType.Deposit,
            accountId: _accountId,
            amount: _amount,
            primaryMarketId: _marketId,
            secondaryMarketId: 0,
            otherAddress: _fromAccount,
            otherAccountId: 0,
            data: bytes("")
        });
    }

    function encodeExpirationAction(
        Account.Info memory _account,
        uint256 _accountId,
        uint256 _owedMarketId,
        address _expiry,
        uint32 _expiryTimeDelta
    ) internal pure returns (Actions.ActionArgs memory) {
        IExpiry.SetExpiryArg[] memory expiryArgs = new IExpiry.SetExpiryArg[](1);
        expiryArgs[0] = IExpiry.SetExpiryArg({
            account : _account,
            marketId : _owedMarketId,
            timeDelta : _expiryTimeDelta,
            forceUpdate : true
        });

        return encodeCallAction(
            _accountId,
            _expiry,
            abi.encode(IExpiry.CallFunctionType.SetExpiry, expiryArgs)
        );
    }

    function encodeExpiryLiquidateAction(
        uint256 _solidAccountId,
        uint256 _liquidAccountId,
        uint256 _owedMarketId,
        uint256 _heldMarketId,
        address _expiryProxy,
        uint32 _expiry,
        uint256 _solidHeldUpdateWithReward,
        uint256 _owedWeiToLiquidate,
        bool _flipMarkets
    ) internal pure returns (Actions.ActionArgs memory) {
        Types.AssetAmount memory assetAmount;
        if (!_flipMarkets) {
            // Make the amount positive so the liquid account's owedMarket goes up (gets repaid).
            assetAmount = Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: _owedWeiToLiquidate
            });
        } else {
            assert(_flipMarkets);
            // Make the amount negative so the liquid account's heldMarket goes down (gets spent to repay owedMarket).
            assetAmount = Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: _solidHeldUpdateWithReward
            });
        }

        return Actions.ActionArgs({
            actionType: Actions.ActionType.Trade,
            accountId: _solidAccountId,
            amount: assetAmount,
            primaryMarketId: !_flipMarkets ? _owedMarketId : _heldMarketId,
            secondaryMarketId: !_flipMarkets ? _heldMarketId : _owedMarketId,
            otherAddress: _expiryProxy,
            otherAccountId: _liquidAccountId,
            data: abi.encode(
                /* calculateAmountWithMakerAccount = */ true,
                abi.encode(_owedMarketId, _expiry)
            )
        });
    }

    function encodeInternalTradeActionWithCustomData(
        uint256 _fromAccountId,
        uint256 _toAccountId,
        uint256 _primaryMarketId,
        uint256 _secondaryMarketId,
        address _traderAddress,
        uint256 _amountInWei,
        bytes memory _orderData
    ) internal pure returns (Actions.ActionArgs memory) {
        // internal trades calculate inputAmount based on `_toAccountId` (the maker account), so the sign should be
        // positive to reflect this
        return Actions.ActionArgs({
            actionType: Actions.ActionType.Trade,
            accountId: _fromAccountId,
            amount: Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: _amountInWei == ALL ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value: _amountInWei == ALL ? 0 : _amountInWei
            }),
            primaryMarketId: _primaryMarketId,
            secondaryMarketId: _secondaryMarketId,
            otherAddress: _traderAddress,
            otherAccountId: _toAccountId,
            data: abi.encode(
                /* calculateAmountWithMakerAccount = */ false,
                _orderData
            )
        });
    }

    function encodeLiquidateAction(
        uint256 _solidAccountId,
        uint256 _liquidAccountId,
        uint256 _owedMarketId,
        uint256 _heldMarketId,
        uint256 _owedWeiToLiquidate
    ) internal pure returns (Actions.ActionArgs memory) {
        return Actions.ActionArgs({
            actionType: Actions.ActionType.Liquidate,
            accountId: _solidAccountId,
            amount: Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: _owedWeiToLiquidate
            }),
            primaryMarketId: _owedMarketId,
            secondaryMarketId: _heldMarketId,
            otherAddress: address(0),
            otherAccountId: _liquidAccountId,
            data: new bytes(0)
        });
    }

    function encodeExternalSellAction(
        uint256 _fromAccountId,
        uint256 _primaryMarketId,
        uint256 _secondaryMarketId,
        address _trader,
        uint256 _amountInWei,
        uint256 _amountOutMinWei,
        bytes memory _orderData
    ) internal pure returns (Actions.ActionArgs memory) {
        return Actions.ActionArgs({
            actionType : Actions.ActionType.Sell,
            accountId : _fromAccountId,
            amount : Types.AssetAmount({
                sign : false,
                denomination : Types.AssetDenomination.Wei,
                ref : _amountInWei == ALL ? Types.AssetReference.Target : Types.AssetReference.Delta,
                value : _amountInWei == ALL ? 0 : _amountInWei
            }),
            primaryMarketId : _primaryMarketId,
            secondaryMarketId : _secondaryMarketId,
            otherAddress : _trader,
            otherAccountId : 0,
            data : abi.encode(_amountOutMinWei, _orderData)
        });
    }

    function encodeTransferAction(
        uint256 _fromAccountId,
        uint256 _toAccountId,
        uint256 _marketId,
        uint256 _amountWei
    ) internal pure returns (Actions.ActionArgs memory) {
        Types.AssetAmount memory assetAmount;
        if (_amountWei == uint(- 1)) {
            assetAmount = Types.AssetAmount({
                sign: true,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Target,
                value: 0
            });
        } else {
            assetAmount = Types.AssetAmount({
                sign: false,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Delta,
                value: _amountWei
            });
        }
        return Actions.ActionArgs({
            actionType : Actions.ActionType.Transfer,
            accountId : _fromAccountId,
            amount : assetAmount,
            primaryMarketId : _marketId,
            secondaryMarketId : 0,
            otherAddress : address(0),
            otherAccountId : _toAccountId,
            data : bytes("")
        });
    }

    function encodeTransferToTargetAmountAction(
        uint256 _fromAccountId,
        uint256 _toAccountId,
        uint256 _marketId,
        Types.Wei memory _targetAmountWei
    ) internal pure returns (Actions.ActionArgs memory) {
        return Actions.ActionArgs({
            actionType : Actions.ActionType.Transfer,
            accountId : _fromAccountId,
            amount : Types.AssetAmount({
                sign: _targetAmountWei.sign,
                denomination: Types.AssetDenomination.Wei,
                ref: Types.AssetReference.Target,
                value: _targetAmountWei.value
            }),
            primaryMarketId : _marketId,
            secondaryMarketId : 0,
            otherAddress : address(0),
            otherAccountId : _toAccountId,
            data : bytes("")
        });
    }

    function encodeWithdrawalAction(
        uint256 _accountId,
        uint256 _marketId,
        Types.AssetAmount memory _amount,
        address _toAccount
    ) internal pure returns (Actions.ActionArgs memory) {
        return Actions.ActionArgs({
            actionType: Actions.ActionType.Withdraw,
            accountId: _accountId,
            amount: _amount,
            primaryMarketId: _marketId,
            secondaryMarketId: 0,
            otherAddress: _toAccount,
            otherAccountId: 0,
            data: bytes("")
        });
    }
}

File 28 of 31 : IWETH.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.4;


interface IWETH {

    function deposit() external payable;

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

    function withdraw(uint) external;

    function balanceOf(address) external view returns (uint);

    function approve(address spender, uint allowance) external returns (bool);
}

File 29 of 31 : IExpiry.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 { Account } from "../../protocol/lib/Account.sol";
import { Monetary } from "../../protocol/lib/Monetary.sol";


/**
 * @title IExpiry
 * @author Dolomite
 */
interface IExpiry {

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

    enum CallFunctionType {
        SetExpiry,
        SetApproval
    }

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

    struct SetExpiryArg {
        Account.Info account;
        uint256 marketId;
        uint32 timeDelta;
        bool forceUpdate;
    }

    struct SetApprovalArg {
        address sender;
        uint32 minTimeDelta;
    }

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

    function g_expiryRampTime() external view returns (uint256);

    function getLiquidationSpreadAdjustedPrices(
        Account.Info calldata liquidAccount,
        uint256 heldMarketId,
        uint256 owedMarketId,
        uint32 expiry
    )
        external
        view
        returns (Monetary.Price memory heldPrice, Monetary.Price memory owedPriceAdj);

    function getExpiry(
        Account.Info calldata account,
        uint256 marketId
    )
        external
        view
        returns (uint32);

}

File 30 of 31 : IDepositWithdrawalProxy.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;

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


interface IDepositWithdrawalProxy {

    /**
     * @param _toAccountNumber  The account number into which `msg.sender` will be depositing
     * @param _marketId         The ID of the market being deposited
     * @param _amountWei        The amount, in Wei, to deposit. Use `uint(-1)` to deposit `msg.sender`'s entire balance
     */
    function depositWei(
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountWei
    ) external;

    /**
     * Same as `depositWei` but converts the `msg.sender`'s sent ETH into WETH before depositing into `DolomiteMargin`.
     *
     * @param _toAccountNumber The account number into which `msg.sender` will be depositing
     */
    function depositETH(
        uint256 _toAccountNumber
    ) external payable;

    /**
     * @dev Same as `depositWei` but defaults to account number 0 to save additional call data
     *
     * @param _marketId     The ID of the market being deposited
     * @param _amountWei    The amount, in Wei, to deposit. Use `uint(-1)` to deposit `msg.sender`'s entire balance
     */
    function depositWeiIntoDefaultAccount(
        uint256 _marketId,
        uint256 _amountWei
    ) external;

    /**
     * Same as `depositWeiIntoDefaultAccount` but converts the `msg.sender`'s sent ETH into WETH before depositing into
     * `DolomiteMargin`.
     */
    function depositETHIntoDefaultAccount() external payable;

    /**
     * @param _fromAccountNumber    The account number from which `msg.sender` will be withdrawing
     * @param _marketId             The ID of the market being withdrawn
     * @param _amountWei            The amount, in Wei, to withdraw. Use `uint(-1)` to withdraw `msg.sender`'s entire
     *                              balance
     * @param _balanceCheckFlag     Use `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` to check that
     *                              `_fromAccountNumber` balance is non-negative after the withdrawal settles.
     */
    function withdrawWei(
        uint256 _fromAccountNumber,
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * Same as `withdrawWei` but for withdrawing ETH. The user will receive unwrapped ETH from DolomiteMargin.
     *
     * @param _fromAccountNumber    The account number from which `msg.sender` will be withdrawing
     * @param _amountWei            The amount, in Wei, to withdraw. Use `uint(-1)` to withdraw `msg.sender`'s entire
     *                              balance.
     * @param _balanceCheckFlag     Use `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` to check that
     *                              `_fromAccountNumber` balance is non-negative after the withdrawal settles.
     */
    function withdrawETH(
        uint256 _fromAccountNumber,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @dev Same as `withdrawWei` but defaults to account number 0 to save additional call data
     *
     * @param _marketId         The ID of the market being withdrawn
     * @param _amountWei        The amount, in Wei, to withdraw. Use `uint(-1)` to withdraw `msg.sender`'s entire
     *                          balance
     * @param _balanceCheckFlag Use `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` to check that `_fromAccountNumber`
     *                          balance is non-negative after the withdrawal settles.
     */
    function withdrawWeiFromDefaultAccount(
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * Same as `withdrawWeiFromDefaultAccount` but for withdrawing ETH. The user will receive unwrapped ETH from
     * DolomiteMargin.
     *
     * @param _amountWei        The amount, in Wei, to withdraw. Use `uint(-1)` to withdraw `msg.sender`'s entire
     *                          balance
     * @param _balanceCheckFlag Use `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` to check that `_fromAccountNumber`
     *                          balance is non-negative after the withdrawal settles.
     */
    function withdrawETHFromDefaultAccount(
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @param _toAccountNumber  The account number into which `msg.sender` will be depositing
     * @param _marketId         The ID of the market being deposited
     * @param _amountPar        The amount, in Par, to deposit.
     */
    function depositPar(
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountPar
    ) external;

    /**
     * @dev Same as `depositPar` but defaults to account number 0 to save additional call data
     *
     * @param _marketId     The ID of the market being deposited
     * @param _amountPar    The amount, in Par, to deposit.
     */
    function depositParIntoDefaultAccount(
        uint256 _marketId,
        uint256 _amountPar
    ) external;

    /**
     * @param _fromAccountNumber    The account number from which `msg.sender` will be withdrawing
     * @param _marketId             The ID of the market being withdrawn
     * @param _amountPar            The amount, in Par, to withdraw. Use `uint(-1)` to withdraw `msg.sender`'s entire
     *                              balance
     * @param _balanceCheckFlag     Use `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` to check that
     *                              `_fromAccountNumber` balance is non-negative after the withdrawal settles.
     */
    function withdrawPar(
        uint256 _fromAccountNumber,
        uint256 _marketId,
        uint256 _amountPar,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @dev Same as `withdrawPar` but defaults to account number 0 to save additional call data
     *
     * @param _marketId         The ID of the market being withdrawn
     * @param _amountPar        The amount, in Par, to withdraw. Use `uint(-1)` to withdraw `msg.sender`'s entire balance
     * @param _balanceCheckFlag Use `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` to check that `_fromAccountNumber`
     *                          balance is non-negative after the withdrawal settles.
     */
    function withdrawParFromDefaultAccount(
        uint256 _marketId,
        uint256 _amountPar,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;
}

File 31 of 31 : OnlyDolomiteMargin.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 { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { Require } from "../../protocol/lib/Require.sol";


/**
 * @title OnlyDolomiteMargin
 * @author Dolomite
 *
 * Inheritable contract that restricts the calling of certain functions to DolomiteMargin only
 */
contract OnlyDolomiteMargin {

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

    bytes32 private constant FILE = "OnlyDolomiteMargin";

    // ============ Storage ============

    IDolomiteMargin public DOLOMITE_MARGIN;

    // ============ Constructor ============

    constructor (
        address _dolomiteMargin
    )
        public
    {
        DOLOMITE_MARGIN = IDolomiteMargin(_dolomiteMargin);
    }

    // ============ Modifiers ============

    modifier onlyDolomiteMargin(address _from) {
        Require.that(
            _from == address(DOLOMITE_MARGIN),
            FILE,
            "Only Dolomite can call function",
            _from
        );
        _;
    }

    modifier onlyDolomiteMarginOwner(address _from) {
        Require.that(
            _from == DOLOMITE_MARGIN.owner(),
            FILE,
            "Only Dolomite owner can call",
            _from
        );
        _;
    }

    modifier onlyGlobalOperator(address _from) {
        Require.that(
            DOLOMITE_MARGIN.getIsGlobalOperator(_from),
            FILE,
            "Only global operator can call",
            _from
        );
        _;
    }
}

Settings
{
  "remappings": [],
  "optimizer": {
    "enabled": true,
    "runs": 10000
  },
  "evmVersion": "istanbul",
  "libraries": {},
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_dolomiteMargin","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":true,"inputs":[],"name":"DOLOMITE_MARGIN","outputs":[{"internalType":"contract IDolomiteMargin","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_toAccountNumber","type":"uint256"}],"name":"depositETH","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"depositETHIntoDefaultAccount","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_toAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountPar","type":"uint256"}],"name":"depositPar","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountPar","type":"uint256"}],"name":"depositParIntoDefaultAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_toAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"depositWei","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"depositWeiIntoDefaultAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address payable","name":"_weth","type":"address"}],"name":"initializeETHMarket","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_fromAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"_balanceCheckFlag","type":"uint8"}],"name":"withdrawETH","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_amountWei","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"_balanceCheckFlag","type":"uint8"}],"name":"withdrawETHFromDefaultAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_fromAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountPar","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"_balanceCheckFlag","type":"uint8"}],"name":"withdrawPar","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountPar","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"_balanceCheckFlag","type":"uint8"}],"name":"withdrawParFromDefaultAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_fromAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"_balanceCheckFlag","type":"uint8"}],"name":"withdrawWei","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_marketId","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"_balanceCheckFlag","type":"uint8"}],"name":"withdrawWeiFromDefaultAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]

60806040523480156200001157600080fd5b506040516200285a3803806200285a83398101604081905262000034916200007b565b6000805460ff60a01b196001600160a01b039093166001600160a01b03199091161791909116600160a01b179055620000d0565b80516200007581620000b6565b92915050565b6000602082840312156200008e57600080fd5b60006200009c848462000068565b949350505050565b60006001600160a01b03821662000075565b620000c181620000a4565b8114620000cd57600080fd5b50565b61277a80620000e06000396000f3fe6080604052600436106100dd5760003560e01c8063bc6efe311161007f578063d2484bb911610059578063d2484bb914610283578063d8ddf431146102a3578063e9ed3d30146102c3578063fe491ee7146102cb576100dd565b8063bc6efe3114610223578063c38fd74e14610243578063cfeb65fe14610263576100dd565b80636e4bb3b5116100bb5780636e4bb3b5146101a35780637e54cf02146101c3578063807cb86a146101e3578063822bcd5a14610203576100dd565b8063122373191461014557806315c14a4a146101655780635358fbda14610190575b6001546101439073ffffffffffffffffffffffffffffffffffffffff1633147f4465706f7369745769746864726177616c50726f7879000000000000000000007f696e76616c6964204554482073656e64657200000000000000000000000000006102eb565b005b34801561015157600080fd5b50610143610160366004611f0a565b610387565b34801561017157600080fd5b5061017a610467565b6040516101879190612517565b60405180910390f35b61014361019e366004611e94565b610483565b3480156101af57600080fd5b506101436101be366004611ed0565b6105c0565b3480156101cf57600080fd5b506101436101de366004611f87565b6106ef565b3480156101ef57600080fd5b506101436101fe366004611f3a565b6107c1565b34801561020f57600080fd5b5061014361021e366004611e3a565b610855565b34801561022f57600080fd5b5061014361023e366004611f0a565b610a60565b34801561024f57600080fd5b5061014361025e366004611fca565b610b1d565b34801561026f57600080fd5b5061014361027e366004611fca565b610bee565b34801561028f57600080fd5b5061014361029e366004611f3a565b610c85565b3480156102af57600080fd5b506101436102be366004611f3a565b610d75565b610143610e0a565b3480156102d757600080fd5b506101436102e6366004611f87565b610f33565b82610382576102f982610fca565b7f3a2000000000000000000000000000000000000000000000000000000000000061032383610fca565b604051602001610335939291906123fc565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529082905262461bcd60e51b825261037991600401612525565b60405180910390fd5b505050565b60005474010000000000000000000000000000000000000000900460ff166103c15760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152600180825261042e9373ffffffffffffffffffffffffffffffffffffffff909316923392839288919060208201905b815260200160008152602001889052611086565b50506000805474ff0000000000000000000000000000000000000000191674010000000000000000000000000000000000000000179055565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b6003546104d49060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff1661050e5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000191690556105346111e6565b600080546002546040805160808101909152600181526105889373ffffffffffffffffffffffffffffffffffffffff9093169233923092879260208201905b81526020016000815260200134815250611086565b506000805474ff0000000000000000000000000000000000000000191674010000000000000000000000000000000000000000179055565b6003546106119060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff1661064b5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560025460408051608081019091528381526106e79373ffffffffffffffffffffffffffffffffffffffff909316923392909130919060208101845b81526020016000198a146106ba5760006106bd565b60015b60018111156106c857fe5b81526020016000198a146106dc57896106df565b60005b90528761126b565b61042e611421565b60005474010000000000000000000000000000000000000000900460ff166107295760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116909155604080516080810190915260018082526107879273ffffffffffffffffffffffffffffffffffffffff1691339182918891889190602082019061041a565b50506000805474ff000000000000000000000000000000000000000019167401000000000000000000000000000000000000000017905550565b60005474010000000000000000000000000000000000000000900460ff166107fb5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560408051608081019091528281526107879273ffffffffffffffffffffffffffffffffffffffff9092169133918290889060208101846106a5565b6003546108a79060ff16157f4465706f7369745769746864726177616c50726f7879000000000000000000007f616c726561647920696e697469616c697a6564000000000000000000000000006102eb565b6003805460017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00909116811790915580547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff838116919091179091556000546040517f8fae3be1000000000000000000000000000000000000000000000000000000008152911690638fae3be1906109599084906004016124c9565b60206040518083038186803b15801561097157600080fd5b505afa158015610985573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506109a99190810190611eb2565b6002556001546000546040517f095ea7b300000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9283169263095ea7b392610a0a92911690600019906004016124d7565b602060405180830381600087803b158015610a2457600080fd5b505af1158015610a38573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610a5c9190810190611e58565b5050565b60005474010000000000000000000000000000000000000000900460ff16610a9a5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560408051608081019091526001815261042e9273ffffffffffffffffffffffffffffffffffffffff909216913391829190879060208101835b8152602001600081526020016000198914610b0d5788610b16565b610b168a611566565b9052611086565b60005474010000000000000000000000000000000000000000900460ff16610b575760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152828152610bb39273ffffffffffffffffffffffffffffffffffffffff90921691339188918391899160208201906106a5565b50506000805474ff00000000000000000000000000000000000000001916740100000000000000000000000000000000000000001790555050565b60005474010000000000000000000000000000000000000000900460ff16610c285760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152918252610bb39173ffffffffffffffffffffffffffffffffffffffff9091169033908790829088906020810160016106a5565b600354610cd69060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff16610d105760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556002546040805160808101909152838152610d6d9373ffffffffffffffffffffffffffffffffffffffff9093169233928892309260208201906106a5565b610787611421565b60005474010000000000000000000000000000000000000000900460ff16610daf5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560408051608081019091528281526107879273ffffffffffffffffffffffffffffffffffffffff909216913391829088906020810160016106a5565b600354610e5b9060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff16610e955760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019169055610ebb6111e6565b60008054600254604080516080810190915260018152610efc9373ffffffffffffffffffffffffffffffffffffffff90931692339230926020810183610573565b6000805474ff0000000000000000000000000000000000000000191674010000000000000000000000000000000000000000179055565b60005474010000000000000000000000000000000000000000900460ff16610f6d5760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152600181526107879273ffffffffffffffffffffffffffffffffffffffff9092169133918291889188916020820190610af2565b60608082604051602001610fde91906123e7565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152919052905060205b80156110695781516000199091019082908290811061102c57fe5b01602001517fff0000000000000000000000000000000000000000000000000000000000000016156110645760010181529050611081565b611011565b5060408051600080825260208201909252905b509150505b919050565b604080516001808252818301909252606091816020015b6110a5611ce1565b81526020019060019003908161109d57905050905060405180604001604052808773ffffffffffffffffffffffffffffffffffffffff16815260200185815250816000815181106110f257fe5b6020908102919091010152604080516001808252818301909252606091816020015b61111c611cf8565b81526020019060019003908161111457905050905061113e600085858961169b565b8160008151811061114b57fe5b60209081029190910101526040517fa67a6a4500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff89169063a67a6a45906111aa90859085906004016124f2565b600060405180830381600087803b1580156111c457600080fd5b505af11580156111d8573d6000803e3d6000fd5b505050505050505050505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561125057600080fd5b505af1158015611264573d6000803e3d6000fd5b5050505050565b604080516001808252818301909252606091816020015b61128a611ce1565b81526020019060019003908161128257905050905060405180604001604052808873ffffffffffffffffffffffffffffffffffffffff16815260200187815250816000815181106112d757fe5b6020908102919091010152604080516001808252818301909252606091816020015b611301611cf8565b8152602001906001900390816112f95790505090506113236000868689611711565b8160008151811061133057fe5b60209081029190910101526040517fa67a6a4500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8a169063a67a6a459061138f90859085906004016124f2565b600060405180830381600087803b1580156113a957600080fd5b505af11580156113bd573d6000803e3d6000fd5b50600092506113ca915050565b8360038111156113d657fe5b14806113ed575060018360038111156113eb57fe5b145b1561141657611416898360008151811061140357fe5b602002602001015160000151898861172d565b505050505050505050565b6001546040517f70a0823100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9091169060009082906370a082319061147c9030906004016124c9565b60206040518083038186803b15801561149457600080fd5b505afa1580156114a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506114cc9190810190611eb2565b6040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815290915073ffffffffffffffffffffffffffffffffffffffff831690632e1a7d4d90611521908490600401612581565b600060405180830381600087803b15801561153b57600080fd5b505af115801561154f573d6000803e3d6000fd5b50610a5c925033915083905063ffffffff61187c16565b600080546040517f062bd3e900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9091169063062bd3e9906115bd908590600401612581565b60206040518083038186803b1580156115d557600080fd5b505afa1580156115e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061160d9190810190611e14565b73ffffffffffffffffffffffffffffffffffffffff166370a08231336040518263ffffffff1660e01b815260040161164591906124c9565b60206040518083038186803b15801561165d57600080fd5b505afa158015611671573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506116959190810190611eb2565b92915050565b6116a3611cf8565b6040805161010081019091528060005b8152602001868152602001848152602001858152602001600081526020018373ffffffffffffffffffffffffffffffffffffffff16815260200160008152602001604051806020016040528060008152508152509050949350505050565b611719611cf8565b6040805161010081019091528060016116b3565b611735611ce1565b60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff16815260200184815250905061176a611ce1565b6040517f47d1b53c00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8716906347d1b53c906117be9085908790600401612566565b604080518083038186803b1580156117d557600080fd5b505afa1580156117e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061180d9190810190611e76565b905061187461181b82611925565b8061182a575061182a8261194d565b7f4163636f756e7442616c616e63654c69620000000000000000000000000000007f6163636f756e742063616e6e6f7420676f206e65676174697665000000000000888888611967565b505050505050565b8047101561189c5760405162461bcd60e51b815260040161037990612546565b60008273ffffffffffffffffffffffffffffffffffffffff16826040516118c2906124be565b60006040518083038185875af1925050503d80600081146118ff576040519150601f19603f3d011682016040523d82523d6000602084013e611904565b606091505b50509050806103825760405162461bcd60e51b815260040161037990612536565b80516000908015611695575050602001516fffffffffffffffffffffffffffffffff16151590565b602001516fffffffffffffffffffffffffffffffff161590565b856118745761197585610fca565b7f3a2000000000000000000000000000000000000000000000000000000000000061199f86610fca565b7f203c0000000000000000000000000000000000000000000000000000000000006119c987611a57565b7f2c200000000000000000000000000000000000000000000000000000000000006119f388611bce565b7f2c20000000000000000000000000000000000000000000000000000000000000611a1d89611bce565b604051610335999897969594939291907f3e0000000000000000000000000000000000000000000000000000000000000090602001612424565b60408051602a808252606082810190935273ffffffffffffffffffffffffffffffffffffffff8416918391602082018180388339019050509050603060f81b81600081518110611aa357fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350607860f81b81600181518110611ae457fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060005b601481101561107c5760028102611b2f600f8516611cbf565b838260290381518110611b3e57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600484901c9350611b80600f8516611cbf565b838260280381518110611b8f57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053505060049290921c91600101611b16565b606081611c0f575060408051808201909152600181527f30000000000000000000000000000000000000000000000000000000000000006020820152611081565b8160005b8115611c2757600101600a82049150611c13565b6060816040519080825280601f01601f191660200182016040528015611c54576020820181803883390190505b508593509050815b8015611cb65760001901600a840660300160f81b828281518110611c7c57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84049350611c5c565b50949350505050565b6000600a821015611cd757506030810160f81b611081565b5060570160f81b90565b604080518082019091526000808252602082015290565b604080516101008101825260008082526020820152908101611d18611d57565b81526020016000815260200160008152602001600073ffffffffffffffffffffffffffffffffffffffff16815260200160008152602001606081525090565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b8051611695816126fb565b8035611695816126fb565b80516116958161270f565b803561169581612718565b600060408284031215611dbe57600080fd5b611dc8604061258f565b90506000611dd68484611d96565b8252506020611de784848301611df3565b60208301525092915050565b805161169581612725565b80356116958161272e565b80516116958161272e565b600060208284031215611e2657600080fd5b6000611e328484611d80565b949350505050565b600060208284031215611e4c57600080fd5b6000611e328484611d8b565b600060208284031215611e6a57600080fd5b6000611e328484611d96565b600060408284031215611e8857600080fd5b6000611e328484611dac565b600060208284031215611ea657600080fd5b6000611e328484611dfe565b600060208284031215611ec457600080fd5b6000611e328484611e09565b60008060408385031215611ee357600080fd5b6000611eef8585611dfe565b9250506020611f0085828601611da1565b9150509250929050565b60008060408385031215611f1d57600080fd5b6000611f298585611dfe565b9250506020611f0085828601611dfe565b600080600060608486031215611f4f57600080fd5b6000611f5b8686611dfe565b9350506020611f6c86828701611dfe565b9250506040611f7d86828701611da1565b9150509250925092565b600080600060608486031215611f9c57600080fd5b6000611fa88686611dfe565b9350506020611fb986828701611dfe565b9250506040611f7d86828701611dfe565b60008060008060808587031215611fe057600080fd5b6000611fec8787611dfe565b9450506020611ffd87828801611dfe565b935050604061200e87828801611dfe565b925050606061201f87828801611da1565b91505092959194509250565b600061203783836122c3565b9392505050565b600061204a83836123be565b505060400190565b61205b81612668565b82525050565b61205b816125c9565b6000612075826125bc565b61207f81856125c0565b935083602082028501612091856125b6565b8060005b858110156120cb57848403895281516120ae858261202b565b94506120b9836125b6565b60209a909a0199925050600101612095565b5091979650505050505050565b60006120e3826125bc565b6120ed81856125c0565b93506120f8836125b6565b8060005b83811015612126578151612110888261203e565b975061211b836125b6565b9250506001016120fc565b509495945050505050565b61205b816125d4565b61205b612146826125d9565b612623565b61205b612146826125fe565b61205b61214682612623565b600061216e826125bc565b6121788185611081565b9350612188818560208601612690565b9290920192915050565b600061219d826125bc565b6121a781856125c0565b93506121b7818560208601612690565b6121c0816126bc565b9093019392505050565b61205b8161266f565b61205b8161267a565b61205b81612685565b60006121f2603a836125c0565b7f416464726573733a20756e61626c6520746f2073656e642076616c75652c207281527f6563697069656e74206d61792068617665207265766572746564000000000000602082015260400192915050565b6000612251601d836125c0565b7f416464726573733a20696e73756666696369656e742062616c616e6365000000815260200192915050565b6000611695600083611081565b6000612297601f836125c0565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00815260200192915050565b80516000906101608401906122d885826121d3565b5060208301516122eb60208601826123de565b5060408301516122fe604086018261236e565b50606083015161231160c08601826123de565b50608083015161232460e08601826123de565b5060a0830151612338610100860182612061565b5060c083015161234c6101208601826123de565b5060e08301518482036101408601526123658282612192565b95945050505050565b8051608083019061237f8482612131565b50602082015161239260208501826121dc565b5060408201516123a560408501826121dc565b5060608201516123b860608501826123de565b50505050565b805160408301906123cf8482612061565b5060208201516123b860208501825b61205b81612623565b60006123f38284612157565b50602001919050565b60006124088286612163565b9150612414828561214b565b6002820191506123658284612163565b6000612430828d612163565b915061243c828c61214b565b60028201915061244c828b612163565b9150612458828a61214b565b6002820191506124688289612163565b9150612474828861214b565b6002820191506124848287612163565b9150612490828661214b565b6002820191506124a08285612163565b91506124ac828461213a565b506001019a9950505050505050505050565b60006116958261227d565b602081016116958284612052565b604081016124e58285612061565b61203760208301846123de565b6040808252810161250381856120d8565b90508181036020830152611e32818461206a565b6020810161169582846121ca565b602080825281016120378184612192565b60208082528101611695816121e5565b6020808252810161169581612244565b602080825281016116958161228a565b6060810161257482856123be565b61203760408301846123de565b6020810161169582846123de565b60405181810167ffffffffffffffff811182821017156125ae57600080fd5b604052919050565b60200190565b5190565b90815260200190565b60006116958261264f565b151590565b7fff000000000000000000000000000000000000000000000000000000000000001690565b7fffff0000000000000000000000000000000000000000000000000000000000001690565b90565b80611081816126e4565b80611081816126f1565b6fffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b6000611695825b6000611695826125c9565b600061169582612626565b600061169582612630565b60005b838110156126ab578181015183820152602001612693565b838111156123b85750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b600981106126ee57fe5b50565b600281106126ee57fe5b612704816125c9565b81146126ee57600080fd5b612704816125d4565b600481106126ee57600080fd5b6127048161263a565b6127048161262356fea365627a7a7231582006b3e8751a74a42b9a436a66d1d9ed620d1d9d4c3f5a33a6acf211dd81914e776c6578706572696d656e74616cf564736f6c63430005100040000000000000000000000000836b557cf9ef29fcf49c776841191782df34e4e5

Deployed Bytecode

0x6080604052600436106100dd5760003560e01c8063bc6efe311161007f578063d2484bb911610059578063d2484bb914610283578063d8ddf431146102a3578063e9ed3d30146102c3578063fe491ee7146102cb576100dd565b8063bc6efe3114610223578063c38fd74e14610243578063cfeb65fe14610263576100dd565b80636e4bb3b5116100bb5780636e4bb3b5146101a35780637e54cf02146101c3578063807cb86a146101e3578063822bcd5a14610203576100dd565b8063122373191461014557806315c14a4a146101655780635358fbda14610190575b6001546101439073ffffffffffffffffffffffffffffffffffffffff1633147f4465706f7369745769746864726177616c50726f7879000000000000000000007f696e76616c6964204554482073656e64657200000000000000000000000000006102eb565b005b34801561015157600080fd5b50610143610160366004611f0a565b610387565b34801561017157600080fd5b5061017a610467565b6040516101879190612517565b60405180910390f35b61014361019e366004611e94565b610483565b3480156101af57600080fd5b506101436101be366004611ed0565b6105c0565b3480156101cf57600080fd5b506101436101de366004611f87565b6106ef565b3480156101ef57600080fd5b506101436101fe366004611f3a565b6107c1565b34801561020f57600080fd5b5061014361021e366004611e3a565b610855565b34801561022f57600080fd5b5061014361023e366004611f0a565b610a60565b34801561024f57600080fd5b5061014361025e366004611fca565b610b1d565b34801561026f57600080fd5b5061014361027e366004611fca565b610bee565b34801561028f57600080fd5b5061014361029e366004611f3a565b610c85565b3480156102af57600080fd5b506101436102be366004611f3a565b610d75565b610143610e0a565b3480156102d757600080fd5b506101436102e6366004611f87565b610f33565b82610382576102f982610fca565b7f3a2000000000000000000000000000000000000000000000000000000000000061032383610fca565b604051602001610335939291906123fc565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529082905262461bcd60e51b825261037991600401612525565b60405180910390fd5b505050565b60005474010000000000000000000000000000000000000000900460ff166103c15760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152600180825261042e9373ffffffffffffffffffffffffffffffffffffffff909316923392839288919060208201905b815260200160008152602001889052611086565b50506000805474ff0000000000000000000000000000000000000000191674010000000000000000000000000000000000000000179055565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b6003546104d49060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff1661050e5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000191690556105346111e6565b600080546002546040805160808101909152600181526105889373ffffffffffffffffffffffffffffffffffffffff9093169233923092879260208201905b81526020016000815260200134815250611086565b506000805474ff0000000000000000000000000000000000000000191674010000000000000000000000000000000000000000179055565b6003546106119060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff1661064b5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560025460408051608081019091528381526106e79373ffffffffffffffffffffffffffffffffffffffff909316923392909130919060208101845b81526020016000198a146106ba5760006106bd565b60015b60018111156106c857fe5b81526020016000198a146106dc57896106df565b60005b90528761126b565b61042e611421565b60005474010000000000000000000000000000000000000000900460ff166107295760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116909155604080516080810190915260018082526107879273ffffffffffffffffffffffffffffffffffffffff1691339182918891889190602082019061041a565b50506000805474ff000000000000000000000000000000000000000019167401000000000000000000000000000000000000000017905550565b60005474010000000000000000000000000000000000000000900460ff166107fb5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560408051608081019091528281526107879273ffffffffffffffffffffffffffffffffffffffff9092169133918290889060208101846106a5565b6003546108a79060ff16157f4465706f7369745769746864726177616c50726f7879000000000000000000007f616c726561647920696e697469616c697a6564000000000000000000000000006102eb565b6003805460017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00909116811790915580547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff838116919091179091556000546040517f8fae3be1000000000000000000000000000000000000000000000000000000008152911690638fae3be1906109599084906004016124c9565b60206040518083038186803b15801561097157600080fd5b505afa158015610985573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506109a99190810190611eb2565b6002556001546000546040517f095ea7b300000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9283169263095ea7b392610a0a92911690600019906004016124d7565b602060405180830381600087803b158015610a2457600080fd5b505af1158015610a38573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610a5c9190810190611e58565b5050565b60005474010000000000000000000000000000000000000000900460ff16610a9a5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560408051608081019091526001815261042e9273ffffffffffffffffffffffffffffffffffffffff909216913391829190879060208101835b8152602001600081526020016000198914610b0d5788610b16565b610b168a611566565b9052611086565b60005474010000000000000000000000000000000000000000900460ff16610b575760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152828152610bb39273ffffffffffffffffffffffffffffffffffffffff90921691339188918391899160208201906106a5565b50506000805474ff00000000000000000000000000000000000000001916740100000000000000000000000000000000000000001790555050565b60005474010000000000000000000000000000000000000000900460ff16610c285760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152918252610bb39173ffffffffffffffffffffffffffffffffffffffff9091169033908790829088906020810160016106a5565b600354610cd69060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff16610d105760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556002546040805160808101909152838152610d6d9373ffffffffffffffffffffffffffffffffffffffff9093169233928892309260208201906106a5565b610787611421565b60005474010000000000000000000000000000000000000000900460ff16610daf5760405162461bcd60e51b815260040161037990612556565b6000805474ff0000000000000000000000000000000000000000198116825560408051608081019091528281526107879273ffffffffffffffffffffffffffffffffffffffff909216913391829088906020810160016106a5565b600354610e5b9060ff167f4465706f7369745769746864726177616c50726f7879000000000000000000007f6e6f7420696e697469616c697a656400000000000000000000000000000000006102eb565b60005474010000000000000000000000000000000000000000900460ff16610e955760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019169055610ebb6111e6565b60008054600254604080516080810190915260018152610efc9373ffffffffffffffffffffffffffffffffffffffff90931692339230926020810183610573565b6000805474ff0000000000000000000000000000000000000000191674010000000000000000000000000000000000000000179055565b60005474010000000000000000000000000000000000000000900460ff16610f6d5760405162461bcd60e51b815260040161037990612556565b6000805474ff000000000000000000000000000000000000000019811682556040805160808101909152600181526107879273ffffffffffffffffffffffffffffffffffffffff9092169133918291889188916020820190610af2565b60608082604051602001610fde91906123e7565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152919052905060205b80156110695781516000199091019082908290811061102c57fe5b01602001517fff0000000000000000000000000000000000000000000000000000000000000016156110645760010181529050611081565b611011565b5060408051600080825260208201909252905b509150505b919050565b604080516001808252818301909252606091816020015b6110a5611ce1565b81526020019060019003908161109d57905050905060405180604001604052808773ffffffffffffffffffffffffffffffffffffffff16815260200185815250816000815181106110f257fe5b6020908102919091010152604080516001808252818301909252606091816020015b61111c611cf8565b81526020019060019003908161111457905050905061113e600085858961169b565b8160008151811061114b57fe5b60209081029190910101526040517fa67a6a4500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff89169063a67a6a45906111aa90859085906004016124f2565b600060405180830381600087803b1580156111c457600080fd5b505af11580156111d8573d6000803e3d6000fd5b505050505050505050505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561125057600080fd5b505af1158015611264573d6000803e3d6000fd5b5050505050565b604080516001808252818301909252606091816020015b61128a611ce1565b81526020019060019003908161128257905050905060405180604001604052808873ffffffffffffffffffffffffffffffffffffffff16815260200187815250816000815181106112d757fe5b6020908102919091010152604080516001808252818301909252606091816020015b611301611cf8565b8152602001906001900390816112f95790505090506113236000868689611711565b8160008151811061133057fe5b60209081029190910101526040517fa67a6a4500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8a169063a67a6a459061138f90859085906004016124f2565b600060405180830381600087803b1580156113a957600080fd5b505af11580156113bd573d6000803e3d6000fd5b50600092506113ca915050565b8360038111156113d657fe5b14806113ed575060018360038111156113eb57fe5b145b1561141657611416898360008151811061140357fe5b602002602001015160000151898861172d565b505050505050505050565b6001546040517f70a0823100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9091169060009082906370a082319061147c9030906004016124c9565b60206040518083038186803b15801561149457600080fd5b505afa1580156114a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506114cc9190810190611eb2565b6040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815290915073ffffffffffffffffffffffffffffffffffffffff831690632e1a7d4d90611521908490600401612581565b600060405180830381600087803b15801561153b57600080fd5b505af115801561154f573d6000803e3d6000fd5b50610a5c925033915083905063ffffffff61187c16565b600080546040517f062bd3e900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9091169063062bd3e9906115bd908590600401612581565b60206040518083038186803b1580156115d557600080fd5b505afa1580156115e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061160d9190810190611e14565b73ffffffffffffffffffffffffffffffffffffffff166370a08231336040518263ffffffff1660e01b815260040161164591906124c9565b60206040518083038186803b15801561165d57600080fd5b505afa158015611671573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506116959190810190611eb2565b92915050565b6116a3611cf8565b6040805161010081019091528060005b8152602001868152602001848152602001858152602001600081526020018373ffffffffffffffffffffffffffffffffffffffff16815260200160008152602001604051806020016040528060008152508152509050949350505050565b611719611cf8565b6040805161010081019091528060016116b3565b611735611ce1565b60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff16815260200184815250905061176a611ce1565b6040517f47d1b53c00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8716906347d1b53c906117be9085908790600401612566565b604080518083038186803b1580156117d557600080fd5b505afa1580156117e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061180d9190810190611e76565b905061187461181b82611925565b8061182a575061182a8261194d565b7f4163636f756e7442616c616e63654c69620000000000000000000000000000007f6163636f756e742063616e6e6f7420676f206e65676174697665000000000000888888611967565b505050505050565b8047101561189c5760405162461bcd60e51b815260040161037990612546565b60008273ffffffffffffffffffffffffffffffffffffffff16826040516118c2906124be565b60006040518083038185875af1925050503d80600081146118ff576040519150601f19603f3d011682016040523d82523d6000602084013e611904565b606091505b50509050806103825760405162461bcd60e51b815260040161037990612536565b80516000908015611695575050602001516fffffffffffffffffffffffffffffffff16151590565b602001516fffffffffffffffffffffffffffffffff161590565b856118745761197585610fca565b7f3a2000000000000000000000000000000000000000000000000000000000000061199f86610fca565b7f203c0000000000000000000000000000000000000000000000000000000000006119c987611a57565b7f2c200000000000000000000000000000000000000000000000000000000000006119f388611bce565b7f2c20000000000000000000000000000000000000000000000000000000000000611a1d89611bce565b604051610335999897969594939291907f3e0000000000000000000000000000000000000000000000000000000000000090602001612424565b60408051602a808252606082810190935273ffffffffffffffffffffffffffffffffffffffff8416918391602082018180388339019050509050603060f81b81600081518110611aa357fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350607860f81b81600181518110611ae457fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060005b601481101561107c5760028102611b2f600f8516611cbf565b838260290381518110611b3e57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600484901c9350611b80600f8516611cbf565b838260280381518110611b8f57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053505060049290921c91600101611b16565b606081611c0f575060408051808201909152600181527f30000000000000000000000000000000000000000000000000000000000000006020820152611081565b8160005b8115611c2757600101600a82049150611c13565b6060816040519080825280601f01601f191660200182016040528015611c54576020820181803883390190505b508593509050815b8015611cb65760001901600a840660300160f81b828281518110611c7c57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84049350611c5c565b50949350505050565b6000600a821015611cd757506030810160f81b611081565b5060570160f81b90565b604080518082019091526000808252602082015290565b604080516101008101825260008082526020820152908101611d18611d57565b81526020016000815260200160008152602001600073ffffffffffffffffffffffffffffffffffffffff16815260200160008152602001606081525090565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b8051611695816126fb565b8035611695816126fb565b80516116958161270f565b803561169581612718565b600060408284031215611dbe57600080fd5b611dc8604061258f565b90506000611dd68484611d96565b8252506020611de784848301611df3565b60208301525092915050565b805161169581612725565b80356116958161272e565b80516116958161272e565b600060208284031215611e2657600080fd5b6000611e328484611d80565b949350505050565b600060208284031215611e4c57600080fd5b6000611e328484611d8b565b600060208284031215611e6a57600080fd5b6000611e328484611d96565b600060408284031215611e8857600080fd5b6000611e328484611dac565b600060208284031215611ea657600080fd5b6000611e328484611dfe565b600060208284031215611ec457600080fd5b6000611e328484611e09565b60008060408385031215611ee357600080fd5b6000611eef8585611dfe565b9250506020611f0085828601611da1565b9150509250929050565b60008060408385031215611f1d57600080fd5b6000611f298585611dfe565b9250506020611f0085828601611dfe565b600080600060608486031215611f4f57600080fd5b6000611f5b8686611dfe565b9350506020611f6c86828701611dfe565b9250506040611f7d86828701611da1565b9150509250925092565b600080600060608486031215611f9c57600080fd5b6000611fa88686611dfe565b9350506020611fb986828701611dfe565b9250506040611f7d86828701611dfe565b60008060008060808587031215611fe057600080fd5b6000611fec8787611dfe565b9450506020611ffd87828801611dfe565b935050604061200e87828801611dfe565b925050606061201f87828801611da1565b91505092959194509250565b600061203783836122c3565b9392505050565b600061204a83836123be565b505060400190565b61205b81612668565b82525050565b61205b816125c9565b6000612075826125bc565b61207f81856125c0565b935083602082028501612091856125b6565b8060005b858110156120cb57848403895281516120ae858261202b565b94506120b9836125b6565b60209a909a0199925050600101612095565b5091979650505050505050565b60006120e3826125bc565b6120ed81856125c0565b93506120f8836125b6565b8060005b83811015612126578151612110888261203e565b975061211b836125b6565b9250506001016120fc565b509495945050505050565b61205b816125d4565b61205b612146826125d9565b612623565b61205b612146826125fe565b61205b61214682612623565b600061216e826125bc565b6121788185611081565b9350612188818560208601612690565b9290920192915050565b600061219d826125bc565b6121a781856125c0565b93506121b7818560208601612690565b6121c0816126bc565b9093019392505050565b61205b8161266f565b61205b8161267a565b61205b81612685565b60006121f2603a836125c0565b7f416464726573733a20756e61626c6520746f2073656e642076616c75652c207281527f6563697069656e74206d61792068617665207265766572746564000000000000602082015260400192915050565b6000612251601d836125c0565b7f416464726573733a20696e73756666696369656e742062616c616e6365000000815260200192915050565b6000611695600083611081565b6000612297601f836125c0565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00815260200192915050565b80516000906101608401906122d885826121d3565b5060208301516122eb60208601826123de565b5060408301516122fe604086018261236e565b50606083015161231160c08601826123de565b50608083015161232460e08601826123de565b5060a0830151612338610100860182612061565b5060c083015161234c6101208601826123de565b5060e08301518482036101408601526123658282612192565b95945050505050565b8051608083019061237f8482612131565b50602082015161239260208501826121dc565b5060408201516123a560408501826121dc565b5060608201516123b860608501826123de565b50505050565b805160408301906123cf8482612061565b5060208201516123b860208501825b61205b81612623565b60006123f38284612157565b50602001919050565b60006124088286612163565b9150612414828561214b565b6002820191506123658284612163565b6000612430828d612163565b915061243c828c61214b565b60028201915061244c828b612163565b9150612458828a61214b565b6002820191506124688289612163565b9150612474828861214b565b6002820191506124848287612163565b9150612490828661214b565b6002820191506124a08285612163565b91506124ac828461213a565b506001019a9950505050505050505050565b60006116958261227d565b602081016116958284612052565b604081016124e58285612061565b61203760208301846123de565b6040808252810161250381856120d8565b90508181036020830152611e32818461206a565b6020810161169582846121ca565b602080825281016120378184612192565b60208082528101611695816121e5565b6020808252810161169581612244565b602080825281016116958161228a565b6060810161257482856123be565b61203760408301846123de565b6020810161169582846123de565b60405181810167ffffffffffffffff811182821017156125ae57600080fd5b604052919050565b60200190565b5190565b90815260200190565b60006116958261264f565b151590565b7fff000000000000000000000000000000000000000000000000000000000000001690565b7fffff0000000000000000000000000000000000000000000000000000000000001690565b90565b80611081816126e4565b80611081816126f1565b6fffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b6000611695825b6000611695826125c9565b600061169582612626565b600061169582612630565b60005b838110156126ab578181015183820152602001612693565b838111156123b85750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b600981106126ee57fe5b50565b600281106126ee57fe5b612704816125c9565b81146126ee57600080fd5b612704816125d4565b600481106126ee57600080fd5b6127048161263a565b6127048161262356fea365627a7a7231582006b3e8751a74a42b9a436a66d1d9ed620d1d9d4c3f5a33a6acf211dd81914e776c6578706572696d656e74616cf564736f6c63430005100040

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000836b557cf9ef29fcf49c776841191782df34e4e5

-----Decoded View---------------
Arg [0] : _dolomiteMargin (address): 0x836b557Cf9eF29fcF49C776841191782df34e4e5

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000836b557cf9ef29fcf49c776841191782df34e4e5


Block Transaction Gas Used Reward
view all blocks sequenced

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

Validator Index Block Amount
View All Withdrawals

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

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