-
Notifications
You must be signed in to change notification settings - Fork 4
/
LibUsdOracle.sol
75 lines (62 loc) · 2.49 KB
/
LibUsdOracle.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* SPDX-License-Identifier: MIT
**/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import {LibEthUsdOracle} from "./LibEthUsdOracle.sol";
import {LibWstethUsdOracle} from "./LibWstethUsdOracle.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {C} from "contracts/C.sol";
/**
* @title Eth Usd Oracle Library
* @notice Contains functionalty to fetch the manipulation resistant USD price of different tokens.
* @dev currently supports:
* - ETH/USD price
**/
library LibUsdOracle {
using SafeMath for uint256;
function getUsdPrice(address token) internal view returns (uint256) {
return getUsdPrice(token, 0);
}
/**
* @dev Returns the price of a given token in in USD with the option of using a lookback. (Usd:token Price)
* `lookback` should be 0 if the instantaneous price is desired. Otherwise, it should be the
* TWAP lookback in seconds.
* If using a non-zero lookback, it is recommended to use a substantially large `lookback`
* (> 900 seconds) to protect against manipulation.
*/
function getUsdPrice(address token, uint256 lookback) internal view returns (uint256) {
if (token == C.WETH) {
uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice(lookback);
if (ethUsdPrice == 0) return 0;
return uint256(1e24).div(ethUsdPrice);
}
if (token == C.WSTETH) {
uint256 wstethUsdPrice = LibWstethUsdOracle.getWstethUsdPrice(lookback);
if (wstethUsdPrice == 0) return 0;
return uint256(1e24).div(wstethUsdPrice);
}
revert("Oracle: Token not supported.");
}
function getTokenPrice(address token) internal view returns (uint256) {
return getTokenPrice(token, 0);
}
/**
* @notice returns the price of a given token in USD (token:Usd Price)
* @dev if ETH returns 1000 USD, this function returns 1000
* (ignoring decimal precision)
*/
function getTokenPrice(address token, uint256 lookback) internal view returns (uint256) {
if (token == C.WETH) {
uint256 ethUsdPrice = LibEthUsdOracle.getEthUsdPrice(lookback);
if (ethUsdPrice == 0) return 0;
return ethUsdPrice;
}
if (token == C.WSTETH) {
uint256 wstethUsdPrice = LibWstethUsdOracle.getWstethUsdPrice(0);
if (wstethUsdPrice == 0) return 0;
return wstethUsdPrice;
}
revert("Oracle: Token not supported.");
}
}