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

// File: contracts/oracle/AggregatorV3Interface.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

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: contracts/oracle/IPriceOracleV2.sol



//SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.16;

interface PriceOracle {
    function getUnderlyingPrice(address rToken) external view returns (uint256);
}

interface IPriceOracle is PriceOracle {
    function setRTokenToCToken(address rToken, address cToken) external;

    function setOracle(address newOracle) external;

    event SetRTokenToCToken(
        address indexed rToken,
        address oldCToken,
        address newCToken
    );

    event SetUnderlyingPrice(
        address indexed rToken,
        uint256 oldPrice,
        uint256 newPrice
    );

    event SetCTokenOracle(address oldOracle, address newOracle);
}

interface IPriceOracleV2 is IPriceOracle {
    enum OracleType {
        UNKNOW,
        MANUAL,
        COMPOUND,
        CHAINLINK
    }

    function setPriceCeiling(address rToken, uint256 value) external;

    function setRTokenToChainlinkOracle(
        address rToken,
        address newChainlinkOracle,
        uint256 maxTimeDelay
    ) external;

    function setRTokenToManualOracle(
        address rToken,
        address newChainlinkOracle
    ) external;

    function setRTokenToOracleType(
        address rToken,
        OracleType oracleType
    ) external;

    event SetPriceCeiling(
        address indexed rToken,
        uint256 oldPriceCap,
        uint256 newPriceCap
    );

    event SetChainlinkOracle(
        address indexed rToken,
        address oldOracle,
        address newOracle,
        uint256 maxTimeDelay
    );

    event SetManualOracle(
        address indexed rToken,
        address oldOracle,
        address newOracle
    );

    event SetRTokenToOracleType(address indexed rToken, OracleType oracleType);
}

// File: contracts/oracle/PriceOracleV2.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import "@openzeppelin/contracts/access/Ownable.sol";
import "./IPriceOracleV2.sol";
import "./AggregatorV3Interface.sol";

interface CTokenOracle {
    function getUnderlyingPrice(address cToken) external view returns (uint256);
}

interface CTokenLike {
    function underlying() external view returns (address);
}

interface IERC20Like {
    function decimals() external view returns (uint8);
}

contract PriceOracleV2 is IPriceOracleV2, Ownable {
    bool public constant isPriceOracle = true;
    CTokenOracle public cTokenOracle =
        CTokenOracle(0x50ce56A3239671Ab62f185704Caedf626352741e);

    mapping(address => OracleType) public rTokenToOracleType;
    mapping(address => address) public rTokenToCToken;

    struct ChainlinkOracleInfo {
        AggregatorV3Interface oracle;
        uint256 scaleFactor;
        uint256 maxTimeDelay;
    }

    mapping(address => ChainlinkOracleInfo) public rTokenToChainlinkOracle;

    struct ManualOracleInfo {
        AggregatorV3Interface oracle;
        uint256 scaleFactor;
    }

    mapping(address => ManualOracleInfo) public rTokenToManualOracle;
    mapping(address => uint256) public rTokenToUnderlyingPriceCap;

    uint internal constant lowerTimeDelay = 43200; // 12 hours
    uint internal constant upperTimeDelay = 172800; // 48 hours

    function getUnderlyingPrice(
        address rToken
    ) external view override returns (uint256) {
        uint256 price;

        OracleType oracleType = rTokenToOracleType[rToken];
        if (oracleType == OracleType.MANUAL) {
            price = getManualOraclePrice(rToken);
        } else if (oracleType == OracleType.COMPOUND) {
            address cTokenAddress = rTokenToCToken[rToken];
            price = cTokenOracle.getUnderlyingPrice(cTokenAddress);
        } else if (oracleType == OracleType.CHAINLINK) {
            price = getChainlinkOraclePrice(rToken);
        } else {
            revert("Oracle type not supported");
        }

        if (rTokenToUnderlyingPriceCap[rToken] > 0) {
            price = _min(price, rTokenToUnderlyingPriceCap[rToken]);
        }

        return price;
    }

    function setPriceCeiling(
        address rToken,
        uint256 value
    ) external override onlyOwner {
        uint256 oldPriceCap = rTokenToUnderlyingPriceCap[rToken];
        rTokenToUnderlyingPriceCap[rToken] = value;
        emit SetPriceCeiling(rToken, oldPriceCap, value);
    }

    function setRTokenToOracleType(
        address rToken,
        OracleType oracleType
    ) external override onlyOwner {
        rTokenToOracleType[rToken] = oracleType;
        emit SetRTokenToOracleType(rToken, oracleType);
    }

    function setRTokenToManualOracle(
        address rToken,
        address newManualOracle
    ) external override onlyOwner {
        address oldManualOracle = address(rTokenToManualOracle[rToken].oracle);

        _setRTokenToManualOracle(rToken, newManualOracle);
        emit SetManualOracle(rToken, oldManualOracle, newManualOracle);
    }

    function _setRTokenToManualOracle(
        address rToken,
        address manualOracle
    ) internal {
        require(
            rTokenToOracleType[rToken] == OracleType.MANUAL,
            "OracleType must be Manual"
        );
        address underlying = CTokenLike(rToken).underlying();
        rTokenToManualOracle[rToken].scaleFactor = (10 **
            (36 -
                uint256(IERC20Like(underlying).decimals()) -
                uint256(AggregatorV3Interface(manualOracle).decimals())));
        rTokenToManualOracle[rToken].oracle = AggregatorV3Interface(
            manualOracle
        );
    }

    function setOracle(address newOracle) external override onlyOwner {
        address oldOracle = address(cTokenOracle);
        cTokenOracle = CTokenOracle(newOracle);
        emit SetCTokenOracle(oldOracle, newOracle);
    }

    function setRTokenToCToken(
        address rToken,
        address cToken
    ) external override onlyOwner {
        address oldCToken = rTokenToCToken[rToken];
        _setRTokenToCToken(rToken, cToken);
        emit SetRTokenToCToken(rToken, oldCToken, cToken);
    }

    function _setRTokenToCToken(address rToken, address cToken) internal {
        require(
            rTokenToOracleType[rToken] == OracleType.COMPOUND,
            "OracleType must be Compound"
        );
        require(
            CTokenLike(rToken).underlying() == CTokenLike(cToken).underlying(),
            "cToken and rToken must have the same underlying asset"
        );
        rTokenToCToken[rToken] = cToken;
    }

    function getManualOraclePrice(
        address rToken
    ) public view returns (uint256) {
        require(
            rTokenToOracleType[rToken] == OracleType.MANUAL,
            "rToken is not configured for Manual oracle"
        );
        ManualOracleInfo storage manualInfo = rTokenToManualOracle[rToken];
        (
            uint80 roundId,
            int256 answer,
            ,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = manualInfo.oracle.latestRoundData();
        require(answeredInRound >= roundId);
        require(answer >= 0, "Price cannot be negative");
        return uint256(answer) * manualInfo.scaleFactor;
    }

    function setRTokenToChainlinkOracle(
        address rToken,
        address newChainlinkOracle,
        uint256 maxTimeDelay
    ) external override onlyOwner {
		require(
		    maxTimeDelay >= lowerTimeDelay && maxTimeDelay <= upperTimeDelay,
		    "maxTimeDelay must be within bounds"
		);
        address oldChainlinkOracle = address(
            rTokenToChainlinkOracle[rToken].oracle
        );
        _setRTokenToChainlinkOracle(rToken, newChainlinkOracle, maxTimeDelay);
        emit SetChainlinkOracle(
            rToken,
            oldChainlinkOracle,
            newChainlinkOracle,
            maxTimeDelay
        );
    }

    function _setRTokenToChainlinkOracle(
        address rToken,
        address chainlinkOracle,
        uint256 maxTimeDelay
    ) internal {
        require(
            rTokenToOracleType[rToken] == OracleType.CHAINLINK,
            "OracleType must be Chainlink"
        );
        address underlying = CTokenLike(rToken).underlying();
        rTokenToChainlinkOracle[rToken].scaleFactor = (10 **
            (36 -
                uint256(IERC20Like(underlying).decimals()) -
                uint256(AggregatorV3Interface(chainlinkOracle).decimals())));
        rTokenToChainlinkOracle[rToken].oracle = AggregatorV3Interface(
            chainlinkOracle
        );
        rTokenToChainlinkOracle[rToken].maxTimeDelay = maxTimeDelay;
    }

    function getChainlinkOraclePrice(
        address rToken
    ) public view returns (uint256) {
        require(
            rTokenToOracleType[rToken] == OracleType.CHAINLINK,
            "rToken is not configured for Chainlink oracle"
        );
        ChainlinkOracleInfo storage chainlinkInfo = rTokenToChainlinkOracle[
            rToken
        ];
        (
            uint80 roundId,
            int256 answer,
            ,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = chainlinkInfo.oracle.latestRoundData();
        require(answeredInRound >= roundId);
        require(answer >= 0, "Price cannot be negative");
        require(
            updatedAt >= block.timestamp - chainlinkInfo.maxTimeDelay,
            "Chainlink price data is stale"
        );
        return uint256(answer) * chainlinkInfo.scaleFactor;
    }

    function _min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }
}