|
| 1 | +// SPDX-License-Identifier: UNLICENSED |
| 2 | +pragma solidity >=0.8.0; |
| 3 | + |
| 4 | +import { ERC20Upgradeable } from "openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol"; |
| 5 | + |
| 6 | +import { ICToken } from "../../external/compound/ICToken.sol"; |
| 7 | +import { MasterPriceOracle } from "../MasterPriceOracle.sol"; |
| 8 | +import { ICErc20 } from "../../external/compound/ICErc20.sol"; |
| 9 | +import "../../external/compound/IPriceOracle.sol"; |
| 10 | +import "../BasePriceOracle.sol"; |
| 11 | + |
| 12 | +interface AnkrOracle { |
| 13 | + function peek() external view returns (bytes32, bool); |
| 14 | +} |
| 15 | + |
| 16 | +contract AnkrBNBcPriceOracle is IPriceOracle, BasePriceOracle { |
| 17 | + MasterPriceOracle public immutable MASTER_PRICE_ORACLE; |
| 18 | + AnkrOracle private immutable ANKR_ORACLE; |
| 19 | + address public immutable BASE_TOKEN; |
| 20 | + address public immutable USD_TOKEN; |
| 21 | + uint256 private lastPrice = 0; |
| 22 | + |
| 23 | + constructor( |
| 24 | + AnkrOracle _ankrOracle, |
| 25 | + MasterPriceOracle masterPriceOracle, |
| 26 | + address _baseToken, |
| 27 | + address usdToken |
| 28 | + ) { |
| 29 | + MASTER_PRICE_ORACLE = masterPriceOracle; |
| 30 | + ANKR_ORACLE = _ankrOracle; |
| 31 | + USD_TOKEN = usdToken; |
| 32 | + BASE_TOKEN = _baseToken; |
| 33 | + } |
| 34 | + |
| 35 | + function getUnderlyingPrice(ICToken cToken) external view override returns (uint256) { |
| 36 | + // Return 1e18 for ETH |
| 37 | + if (cToken.isCEther()) return 1e18; |
| 38 | + |
| 39 | + // Get underlying token address |
| 40 | + address underlying = ICErc20(address(cToken)).underlying(); |
| 41 | + |
| 42 | + require(underlying == BASE_TOKEN, "Invalid underlying"); |
| 43 | + // Get price |
| 44 | + uint256 oraclePrice = _price(); |
| 45 | + |
| 46 | + // Format and return price |
| 47 | + uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals()); |
| 48 | + return |
| 49 | + underlyingDecimals <= 18 |
| 50 | + ? uint256(oraclePrice) * (10**(18 - underlyingDecimals)) |
| 51 | + : uint256(oraclePrice) / (10**(underlyingDecimals - 18)); |
| 52 | + } |
| 53 | + |
| 54 | + function price(address underlying) external view override returns (uint256) { |
| 55 | + require(underlying == BASE_TOKEN, "Invalid underlying."); |
| 56 | + return _price(); |
| 57 | + } |
| 58 | + |
| 59 | + function _price() internal view returns (uint256) { |
| 60 | + // aBNBc/BUSD price |
| 61 | + (bytes32 price, bool success) = ANKR_ORACLE.peek(); |
| 62 | + |
| 63 | + if (success) { |
| 64 | + uint256 BusdBnbPrice = MASTER_PRICE_ORACLE.price(USD_TOKEN); |
| 65 | + |
| 66 | + return (uint256(price) / 10**18) * BusdBnbPrice; |
| 67 | + } |
| 68 | + |
| 69 | + return 0; |
| 70 | + } |
| 71 | +} |
0 commit comments