Focus keywords and variations. Ex. blockchain oracles, APIs smart contracts

Solidity prices, smart contract price, fx feeds

Post URL. Short and descriptive (blog.chain.link/post-title)

/fetch-foreign-exchange-rates-in-solidity-smart-contracts

Publish date.

Tag. Education, Developers, etc.

Developers

Author. Default to Chainlink.

Chainlink

Excerpt. Not SEO-related. For blog post cards in Ghost. 180 characters max.

In this technical tutorial, learn how to use Chainlink Price Feeds to obtain real-time Foreign Exchange (FX) price data in your smart contract.

Meta title. 60 characters max.

Fetch Foreign Exchange Rates in Solidity Smart Contracts

Meta description. 156 characters max.

Learn how to use Chainlink to fetch tamper-proof Foreign Exchange (FX) price data in your Solidity smart contracts.

Canonical URL. Only use if you want to point to another Chainlink URL.

n/a

Image filenames, captions, and ALTs? Do all images have optimized filenames, captions, and alt text?

YES

Word count. At least 1,500 words.

~1000

Tweet. 280 characters - 23 characters link = 257 characters

The Foreign Exchange (FX) market averages over $6T in volume daily, representing a major opportunity for #DeFi derivatives. Learn how to use #Chainlink FX Price Feeds in your Solidity smart contracts to build advanced and hyper-reliable financial products.

Internally linked? Have you internally linked this post to other Chainlink posts?

YES/NO

Ghost link. The post URL in our Ghost CMS.

https://chainlink.ghost.io/ghost/#/editor/post/6023490e3be616003967d4ff

Fetch Foreign Exchange Rates in Solidity Smart Contracts

Price data is the centerpiece of various financial instruments, especially in decentralized finance (DeFi) applications. Foreign exchange (FX) rates are of particular interest within the DeFi space for creating options, futures, and other complex derivatives. In addition to fetching secure cryptocurrency price data, Chainlink Price Feeds can also be used to get high-quality FX Price Data in your smart contracts.

In this technical tutorial, we’ll walk through how you can use Chainlink FX Price Feeds in your Solidity smart contracts. First, let’s quickly go over what FX feeds are and what types of derivatives can be created by using them.

What Are FX feeds?

The foreign exchange market is a global market for the trading of currencies and has a daily volume of close to $7 trillion. This market determines foreign exchange rates for every currency and includes all aspects of buying, selling, and exchanging currencies at current or determined prices. Due to the high volume and popularity of this market, many DeFi applications use Chainlink FX Price Feeds to ensure that FX data is delivered to their derivatives contracts in a secure and decentralized manner, without any single point of failure.

Synthetix Exchange, a DeFi derivatives exchange, uses several FX price feeds provided by Chainlink oracles to ensure tamper-proof and accurate valuations in accordance with the real-world market price of their underlying assets, even during times of high volatility.

<How Synthetix Exchange uses Chainlink oracles to obtain real time market data of various FX currencies.>

<ALT: Synthetix Exchange synths being powered by the Chainlink network.>

How to Use Chainlink FX Price Feeds

Chainlink Price Feeds use hundreds of high-quality data sources and aggregate them through a decentralized network of Chainlink oracles that feed price data into reference contracts, where the results are again aggregated in an Aggregator Smart Contract as the latest, trusted answer. By using numerous sources of data aggregated by a decentralized network of nodes, Chainlink oracles ensure price data is of the highest quality and not vulnerable to exploits or price oracle attacks.

Creating the Smart Contract

To try using Chainlink FX Price Feeds in your smart contracts, first get testnet ETH to use as gas in your smart contract. Once you have some ETH, the easiest way to start building a smart contract that uses Chainlink FX Price Feeds is to deploy the Price Consumer contract. This is a basic contract for initiating requests for Chainlink Price Feeds. First, we need to import the AggregatorV3Interface contract interface which allows our smart contract to reference the on-chain Price Feeds on the Kovan testnet. An instance of it is then created in a local variable.

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

```AggregatorV3Interface internal priceFeed;```

In the constructor of the Price Feed reference contract, we can then initialize the address of the price feed we’re interested in. By exploring the Ethereum Price Feeds page in the documentation, we can find all the price feed contract addresses that Chainlink currently provides. Navigate to the Kovan portion of the page and choose a FX price feed. For the purposes of this example, we’ll choose the GBP/USD price feed whose address is 0x28b0061f44E6A9780224AA61BEc8C3Fcb0d37de9.

```priceFeed = AggregatorV3Interface(0x28b0061f44E6A9780224AA61BEc8C3Fcb0d37de9);```

A function has been defined called getLatestPrice to obtain the latest price from the Price Feed Aggregator contract that was instantiated in the constructor above. To do this, a new function was defined that calls the latestRoundData function from the Aggregator contract. This is the function that returns the current state of the Aggregator contract, and in this case we are taking the current price and returning it in our consuming function.

```   function getLatestPrice() public view returns (int) {

        (

            uint80 roundID,

            int price,

            uint startedAt,

            uint timeStamp,

            uint80 answeredInRound

        ) = priceFeed.latestRoundData();

        return price;

    }

```

Deploying and Testing the Smart Contract

Now we are ready to deploy and test our contract. Compile the contract in Remix, then on the deployment tab, change the environment to “Injected Web3”, and ensure the wallet address below is the one in your MetaMask wallet that contains some ETH obtained earlier, press the deploy button, and follow the steps. The end result is you have your smart contract deployed to the Kovan testnet. You should take note of the deployed contract address via the transaction output in the Remix console.

Once deployed, we simply need to execute the “getLatestPrice” function. The result should be that the function returns the latest price from the GBP/USD Aggregator contract, which can then be used on-chain in our smart contract. Take note that we didn’t need to send any LINK for the request, and we didn’t even use any ETH either since the transaction is a pure read of the data in the on-chain GBP-USD Aggregator contract.

<GBP/USD Price Feed result>

<ALT: GBP/USD Price Feed result>

Summary

Chainlink Price Feeds provide a reliable way to get high-quality FX price data into Solidity smart contracts. Moreover, Chainlink’s oracle framework provides the flexibility to quickly and easily fetch data around stocks, cryptocurrencies, commodities, and many other asset types.

If you’re a developer and want to quickly get your application connected to Chainlink Price Reference Data, visit the developer documentation and join the technical discussion in Discord.

More on This Topic

Website | Twitter | Discord | Reddit | YouTube | Telegram | Events | GitHub | Price Feeds | DeFi