How do I get the current prices of eth, BTC and other cryptocurrencies in solidity

Time:2021-11-19

Original link: https://blog.chain.link/fetch-current-crypto-price-data-solidity/
Original title:_ How to Fetch the Current Price of Ethereum, Bitcoin, and Other Cryptocurrencies in Solidity_
Original author: Harry papacharissiou

Obtaining price data in a solid smart contract is a common requirement for defi applications. In solidity, in order to obtain the price of eth, BTC or other cryptocurrencies, you can do it in one of the following two ways:

  • Use chainlink’s feed price to obtain price data
  • Obtain price data through chainlink Oracle using external API

In this technical tutorial, we will explain these two methods in detail and share code cases to help you build, deploy and test smart contracts. First, let’s quickly understand the importance of data quality and end-to-end decentralization when providing external data for smart contracts.

The demand of smart contracts for accurate and reliable price data

This year, the total lock-in value of defi has surged from US $680 million in January to US $14 billion now. These defi protocols rely on external price data as the data source, because the blockchain cannot directly access external data locally. In addition, these applications need to provide data protection to protect applications from exploits, such as price Oracle attacks.

Chainlink pricing can reduce the risk of these attacks by providing data aggregated from a variety of high-quality data providers and inputting the data into the chain through the decentralized oracle on the chainlink network. Chainlink’s decentralized Oracle mechanism can ensure that the final price data reflects a wide range of market information coverage, which means that the final price data is determined after summarizing various price data in the whole market, not just a small part of the information, but also considering other factors, such as trading volume and liquidity.

Now that we understand the demand for accurate and reliable price data of solid smart contract and the important role of chainlink feed price Oracle, we will explain in detail the case of using chainlink feed price to obtain the latest Ethereum price data. The following steps can also be applied to bitcoin and other cryptocurrencies.

Using chainlink to feed prices on Ethereum

Chainlink pricing uses a variety of high-quality data inputs, aggregates these data through the decentralized network of chainlink Oracle, and inputs the price data into the reference contract. These data results will be aggregated into the latest price data in the aggregator smart contract as a reliable answer. Using multiple data sources aggregated by multiple nodes, we can ensure that our price data reaches the highest quality and will not be attacked by vulnerability exploitation or price oracle.

Create smart contract

The first step is to obtain the ETH of the test network as the gas fee of the smart contract. After obtaining some eth, the easiest way to build a smart contract fed by chainlink is to start with the standard price consumer contract. This is the basic contract used to start the price feeding request for chainlink. This part is for demonstration purposes. We will use eth / USD pricing already defined in the standard price consumer contract, but we will explain the code in detail so that you can understand its working principle.

First, we can see that the aggregatorv3interface contract interface is imported. In this way, our smart contract can reference the price feeding contract deployed in the Kovan test network. Next, we create a contract instance and save it to a local variable.

import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
AggregatorV3Interface internal priceFeed;

Next, we can see that the feed reference contract is initialized in the constructor. The ETH / USD price reference contract on Kovan test network is deployed at the address_ 0x9326BFA02ADD2366b30bacB125260Af641031331_ Come on.

priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);

Then we see a defined function to obtain the latest price data from the feed aggregation contract, which is instantiated in the constructor mentioned above. To get the price, we define a new function from the aggregator(Aggregator)The latestRoundData function is called in the contract. This is the return aggregator(Aggregator)In this case, we take the current price and return it to the consumption function.

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

Deploy and test smart contracts

Now we are ready to deploy and test our contract. Compile the contract in remix, and then on the deployment option, change the environment to“Injected Web3”, and make sure that the wallet address below is the wallet address of eth previously obtained in your metamask wallet, click the deploy button, and then follow the steps. The end result is that you deploy the smart contract to the Kovan test network. You need to record the deployed contract address recorded through the transaction output in the remix console.

After deployment, we only need to execute“getLatestPrice”Function. The result should be the latest price returned by the function from the ETH / USD aggregator contract, and then the data can be called on our smart contract chain. Note that we do not need to send any link tokens for the request, nor do we use any eth. This transaction is purely to read the data in the eth-usd aggregator contract on the chain.

How do I get the current prices of eth, BTC and other cryptocurrencies in solidity
Eth / USD price feeding results

Get other price data in solidity

Chainlink feed price provides a large number of price data of the defi price pair at the head. If the asset price data you need to obtain in your smart contract is not covered by the existing feeding contract, such as the price of a specific stock, you can customize the chainlink Oracle to call any external API. The easiest way to use chainlink Oracle to obtain external price data is to start with the API consumer contract of standard chainlink. This is a standardized contract to start external data requests through the chainlink oracle.

After creating the API consumer contract, you can find the API from which you want to obtain price data. For example, you can use the alpha vantage API to find the current price of IBM shares.

With the API endpoint, you only need to set the correct parameters in the contract and send the request to the chainlink oracle. You can find information about this and how to use the standard in the chainlink documentationAPIConsumerMore information about the contract.

Remember that in a production environment, you will want to decentralize this use method or obtain this specific data from the feeding contract itself.

summary

Chainlink price feeding provides a reliable way to obtain high-quality bitcoin, Ethereum and other cryptocurrency price data into the solid smart contract. In addition, chainlink’s Oracle framework also provides the flexibility to quickly and easily obtain other price data, such as the price data of stocks, commodities and other assets.

If you are a developer, you want to quickly connect your application to chainlink’s price reference data, access developer documentation, and access discord technology discussion.
English channels
Website | Twitter | Reddit | YouTube | Telegram | Events | GitHub | Price Feeds | DeFi
Chinese Channel
Chinese official website | segmentfault | CSDN|