Fetch Commodity Prices in Solidity Smart Contracts
Secure, up-to-date price data is the centerpiece of many financial applications, often used to trigger transactions and derive other instruments and products, especially in decentralized finance (DeFi) protocols. Synthetic tokens based on commodity price data are of major interest within the DeFi space for creating decentralized options, futures, and other complex derivatives. In addition to fetching secure cryptocurrency price data, Chainlink Data Feeds can also be used to get high-quality commodity price data in your smart contracts so you can launch these more sophisticated financial products.
In this technical tutorial, we’ll walk through how you can use Chainlink Commodity Data Feeds in your Solidity smart contracts. First, let’s quickly go over what commodity feeds are and what types of derivatives can be created by using them.
What Are Commodity Data Feeds?
The commodity exchange market is a global market for the trading of raw products such as gold and oil. Due to the high volume and popularity of this market, many DeFi applications use Chainlink Commodity Data Feeds to ensure that commodity price data is delivered to their derivatives contracts in a secure and decentralized manner, without any single point of failure.
For example, Synthetix Exchange, a leading DeFi derivatives exchange, uses several commodity 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 to Use Chainlink Commodity Data Feeds
Chainlink Data 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 and multiple levels of aggregation within a decentralized network of nodes, Chainlink oracles ensure price data is of the highest quality and reflects broad market coverage, protecting the data feed from sudden volume shifts and price oracle attacks.
Creating the Smart Contract
To start using Chainlink Commodity Data 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 Commodity Data Feeds is to deploy the Price Consumer contract. This is a basic template contract for initiating requests for Chainlink Data Feeds. First, we need to import the AggregatorV3Interface contract interface, which allows our smart contract to reference the on-chain Data Feeds on the Kovan testnet. An instance of it is then created in a local variable.
Note: this tutorial is in Remix but does mention Node.js syntax, such as in the following import statement:
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 Chainlink 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 commodity price feed. For the purposes of this example, we’ll choose the XAU/USD Price Feed, the Philadelphia Gold and Silver Index, whose address is 0xc8fb5684f2707C82f28595dEaC017Bfdf44EE9c5.
priceFeed = AggregatorV3Interface(0xc8fb5684f2707C82f28595dEaC017Bfdf44EE9c5);
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 XAU/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 XAU-USD Aggregator contract.
Summary
Chainlink Data Feeds provide a hyper-reliable mechanism for getting high-quality commodity price data into Solidity smart contracts so you can build new DeFi derivatives around real-world asset data. Moreover, Chainlink’s oracle framework provides the flexibility to quickly and easily fetch secure data around stocks, cryptocurrencies, stablecoins, indexes, and many other asset types, giving smart contract developers a robust data infrastructure to power the next wave of DeFi innovation.
If you’re a developer and want to quickly get your application connected to Chainlink Data Feeds, visit the developer documentation and join the technical discussion in Discord.