Implementing Oracles in Smart Contracts: Connecting Blockchain to Real-World Data

Yatharth
Simform Engineering
5 min readOct 12, 2023

Connecting Smart Contract to Asset Pricing Data: Chainlink Data Feeds

In the blockchain and decentralized applications world, smart contracts have revolutionized how agreements are executed. These self-executing contracts enable trustless transactions, automate processes, and eliminate the need for intermediaries. However, there’s a critical challenge that smart contracts face: they operate in isolation, unaware of events and data in the real world.

Imagine a scenario where you are a web3 enthusiast trying to develop an “EtherX” DeFi trading platform that allows users to trade various cryptocurrencies, such as Ethereum (ETH), without relying on centralized exchanges. Your platform thrives on real-time pricing data for ETH pairs. For example, when a trader swaps USDT for ETH, the current ETH price is not just a piece of data — it’s the heartbeat of your platform’s functionality.

This is where oracles, particularly Chainlink’s PriceFeed, come to the rescue. Chainlink’s PriceFeed oracle seamlessly integrates with EtherX to provide live and accurate price data for ETH/USD pairs, ensuring that every trade is executed at the most up-to-date rate.

What is Oracle?

We can define oracles as a bridge between the blockchain world and the real world. They play a pivotal role in enabling smart contracts and decentralized applications (dApps) to interact with and access external data and events.

Definition

An oracle is a trusted source of information that provides data or services to a blockchain network or smart contract. It acts as an intermediary between the decentralized world of blockchain and the centralized world of real-world data.

Types of Oracles

  • Data Oracle: Provides data from external sources, e.g., financial market data and API data.
  • Service Oracle: Executes specific tasks or services, e.g., sending emails and making payments.
  • Consensus Oracle: Relies on multiple data sources to reach a consensus, enhancing data reliability.
  • Decentralized Oracle: This is distributed and often uses multiple nodes to provide data, improving security and trust.

Chainlink DataFeed: Getting the Latest Price of ETH

Chainlink is a popular oracle network known for its decentralized and highly reliable oracles. It offers a wide range of data feeds and services, making it a preferred choice for many DeFi and blockchain projects.

Deploy and Run The Contract

Step 1: Open the Remix IDE

https://remix.ethereum.org/

Step 2: Create a New Contract PriceFeed.sol

On the left side, you will find the ‘default_workspace,’ and inside it, you will find a ‘contract’ folder. Create a new file named ‘PriceFeed.sol,’ by simply right-clicking on the ‘contract’ folder.

Step 3: Code for the Contract

Write the smart contract that can get the latest price of ETH.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceFeed{
AggregatorV3Interface internal dataFeed;
constructor(){
dataFeed=AggregatorV3Interface(0x694AA1769357215DE4FAC081bf1f309aDC325306);
}
function getLatestEthPriceInUSD() public view returns(int){
(,int answer,,,)=dataFeed.latestRoundData();
return answer;
}
}

This example contract obtains the latest price from the ETH / USD feed on the Sepolia testnet. You will require some amount of SepoliaETH in your account to pay a gas fee while deploying our smart contract on the Sepolia testnet. If you don’t have the Sepolia faucets, you can collect them here.

Let’s break down the code and try to understand how exactly we are getting the latest price of ETH.

  1. The import line imports the AggregatorV3Interface from Chainlink’s contracts. AggregatorV3Interface is the interface used to interact with Chainlink’s decentralized oracle network.
  2. Inside the contract, a state variable called dataFeed is declared. This variable is of type AggregatorV3Interface and is marked as internal. It will be used to store the address of the Chainlink PriceFeed oracle.
  3. The constructor function is called when the contract is deployed. In this constructor, the dataFeed variable is initialized with the address 0x694AA1769357215DE4FAC081bf1f309aDC325306. This address corresponds to a specific Chainlink PriceFeed oracle on the Sepolia testnet that provides the latest price of Ethereum (ETH) in USD. Essentially, this line sets up the oracle to be used for price data.
  4. Inside the getLatestEthPriceInUSD function, the latestRoundData function of the Chainlink PriceFeed oracle is called via dataFeed.latestRoundData(). This function returns various pieces of data, but the price is the second value in the returned tuple. The variable answer is used to capture this price value. The function then returns the answer, which represents the latest price of Ethereum (ETH) in USD as an integer.

Step 4: Compile the Smart Contract

On the left side, select Solidity compiler option and compile PriceFeed.sol .

Step 5: Deploy the Contract on Sepolia Chain

Go to the Deploy and run transaction option on the left side of the page and select Injected Provider — MetaMask environment. Make sure you are connected to the Sepolia network, and then click on theDeploy button. You will get the metamask pop-up to confirm the transaction and click on theConfirm button.

Step 6: Run "getLatestETHPrice()" Function

Once the contract is deployed successfully, on the left side down corner, you will find the PriceFeed contract under the Deployed Contracts section. You will find getLatestETHPrice method as a button, click on that button, and you will get the latest price of ETH in USD for the Sepolia testnet. The answer on the ETH / USD feed uses 8 decimal places, so an answer 163577610000 indicates an ETH / USD price of 1635.77610000.

Wrapping Up

As we wrap up our exploration of Chainlink’s Data Feeds and the deployment of our price-fetching contract, think of it as the beginning of your exciting adventure into the world of decentralized applications. Here, trust and accuracy are the guiding stars.

In conclusion, oracles are the linchpin that binds the blockchain to real-world data, opening doors to endless possibilities in DeFi, supply chain, insurance, prediction markets, gaming, and beyond. The integration of Chainlink’s Data Feeds and the seamless deployment of our price-fetching contract marks the beginning of your journey into the realm of decentralized applications, where trust and accuracy are paramount.

Follow Simform Engineering to keep up with the latest trends in the development ecosystem.

--

--