Created
December 2, 2021 10:04
-
-
Save Misterhex/593ecb1fbeb31080dcd837daf22478e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.8.7; | |
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; | |
/** | |
* THIS EXAMPLE USES UN-AUDITED CODE. | |
* Network: Kovan | |
* Base: BTC/USD | |
* Base Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e | |
* Quote: EUR/USD | |
* Quote Address: 0x0c15Ab9A0DB086e062194c273CC79f41597Bbf13 | |
* Decimals: 8 | |
*/ | |
contract PriceConverter { | |
function getDerivedPrice(address _base, address _quote, uint8 _decimals) | |
public | |
view | |
returns (int256) | |
{ | |
require(_decimals > uint8(0) && _decimals <= uint8(18), "Invalid _decimals"); | |
int256 decimals = int256(10 ** uint256(_decimals)); | |
( , int256 basePrice, , , ) = AggregatorV3Interface(_base).latestRoundData(); | |
uint8 baseDecimals = AggregatorV3Interface(_base).decimals(); | |
basePrice = scalePrice(basePrice, baseDecimals, _decimals); | |
( , int256 quotePrice, , , ) = AggregatorV3Interface(_quote).latestRoundData(); | |
uint8 quoteDecimals = AggregatorV3Interface(_quote).decimals(); | |
quotePrice = scalePrice(quotePrice, quoteDecimals, _decimals); | |
return basePrice * decimals / quotePrice; | |
} | |
function scalePrice(int256 _price, uint8 _priceDecimals, uint8 _decimals) | |
internal | |
pure | |
returns (int256) | |
{ | |
if (_priceDecimals < _decimals) { | |
return _price * int256(10 ** uint256(_decimals - _priceDecimals)); | |
} else if (_priceDecimals > _decimals) { | |
return _price / int256(10 ** uint256(_priceDecimals - _decimals)); | |
} | |
return _price; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment