How To Build Your Own Oracle Using Ethereum Smart Contracts?
- QuillAudits Team
- July 1, 2022
Table of Contents
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.
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.
Related Articles
Bitcoin Stock-To-Flow (S2F) Model Explained
Read Time: 4 minutes Bitcoin is perceived to be the synonym for cryptocurrency, although
The NFT Ecosystem And Related Security Risks
Read Time: 6 minutes 2021 has been an interesting year for NFTs. The most
Understanding The Stablecoin in Context to Recent Fluctuations
Read Time: 5 minutes The sudden fall in the Terra Luna token price from
What is EIP-1559? How Did It Change Ethereum?
Read Time: 5 minutes The EIP-1559 implementation date was a hot topic in the
Trending
Bitcoin Stock-To-Flow (S2F) Model Explained
The NFT Ecosystem And Related Security Risks
A lot of founders think third-party audits are a waste of time and money.
They’re wrong!
They help you
– Reduce time-to-market
– Focus on launch prep
– Product development
– Build community trust
#smartcontractaudit
Who are the best people to follow in the web3 security space?
#Web3 | #crypto | #ETH | #security | #community
New Partnership Announcement with @QuillAudits
QuillAudits – Smart Contracts Auditing Services, DeFi Safety Audits, Cybersecurity Solutions For Blockchain & Crypto Products.
@QuillAudits X @TheCryptoLaunch
#Launchpad #cryptocurrecy #launchwithtcl #thecryptolaunchpad https://twitter.com/QuillAudits/status/1542414987473596417
The Crypto Launchpad 🤝 QuillAudits
@TheCryptoLaunch is a one-stop solution for all new crypto projects. It assists its clients from developing a token to its listing and marketing.
The Crypto Launchpad recognizes QuillAudits as its Audit partner.
Hi there! 👋Thanks for stopping by.
Here’s our monthly synopsis of #HashingBits- a leading Web3 security #newsletter.
If you are a key actor in the emerging #Web3 ecosystem and would like to join the community, Click the link below to subscribe.
📧https://quillaudits.substack.com/
The Crypto Launchpad 🤝 QuillAudits
@TheCryptoLaunch is a one-stop solution for all new crypto projects. It assists its clients from developing a token to its listing and marketing.
The Crypto Launchpad recognizes QuillAudits as its Audit partner.
Inverse Finance hacked again for $1.2M⚠️In ‘Optimism’ Tokens 🚨
Inverse Finance’s Frontier money market was subject to an oracle price manipulation incident.It resulted in a net loss of $5.83 million in $DOLA, with the attacker earning a total of $1.2 million.