How To Retrieve The Latest Crypto Prices From A Smart Contract | Travis Media (2024)

Using Chainlink Data Feeds, you can retrieve the latest price of a crypto asset from your smart contract in real-time. In this post, I’ll show you step-by-step how to retrieve price data in Solidity using the Remix IDE.

Quick Nav

  1. Why Can’t We Call Off-Chain APIs?
  2. How To Get The Latest Prices From Your Smart Contract
  3. 1. Add a Testnet to your MetaMask wallet
  4. 2. Find the Data Feed Address For Your Chain and Crypto Pair
  5. 3. Add the code to your Solidity smart contract
  6. 4. Deploy To Metamask and Test
  7. Conclusion

Why Can’t We Call Off-Chain APIs?

What’s the problem with calling APIs from a smart contract?

Well, the whole point of the blockchain is immutability and consistency. All nodes in the network should be able to replay transactions with the same results.

APIs introduce the possibility of variable data which is the enemy to the blockchain. When I make a query for a price, it will differ 30 minutes from now and will return different results day to day.

Well, Chainlink has introduced the concept oforaclesto solve this problem, and they do so by posting data on the blockchain itself. They do the API calls for you periodically, and post the results on the blockchain for you, and others, to reference without any difference. Essentially, it’s an on-chain API.

The decentralized oracle handles the security of these calls as well, which is obviously a concern when calling out from an immutable smart contract.

And one, of many, popular use cases for using oracles is to retrieve up-to-date crypto price feeds from your smart contracts.

That’s what we will tackle today.

You can read more about Chainlink oracleshere.

How To Get The Latest Prices From Your Smart Contract

Thankfully, documentation for getting the latest price from a Chainlink Data Feed iswell written.

Well…. until you try it out in your Remix IDE and it gives you the following error:

“The transaction has been reverted to the initial state.Note: The called function should be payable if you send value and the value you send should be less than your current balance.Debug the transaction to get more information.”

Ugh. I wrestled with this one for about an hour.

The (now obvious) problem is that you cannot use Remix’s JavaScript VM Environment to virtually deploy your contract and then expect it to reach out to Chainlink’s provided Price Feed’s addresses on particular chains. You can only call this from a mainnet or a testnet of some sort, where the prices are posted regularly.

Thus, you need to use the Injected Web3 Environment with Metamask.

Here are the steps:

1. Add a Testnet to your MetaMask wallet.

This can be ETH (Kovan or Rinkeby), Binance Smart Chain (Testnet), etc.

Google how to add the one you need, it’s all over the web.

I’ll be using the Binance Smart Chain Testnet for my example today. If you open Metamask, click on the Networks and choose ‘Add Network.’ Then add this Testnet with the following values:

How To Retrieve The Latest Crypto Prices From A Smart Contract | Travis Media (1)

Now switch to that network.

Also, add grab some test BNB fromthisfaucet.

2. Find the Data Feed Address For Your Chain and Crypto Pair

Let’s say I want the ETH/USD price on the Kovan Testnet. I would look at the Ethereum addresseshereand find the address of the price pair that I want.

Let’s say I want the BNB/USD price on the Binance Smart Chain Testnet. I would look at the BNB chain addresseshereand find my address. We’ll be using (at the time of this writing), 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526 which is the BNB / USD pair.

3. Add the code to your Solidity smart contract

Then, integrate the following code into your smart contract:

// SPDX-License-Identifier: MITpragma solidity ^0.8.7;import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";contract PriceConsumerV3 { AggregatorV3Interface internal priceFeed; /** * Network: BSC Testnet * Aggregator: BNB/USD * Address: 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526 */ constructor() { priceFeed = AggregatorV3Interface(0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( /*uint80 roundID*/, int price, /*uint startedAt*/, /*uint timeStamp*/, /*uint80 answeredInRound*/ ) = priceFeed.latestRoundData(); return price; }}

Remember, you can deploy your ETH contract on the Binance Smart Chain.

4. Deploy To Metamask and Test

Now choose Injected Web3 as your Environment in Metamask and deploy your contract to the BSC Testnet.

Now choose the getLatestPrice() function and voila!!

42727000000

How To Retrieve The Latest Crypto Prices From A Smart Contract | Travis Media (2)

Uh, wait… what is this long number??

Well, remember that BSC uses an 8 decimal system (ETH uses 18), so to see the number we are used to, we need to fix that by dividing by 10 ** 8:

return price / 10 ** 8

…which will get you 427:

How To Retrieve The Latest Crypto Prices From A Smart Contract | Travis Media (3)

There you have it!

Conclusion

Chainlink oracles provide a safe and blockchain-compatible way to access off chain data. Be sure to read up on it’s other use cases like generating averified random number(VRF) or properlyrequesting and receiving ANY data off chain.

Hope you found this tutorial helpful. Let’s discuss below.

How To Retrieve The Latest Crypto Prices From A Smart Contract | Travis Media (2024)
Top Articles
The Health Risks of a Dirty Carpet | Carlson
Which Personality Type Makes the Best Counselors? - Carlow University
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
DENVER Überwachungskamera IOC-221, IP, WLAN, außen | 580950
Is Sportsurge Safe and Legal in 2024? Any Alternatives?
Klustron 9
Sprague Brook Park Camping Reservations
Stl Craiglist
Locate Td Bank Near Me
Ucf Event Calendar
Pollen Count Central Islip
Cincinnati Bearcats roll to 66-13 win over Eastern Kentucky in season-opener
Programmieren (kinder)leicht gemacht – mit Scratch! - fobizz
Bc Hyundai Tupelo Ms
How to Store Boiled Sweets
Diesel Mechanic Jobs Near Me Hiring
Jenn Pellegrino Photos
Unterwegs im autonomen Freightliner Cascadia: Finger weg, jetzt fahre ich!
12 Top-Rated Things to Do in Muskegon, MI
College Basketball Picks: NCAAB Picks Against The Spread | Pickswise
Bjerrum difference plots - Big Chemical Encyclopedia
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Page 2383 – Christianity Today
27 Modern Dining Room Ideas You'll Want to Try ASAP
Ardie From Something Was Wrong Podcast
Frank Vascellaro
Ordensfrau: Der Tod ist die Geburt in ein Leben bei Gott
Transformers Movie Wiki
Great Clips On Alameda
Tgh Imaging Powered By Tower Wesley Chapel Photos
Rocketpult Infinite Fuel
About Us | SEIL
Rogers Centre is getting a $300M reno. Here's what the Blue Jays ballpark will look like | CBC News
The 50 Best Albums of 2023
10 games with New Game Plus modes so good you simply have to play them twice
Anhedönia Last Name Origin
The Angel Next Door Spoils Me Rotten Gogoanime
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Stranahan Theater Dress Code
Login
Bekkenpijn: oorzaken en symptomen van pijn in het bekken
Random Animal Hybrid Generator Wheel
Dyi Urban Dictionary
Paperlessemployee/Dollartree
Jane Powell, MGM musical star of 'Seven Brides for Seven Brothers,' 'Royal Wedding,' dead at 92
Gonzalo Lira Net Worth
Mit diesen geheimen Codes verständigen sich Crew-Mitglieder
All Buttons In Blox Fruits
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6602

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.