// File: contracts/oracle/OracleRouter.sol



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

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

/**
 * Oracle set to retrieve the price of an asset in dollars with 8 decimals.
 * @dev If feed not exist admin can set a price fixed for the asset
 * @dev When adding a feed for a stablecoin asset, set the '_isStablecoin' variable to true
 *  to enable checking for stablecoins that cannot deviate in price by more than 30% from 1 USD.
 * @dev Use "setFeed(address _asset, address _feed, uint _priceAdmin, bool _isStablecoin)" to add a new asset.
 * @dev Use "price(address _asset)" to retrieve the price of an asset in USD with 8 decimal
 */
contract OracleRouter is Ownable {
    uint256 constant MIN_DRIFT = uint256(70000000);
    uint256 constant MAX_DRIFT = uint256(130000000);

    struct FeedStruct {
        address feedAddress;
        uint priceAdmin;
        uint heartbeat;
        bool isStablecoin;
    }
    mapping(address => FeedStruct) public assetToFeed;

    function setFeed(address _asset, address _feed, uint _priceAdmin, uint _heartbeat, bool _isStablecoin) external {
        require(_feed == address(0) || _priceAdmin == 0, "cannot set feed and priceAdmin at same time");
        assetToFeed[_asset].feedAddress = _feed;
        assetToFeed[_asset].priceAdmin = _priceAdmin;
        assetToFeed[_asset].heartbeat = _heartbeat;
        assetToFeed[_asset].isStablecoin = _isStablecoin;
    }

    /**
     * @dev The price feed contract to use for a particular asset and if is a stablecoin.
     * @param _asset address of the asset
     */
    function getFeed(address _asset) public view returns (address, uint, uint, bool) {
        return (assetToFeed[_asset].feedAddress, assetToFeed[_asset].priceAdmin, assetToFeed[_asset].heartbeat, assetToFeed[_asset].isStablecoin);
    }

    /**
     * @notice Returns the total price in 8 digit USD for a given asset.
     * @param _asset address of the asset
     * @return uint256 USD price of 1 of the asset, in 8 decimal fixed
     */
    function price(address _asset) external view virtual returns (uint, uint) {
        (address feed, uint priceAdmin, uint heartbeat, bool isStablecoin) = getFeed(_asset);
        if(feed == address(0)) {
            return (priceAdmin, 2);
        }
        (, int256 iPrice, uint startedAt, ,) = AggregatorV3Interface(feed).latestRoundData();
        uint8 decimals = AggregatorV3Interface(feed).decimals();
        require(verifyTimestampRound(startedAt, heartbeat), "feed price is not updated");
        uint256 priceRoundData = uint256(iPrice);
        if (isStablecoin) {
            require(priceRoundData <= MAX_DRIFT, "Oracle: Price exceeds max");
            require(priceRoundData >= MIN_DRIFT, "Oracle: Price under min");
        }
        return (priceRoundData, uint(decimals));
    }

    function verifyTimestampRound(uint _timestampRound, uint _heartbeat) public view returns (bool) {
        return (block.timestamp - _timestampRound) <= _heartbeat;
    }
}

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



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

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

  function version() external view returns (uint256);

  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/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

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() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

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) {
        return msg.data;
    }
}