An Vo
An Vo's Blog

An Vo's Blog

How to get a real-time token price in Ethereum smart contract using Chainlink Data Feeds service

An Vo's photo
An Vo
·Sep 7, 2022·

2 min read

We will use Remix to code a contract that can get token real-time price, for example, ETH.

First, we need to check the Chainlink document to see the code to get the latest price: docs.chain.link/docs/get-the-latest-price

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Goerli
     * Aggregator: ETH/USD
     * Address: 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
     */
    constructor() {
        priceFeed = AggregatorV3Interface(0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            /*uint80 roundID*/,
            int price,
            /*uint startedAt*/,
            /*uint timeStamp*/,
            /*uint80 answeredInRound*/
        ) = priceFeed.latestRoundData();
        return price;
    }
}

There are 4 things to consider:

  1. The AggregatorV3Interface: Contain the real-time token price updated from Chainlink decentralized oracle network.
  2. import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; : The address for Remix to import contract from npm (https://www.npmjs.com/package/@chainlink/contracts)
  3. getLatestPrice(): The function to get the latest price from the Aggregator contract
  4. 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e: The address of the Aggregator instance that contain ETH/USD pair price information. Other pairs can be checked here (for example Goerli): docs.chain.link/docs/ethereum-addresses/#Go..

With this knowledge, let's build a simple contract that can show the ETH price:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract GetTokenPrice {
    function getPrice() public view returns(uint256) {
        AggregatorV3Interface priceFeed = AggregatorV3Interface(0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e);
        (, int price,,,) = priceFeed.latestRoundData();
        return uint256(price / 1e8);
    }
}

Note that we just want to get price, so we just need to put the price variable with commas in the return list (, int price,,,) The decimal of the Aggregator contract is 8, so we need to divide by 10^8 (1e8) to get the price in USD.

Deployed and call the getPrice() function, we will get this result (1 ETH = $1520)

image.png

This is the way to get the token price, for other tokens and other networks, change the address get from the reference page: docs.chain.link/docs/reference-contracts

 
Share this