DEV Community

Cover image for Fetch Real-Time Price Data in Solidity
Patrick Collins
Patrick Collins

Posted on • Updated on

Fetch Real-Time Price Data in Solidity

Introduction

Fetching data from outside Ethereum or whatever blockchain platform is something that most smart contract engineers need to really empower their dApps. Fetching reliable real-time price data in solidity can be the difference between having a powerful DeFi protocol and a quick "Get poor quick" scheme.

We've seen a number of incredibly successful defi projects already pull in real-world price data such as Aave, Synthetix, and yearn.finance. These are protocols at the moment that are securing billions of dollars in the defi space.

Having reliable price data means you can make protocols involving borrowing, lending, trading, synthetic assets, backing collateral, and so much more. Get the price data wrong, and you now have a chance to ruin millions of people's lives.

And just in time for Halloween, a nice spooky platform.

Dex with bad data

I'm having too much fun in this post already.

Price Data Quality

Whether you're fetching your data from a Stock API, Crypto API, or your cousin Larry is uploading coin prices for you, you're going to want to know where your price data is coming from, and you'll want to have that data decentralized if you're going to put it in a smart contract.

So if Larry really wants to be the price oracle for you, just make sure he isn't the only one to do it.

In our smart contracts, we need the data to be decentralized, otherwise we might as well just not build the application in blockchain. Having a centralized data provider in a decentralized system defeats the purpose of building on a decentralized platform in the first place!

So we want to pull from a network of Chainlink oracles to keep our data reliable and decentralized, and have the network pull data from multiple Cryptocurrency API and (if we want another asset class) Stock API providers.

There are currently two approaches, each approach involves using a blockchain oracle.

1. Chainlink Price Feeds

Chainlink Price Feeds are the easiest, most decentralized, and reliable way to fetch real-time price data in your solidity smart contracts. They pull data in from a network of Chainlink nodes and update and aggregate an answer on chain. You can see the responses of all the nodes so you know if any is being malicious.

The function to get the data is just a simple view function as well, so you don't even need to spend any gas to fetch the most recent price!

Here is a sample of how to get the latest ETH/USD price on Kovan, you can try deploying it on remix with this link.

pragma solidity ^0.6.7;

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

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Kovan
     * Aggregator: ETH/USD
     * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
     */
    constructor() public {
        priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        // If the round is not complete yet, timestamp is 0
        require(timeStamp > 0, "Round not complete");
        return price;
    }
}
Enter fullscreen mode Exit fullscreen mode

Once you deploy the contract on kovan, you can just call the getLatestPrice function, and boom, you've just fetched the price data!

This works because we know the proxy contract of the currency pair. We can find a list of supported pairs in the chainlink documentation. We can even get the fast gas price in solidity! Meaning, inside your smart contracts you can estimate how much it will cost in gas to make a certain execution.

The feeds.chain.link page has a number of visualizations to show more information on the price pairs, included when it was last updated, what the nodes are responding with, gas costs, and more.

Fetch price data from Chainlink Price Feeds

2. Chainlink API Calls

If you've read my previous blog on getting off-chain data in ethereum, you know that with Chainlink you can access any API of data source.

It's no different for fetching price data, you simply make several decentralized Chainlink API calls, and aggregate them on chain. If you haven't made a Chainlink API call before, I recommend either checking out my last blog or going through the example walkthrough.

Click here for a demo on remix that shows you how to get stock price data from Alpha Vantage on Ropsten.

You'd want to do this multiple times with multiple nodes and data providers to make sure that it's decentralized. If you do this, you'll basically have yourself a price feed.

Summary

These are some of the tools a number of the defi giants use to get data into their protocols. Let's see what you build out there! Be sure to ping me at @patrickalphac on twitter once you do, we'd love to see what you've built!

Also, join the Chainlink developers discord to join the community, learn, and grow!

Top comments (0)