// File: contracts/PriceOracle.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

/**
 * @notice chainlink price oracle.
 * This is the contract to fix the price at the nearest time after expiry.
 */
contract PriceOracle is Ownable {
    /// @dev expiry price with timestamp
    struct ExpiryPrice {
        uint256 price;
        uint256 timestamp;
    }

    /// @dev chainlink aggregator address of the underlying asset price
    mapping(address => AggregatorV3Interface) aggregators;

    /// @dev aggregator address => timestamp => expiry price
    mapping(address => mapping(uint256 => ExpiryPrice)) internal expiryPrices;

    event ExpiryPriceUpdated(address aggregator, uint256 expiry, uint256 price);

    uint256 public constant DISPUTE_PERIOD = 2 hours;

    /**
     * @notice set aggregator
     * only owner can set new aggregator
     */
    function setAggregator(address _aggregatorAddress) external onlyOwner {
        require(address(aggregators[_aggregatorAddress]) == address(0));
        aggregators[_aggregatorAddress] = AggregatorV3Interface(_aggregatorAddress);
    }

    /**
     * @notice set expiry price
     * anyone can set price if the price has not been setted.
     * Also timestamp must be later than expiration.
     */
    function setExpiryPrice(address _aggregator, uint256 _expiryTimestamp) external {
        (uint256 price, uint256 timestamp) = getPrice(_aggregator);

        require(_expiryTimestamp < timestamp, "PriceOracle: price timestamp must be later than expiry");

        ExpiryPrice storage expiryPrice = expiryPrices[_aggregator][_expiryTimestamp];

        require(expiryPrice.timestamp == 0, "PriceOracle: already setted");

        expiryPrice.price = price;
        expiryPrice.timestamp = timestamp;

        emit ExpiryPriceUpdated(_aggregator, _expiryTimestamp, price);
    }

    /**
     * @notice update expiry price
     * anyone can update price if the price has not been setted
     * or if new price's timestamp is earlier than previous one.
     * Also timestamp must be later than expiration.
     */
    function updateExpiryPrice(
        address _aggregator,
        uint256 _expiryTimestamp,
        uint80 _roundId
    ) external {
        (uint256 price, uint256 timestamp) = getHistoricalPrice(_aggregator, _roundId);

        require(_expiryTimestamp < timestamp, "PriceOracle: price timestamp must be later than expiry");

        ExpiryPrice storage expiryPrice = expiryPrices[_aggregator][_expiryTimestamp];

        require(
            expiryPrice.timestamp == 0 || expiryPrice.timestamp > timestamp,
            "PriceOracle: new price's timestamp must be close to expiry"
        );

        expiryPrice.price = price;
        expiryPrice.timestamp = timestamp;

        emit ExpiryPriceUpdated(_aggregator, _expiryTimestamp, price);
    }

    /**
     * @notice get price for an expiration
     * @return price price scaled by 1e8
     * @return _isFinalized returns true if price has been finalized, if not returns false
     */
    function getExpiryPrice(address _aggregator, uint256 _expiryTimestamp)
        external
        view
        returns (uint256 price, bool _isFinalized)
    {
        price = expiryPrices[_aggregator][_expiryTimestamp].price;
        _isFinalized = isFinalized(_aggregator, _expiryTimestamp);
    }

    /**
     * @notice return flag if price is finalized or not
     * true if dispute period has been passed and price has been setted more than once
     */
    function isFinalized(address _aggregator, uint256 _expiryTimestamp) internal view returns (bool) {
        return
            (_expiryTimestamp + DISPUTE_PERIOD < block.timestamp) &&
            expiryPrices[_aggregator][_expiryTimestamp].timestamp != 0;
    }

    /**
     * @notice get price scaled by 1e8
     */
    function getPrice(address _aggregatorAddress) public view returns (uint256, uint256) {
        (, int256 answer, , uint256 roundTimestamp, ) = aggregators[_aggregatorAddress].latestRoundData();

        require(answer > 0, "PriceOracle: price is lower than 0");

        return (uint256(answer), roundTimestamp);
    }

    function getHistoricalPrice(address _aggregatorAddress, uint80 _roundId) public view returns (uint256, uint256) {
        (, int256 answer, , uint256 roundTimestamp, ) = aggregators[_aggregatorAddress].getRoundData(_roundId);

        require(answer > 0, "PriceOracle: price is lower than 0");

        return (uint256(answer), roundTimestamp);
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

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

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

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

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;

interface AggregatorV3Interface {

  function decimals() external view returns (uint8);
  function description() external view returns (string memory);
  function version() external view returns (uint256);

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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