// File: /contracts/pricers/ManualPricer.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.10;

import {OracleInterface} from "../interfaces/OracleInterface.sol";
import {OpynPricerInterface} from "../interfaces/OpynPricerInterface.sol";
import {SafeMath} from "../packages/oz/SafeMath.sol";
import {AddressBookInterface} from "../interfaces/AddressBookInterface.sol";

/**
 * @notice A Pricer contract for one asset as reported by Manual entity
 */
contract ManualPricer is OpynPricerInterface {
    using SafeMath for uint256;

    /// @notice price deviation multiplier factor
    uint256 public constant MULTIPLIER_FACTOR = 10**2; // price deviation multiplier has 2 decimals

    /// @notice the opyn oracle address
    OracleInterface public oracle;

    /// @notice the opyn addressbook address
    AddressBookInterface public addressbook;

    /// @notice asset that this pricer will a get price for
    address public asset;

    /// @notice bot address that is allowed to call setExpiryPriceInOracle
    address public bot;

    /// @notice lastExpiryTimestamp last timestamp that asset price was set
    uint256 public lastExpiryTimestamp;

    /// @notice priceTimeValidity is the maximum time duration in which an updated price remains valid
    uint256 public priceTimeValidity;

    /// @notice deviation multiplier between new and previous price
    uint256 public deviationMultiplier;

    /// @notice historicalPrice mapping of timestamp to price
    mapping(uint256 => uint256) public historicalPrice;

    /**
     * @param _bot priveleged address that can call setExpiryPriceInOracle
     * @param _asset asset that this pricer will get a price for
     * @param _oracle Opyn Oracle address
     * @param _addressbook Opyn AddressBook address
     */
    constructor(
        address _bot,
        address _asset,
        address _oracle,
        address _addressbook
    ) public {
        require(_bot != address(0), "ManualPricer: Cannot set 0 address as bot");
        require(_oracle != address(0), "ManualPricer: Cannot set 0 address as oracle");
        require(_addressbook != address(0), "ManualPricer: Cannot set 0 address as addressbook");

        bot = _bot;
        oracle = OracleInterface(_oracle);
        asset = _asset;
        addressbook = AddressBookInterface(_addressbook);
    }

    /**
     * @notice modifier to check if sender address is equal to bot address
     */
    modifier onlyBot() {
        require(msg.sender == bot, "ManualPricer: unauthorized sender");

        _;
    }

    /**
     * @notice modifier to check if the sender is the keeper address
     */
    modifier onlyKeeper() {
        require(msg.sender == addressbook.getKeeper(), "ManualPricer: sender is not keeper");

        _;
    }

    /**
     * @notice set the price validity time window, can only be called by Keeper address
     * @param _priceTimeValidity time interval within which price is considered valid (in seconds)
     */
    function setPriceTimeValidity(uint256 _priceTimeValidity) external onlyKeeper {
        require(_priceTimeValidity > 0, "ManualPricer: price time validity cannot be 0");

        priceTimeValidity = _priceTimeValidity;
    }

    /**
     * @notice sets the deviation multiplier, can only be called by Keeper address
     * @param _deviationMultiplier deviation multiplier between new and previous price (2 decimals - eg. 1.75 = 175)
     */
    function setDeviationMultiplier(uint256 _deviationMultiplier) external onlyKeeper {
        require(_deviationMultiplier > 0, "ManualPricer: deviation multiplier cannot be 0");

        deviationMultiplier = _deviationMultiplier;
    }

    /**
     * @notice set the expiry price in the oracle, can only be called by Bot address
     * @param _expiryTimestamp expiry to set a price for
     * @param _price price of the asset in USD, scaled by 1e8
     */
    function setExpiryPriceInOracle(uint256 _expiryTimestamp, uint256 _price) external onlyBot {
        require(_expiryTimestamp <= now, "ManualPricer: expiries prices cannot be set for the future");

        uint256 previousPrice = historicalPrice[lastExpiryTimestamp];

        // checks if new price is within the deviation multiplier allowed from previous price
        // adding MULTIPLIER_FACTOR on one side of the equation is required to
        // match the same number of decimals from deviationMultiplier
        if (previousPrice > 0) {
            require(
                _price.mul(MULTIPLIER_FACTOR) < previousPrice.mul(deviationMultiplier) &&
                    _price.mul(deviationMultiplier) > previousPrice.mul(MULTIPLIER_FACTOR),
                "ManualPricer: price deviation is larger than currently allowed"
            );
        }

        lastExpiryTimestamp = _expiryTimestamp;
        historicalPrice[_expiryTimestamp] = _price;
        oracle.setExpiryPrice(asset, _expiryTimestamp, _price);
    }

    /**
     * @notice get the live price for the asset
     * @dev overides the getPrice function in OpynPricerInterface
     * @return price of the asset in USD, scaled by 1e8
     */
    function getPrice() external view override returns (uint256) {
        require(now <= lastExpiryTimestamp.add(priceTimeValidity), "ManualPricer: price is no longer valid");
        return historicalPrice[lastExpiryTimestamp];
    }

    /**
     * @notice get historical chainlink price
     * @param _roundId chainlink round id
     * @return round price and timestamp
     */
    function getHistoricalPrice(uint80 _roundId) external view override returns (uint256, uint256) {
        revert("ManualPricer: Deprecated");
    }
}

// File: /contracts/packages/oz/SafeMath.sol



// SPDX-License-Identifier: MIT
// openzeppelin-contracts v3.1.0

/* solhint-disable */
pragma solidity ^0.6.0;

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

        return c;
    }

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

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

        return c;
    }

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

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

        return c;
    }

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

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        // 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.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

// File: /contracts/interfaces/OracleInterface.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.10;

interface OracleInterface {
    function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);

    function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);

    function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool);

    function getDisputer() external view returns (address);

    function getPricer(address _asset) external view returns (address);

    function getPrice(address _asset) external view returns (uint256);

    function getPricerLockingPeriod(address _pricer) external view returns (uint256);

    function getPricerDisputePeriod(address _pricer) external view returns (uint256);

    function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256);

    // Non-view function

    function setAssetPricer(address _asset, address _pricer) external;

    function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;

    function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;

    function setExpiryPrice(
        address _asset,
        uint256 _expiryTimestamp,
        uint256 _price
    ) external;

    function disputeExpiryPrice(
        address _asset,
        uint256 _expiryTimestamp,
        uint256 _price
    ) external;

    function setDisputer(address _disputer) external;
}

// File: /contracts/interfaces/OpynPricerInterface.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.10;

interface OpynPricerInterface {
    function getPrice() external view returns (uint256);

    function getHistoricalPrice(uint80 _roundId) external view returns (uint256, uint256);
}

// File: /contracts/interfaces/AddressBookInterface.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.10;

interface AddressBookInterface {
    /* Getters */

    function getOtokenImpl() external view returns (address);

    function getOtokenFactory() external view returns (address);

    function getWhitelist() external view returns (address);

    function getController() external view returns (address);

    function getOracle() external view returns (address);

    function getMarginPool() external view returns (address);

    function getMarginCalculator() external view returns (address);

    function getMarginRequirements() external view returns (address);

    function getLiquidationManager() external view returns (address);

    function getKeeper() external view returns (address);

    function getOTCWrapper() external view returns (address);

    function getAddress(bytes32 _id) external view returns (address);

    /* Setters */

    function setOtokenImpl(address _otokenImpl) external;

    function setOtokenFactory(address _factory) external;

    function setOracleImpl(address _otokenImpl) external;

    function setWhitelist(address _whitelist) external;

    function setController(address _controller) external;

    function setMarginPool(address _marginPool) external;

    function setMarginCalculator(address _calculator) external;

    function setLiquidationManager(address _liquidationManager) external;

    function setAddress(bytes32 _id, address _newImpl) external;
}