How To Build Your Own Oracle Using Ethereum Smart Contracts?

How To Build Your Own Oracle Using Ethereum Smart Contracts?

How To Build Your Own Oracle Using Ethereum Smart Contracts?

How To Build Your Own Oracle Using Ethereum Smart Contracts?

How To Build Your Own Oracle Using Ethereum Smart Contracts?

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.

5,075 Views

Blockchain for dog nose wrinkles' Ponzi makes off ~$127M🐶

Project promised up to 150% returns on investment in 100 days, raising about 166.4 billion South Korean won — or about $127 million — from 22,000 people.

Latest blogs for this week

Understanding Fuzzing and Fuzz Testing: A Vital Tool in Web3 Security

Read Time: 5 minutes When it comes to smart contracts, ensuring the robustness and security of code is paramount. Many techniques are employed to safeguard these contracts against vulnerabilities
Read More

How EigenLayer’s Restaking Enhances Security and Rewards in DeFi

Read Time: 7 minutes Decentralized finance (DeFi) relies on Ethereum staking to secure the blockchain and maintain consensus. Restaking allows liquid staking tokens to be staked with validators in
Read More

ERC 404 Standard: Everything You Need to Know

Read Time: 7 minutes Introduction Ethereum has significantly shaped the crypto world with its introduction of smart contracts and decentralized applications (DApps). This has led to innovative developments in
Read More

DNS Attacks:  Cascading Effects and Mitigation Strategies

Read Time: 8 minutes Introduction DNS security is vital for a safe online space. DNS translates domain names to IP addresses, crucial for internet functionality. DNS ensures unique name-value
Read More

EIP-4844 Explained: The Key to Ethereum’s Scalability with Protodanksharding

Read Time: 7 minutes Introduction  Ethereum, the driving force behind dApps, has struggled with scalability. High fees and slow processing have limited its potential. They have kept it from
Read More

QuillAudits Powers Supermoon at ETH Denver!

Read Time: 4 minutes Calling all the brightest minds and leaders in the crypto world! Are you ready to build, connect, and innovate at the hottest event during ETH
Read More

Decoding the Role of Artificial Intelligence in Metaverse and Web3

Read Time: 7 minutes Introduction  Experts predict a transformative shift in global software, driven by AI and ML, marking the dawn of a new era. PwC predicts AI will
Read More

Transforming Assets: Unlocking Real-World Asset Tokenization

Read Time: 7 minutes In the blockchain, real-world assets (RWAs) are digital tokens that stand for tangible and conventional financial assets, including money, raw materials, stocks, and bonds. As
Read More
Scroll to Top

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: $200K+