Loading...
Many dapps require the real market price of any crypto currency in usd and getting this price in app and sending to smart contract is bit risky. So one option is to get the real time price in contract itself. chainlink offers this functionality and lets see hot to do it..
now head over to the remix IDE and create new solidity file. the following is the code to get the price feed
pragma solidity ^0.6.7;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
contract RealTimePrice {
AggregatorV3Interface internal priceFeed;
constructor() public {
priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
}
function getThePrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
}
pragma solidity ^0.6.7;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
contract RealTimePrice {
AggregatorV3Interface internal priceFeed;
constructor() public {
priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
}
...
the address 0x9326BFA02ADD2366b30bacB125260Af641031331 is used for ETH/USD and that too for Kovan testnet.
you can get your required smart contract address for your required pair and network on chainlink official docs here
Chainlink supports many blockchains like ethereum, polygon, bsc, xdai, avalanche etc , so choose your blockchain then price pair and network you will get smart contract id
unction getThePrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
This function return the real time value of ether in usd now. Note that this has decimal of 8. From above step once you pick smart contract address there in that table only they have also given decimal.
The output for this example will be like this -> int256: 214139672966 :: this give me the real time price of ethere in usd at the time of writing this smartbook. now note the value is big because this is 8 decimal the value will be 2141.39672966 usd actully.
----------