Created
February 10, 2021 15:55
-
-
Save mcchan1/45bdda9da5cd0c06785e1f0f695602f2 to your computer and use it in GitHub Desktop.
Use Chainlink to convert US Dollars to ETH
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
pragma solidity ^0.8.0; | |
// SPDX-License-Identifier: MIT | |
import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; | |
contract PriceConsumerV3 { | |
AggregatorV3Interface internal priceFeed; | |
/** | |
* Network: Rinkeby | |
* Aggregator: ETH/USD | |
* Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e | |
*/ | |
constructor() public { | |
priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); | |
} | |
//convert amount and denominator to wei values with multipliers | |
//multipliers are needed for accurate division | |
function ethUSD(uint _amount) public view returns (uint) { | |
uint denominator = uint(getLatestPrice()); | |
uint256 ethInUsdAmount = _amount * 1000000000000000000000/denominator * 100000; | |
return ethInUsdAmount; | |
} | |
/** | |
* Returns the latest price of ETH/USD from Chain.link | |
*/ | |
function getLatestPrice() public view returns (int) { | |
( | |
uint80 roundID, | |
int price, | |
uint startedAt, | |
uint timeStamp, | |
uint80 answeredInRound | |
) = priceFeed.latestRoundData(); | |
return price; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
constructor(address _priceFeed) public { priceFeed = AggregatorV3Interface(_priceFeed); }
Use any of these priceFeed addresses https://docs.chain.link/docs/ethereum-addresses for different pairs