Fetch Real-Time Price Data in Solidity
Tags: blockchain, solidity, price, stock
Published: 2020-10-30 00:56:03

# Introduction

[Fetching data](https://blog.chain.link/fetch-current-crypto-price-data-solidity/) 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](https://aave.com/), [Synthetix](https://www.synthetix.io/), and [yearn.finance](https://yearn.finance/). These are protocols at the moment that are [securing billions of dollars in the defi space](https://defipulse.com/). 

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](https://dev-to-uploads.s3.amazonaws.com/i/rv8p48s9rbwbeq3ss7eq.png)
 
I'm having too much fun in this post already.

# Price Data Quality

Whether you're fetching your data from a [Stock API](https://medium.com/@patrick.collins_58673/stock-api-landscape-5c6e054ee631), [Crypto API](https://www.coingecko.com/en), 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](https://feeds.chain.link/) 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](https://medium.com/better-programming/what-is-a-blockchain-oracle-f5ccab8dbd72). 

## 1. Chainlink Price Feeds

[Chainlink Price Feeds](https://docs.chain.link/docs/get-the-latest-price) 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](https://docs.chain.link/docs/architecture-decentralized-model) 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](https://www.tutorialspoint.com/solidity/solidity_view_functions.htm) 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](https://remix.ethereum.org/#version=soljson-v0.6.7+commit.b8d736ae.js&optimize=false&evmVersion=null&gist=0c5928a00094810d2ba01fd8d1083581).

```javascript
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;
    }
}
```

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](https://docs.chain.link/docs/reference-contracts) 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](https://feeds.chain.link/eth-usd) 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](https://dev-to-uploads.s3.amazonaws.com/i/8y6q9asi56hp0sss72ku.png)

## 2. Chainlink API Calls

If you've read my previous blog on getting [off-chain data in ethereum](https://dev.to/patrickalphac/off-chain-data-in-ethereum-how-to-access-4395), 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](https://docs.chain.link/docs/make-a-http-get-request), 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](https://docs.chain.link/docs/example-walkthrough). 

[Click here for a demo on remix](https://remix.ethereum.org/#version=soljson-v0.6.12+commit.27d51765.js&optimize=false&gist=51c6a80fd90b460aa9c1cd61bab78ea0) 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](https://discord.gg/2YHSAey) discord to join the community, learn, and grow!