Blog

How To Build Your Own Oracle Using Ethereum Smart Contracts?

build your own oracle

Table of Contents

Read Time: 5 minutes

Ethereum is the first-ever blockchain to inherit the qualities of creating dapps, trading crypto assets on the blockchain, and so on.

It has its programming language to write smart contracts and implement them on the Ethereum virtual machine to infuse decentralisation in performing activities. 

Smart contracts execute the pre-defined lines of codes and fulfil the intended task. But what if we want to make the smart contracts function based on the results of the real-time happening?

To achieve this, we need to understand the concept of blockchain oracles through which smart contracts can receive inputs from the real world. 

What is an oracle in crypto, and how to create an oracle in the Ethereum Smart contract? We shall discuss this in detail in the following section. 

Key Topics Of The Blog

  • What is a crypto oracle, and how do oracles work
  • Different types of oracles
  • The flow of data from oracles to Ethereum smart contracts
  • How to code Ethereum oracles
  • Issues with crypto oracle

What Is An Oracle, And Why Is It Needed?

Oracles are entities that act as a bridge connecting the blockchain with external systems. In other words, oracles provide the off-chain events data to the smart contract to perform an action based on the input.

For example, in betting events, users are allowed to bet on the players they think will win the match. Based on the real-time happening, rewards are distributed to the users who bet on the winner. 

Blockchain oracles help supplement data about the winner to the smart contracts. The data flow on oracle is bi-directional and can be used to translate any real-time data from weather reports to stock market status to smart contracts. 

Every node in the Ethereum blockchain possesses information about the transactions, which ought to be uniform. Therefore, fetching data from APIs could result in discrepancies. In contrast, oracle loads the data on the blockchain, which immutably appears the same on all the nodes.

Blockchain Oracles
Blockchain Oracles

How To Access Data From Oracle?

Smart contracts use the request-and-response cycle to gain information from the oracle node. The oracle implemented with an HTTP GET will receive the request from the smart contract, and the callback function can retrieve the requested data from the oracle. 

In this way, data are collected by the smart contract from the oracle. Each oracle is configured to provide specific information, and you can seek third-party services to acquire the data you look for. 

Here are some of the oracle services

  • Chainlink
  • Provable
  • Witnet
  • Paralink and so on.

Classification Of Oracles

Oracles are categorised into various types depending on fetching, validating, and transferring the data. 

Input oracles: The most widely recognised type where the data are fetched off-chain from the real-time happenings. For ex. Price feeds on stocks are obtained from off-chain to trigger action on smart contracts based on financial market conditions.

Output oracles: The vice verse of input oracles where the smart contracts provoke the oracle to execute the action. For ex. Send signals to the storage provider to store the data or initiate bank networks to make payments.

Cross-chain oracles: Cross-chain oracles facilitate both reading and writing data on different blockchains. It also makes it possible to trigger events in one blockchain and make them operative on another. 

Compute-enabled oracles: Compute-enabled oracles make use of off-chain computation to provide services. Especially when on-chain is not reliable due to technical or financial constraints, this type of oracle is used.

Data Fetching From Oracles

Step 1: The smart contract sends a query to the oracle.

Step 2: The query is directed to the data carrier, which seeks the data from the data source

Step 3: Data is derived from the source and is fed to the oracle.

Step 4: Oracle sends the response to the smart contract as requested. 

Creating Oracle In Ethereum Smart Contract – Code Structure

We will find how oracle works in determining the current price of Bitcoin in USD using an oracle service called Provable. 

pragma solidity >= 0.5.0 < 0.6.0; //Declaring the Solidity version

import "github.com/provable-things/ethereum-api/provableAPI.sol";

//Importing latest version of provable API

contract BitcoinPrice is usingProvable {

//Contract named BitcoinPrice, UsingProvable refers to the API

    uint public bitcoinPriceUSD;

//bitcoinPriceUSD is the variable created to store the price, Provable query event that makes a constructor

    event LogNewBitcoinPrice(string price);
    event LogNewProvableQuery(string description);

    constructor()
        public
    {
        update(); 
    }

// callback function to call the smart contract after the output is received and transfers the result from callback function to the variable assigned

    function __callback(
        bytes32 _myid,
        string memory _result
    )
        public
    {
        require(msg.sender == provable_cbAddress());
        emit LogNewBitcoinPrice(_result);
        BitcoinPriceUSD = parseInt(_result, 2); // Let's save it as cents...

    }

//passing output string and API string to fetch bitcoin price to our constructor


    function update()
        public
        payable
    {
        emit LogNewProvableQuery("Provable query was sent, standing by for the answer...");
        provable_query("URL", "xml("https://min-api.cryptocompare.com/data/generateAvg?fsym=BTC&tsym=USD&e=Kraken"
);
    }
}

Oracle Problems

Oracle problems are fundamentally the conflict between trustless smart contracts and trusted third-party oracles, considering the security and authenticity of data from third parties.

Smart contracts rely on oracles for making decisions regarding their execution, giving them immense power over their functioning. As a matter of fact, the decentralised nature of smart contracts is brought to question. 

However, oracle services like ChainLink and Oraclize work as decentralised solutions that derive data based on novel and authenticated methods. Thus, the data obtained are through decentralised means.  

Conclusion

The connectivity of the blockchain with the real world is acceptably significant for a leap forward toward the decentralised world. Oracles are offering the solution for a reliable interface of smart contracts with real-time data. 

However, to bring forth sustainability, advancements are made by oracle services to instil the security and correctness of the data obtained off-chain. 

Want to stay more relevant to Web3 security?

Follow QuillAudits for many such up-to-date write-ups about Web3.

406 Views

Related Articles

View All

Leave a Comment

Your email address will not be published.

Trending

We need smart contracts audit to:

↗Identify bugs🐞
↗Enhance smart contract’s performance
↗Code optimisation
↗Contract’s performance validation
↗Provide credibility and instil trust among the people
..

The list is long, and it’s absolutely why we need #smartcontract audits.

ÐApps—

According to the reports by @DappRadar,

“The number of users engaging in decentralised applications is growing by 396% yearly, with now 2.4 million.”

Gaming DApps account for over 50% of the user activity in Q1 of 2022.

↓↓

#Web3 | #Ethereum

📌 Why do smart contracts in blockchain needs audit?

↓↓
🧵👇

The need for a smart contract audit can not be stressed enough.

The unbelievable traction of the #DeFi world has resulted in attracting the interest of people with malicious intentions.

#ETH | #cryptocurrency

Load More

Over 300 NFTs Stolen, One of 2022’s Biggest Breach🚨

The Twitter account of Korean NFT artist DeeKay Kwon was compromised and exploited in a phishing scam. As a result, his supporters lost NFT worth nearly $150,000.

Become a Quiffiliate!
Join our mission to safeguard web3

Sounds Interesting, Right? All you have to do is:

1

Refer QuillAudits to Web3 projects for audits.

2

Earn rewards as we conclude the audits.

3

Thereby help us Secure web3 ecosystem.

Total Rewards Shared Out: $150K+