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 the foreign exchange 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 price feeds for foreign exchange rates 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.
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.
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.