January 09, 2021

How to create your own Oracle with an Ethereum smart contract


Ethereum smart contracts are the most valuable features of the Ethereum blockchain network; The development of applications driven by smart contracts on the Ethereum blockchain has skyrocketed recently. These smart-contracts are sandboxed and can’t access the data available outside of the Ethereum blockchain. Ethereum smart contracts can’t make HTTP calls or access the hardware layers; they are merely code that gets executed only once a transaction is sent. To provide data access to smart contracts and essentially connect them to the outside world, beyond the Ethereum blockchain network -  an Oracle is required. In this article, we will understand/learn how to set up our own Oracle inside a smart contract.

What is an Oracle in Ethereum?

The Ethereum blockchain network is a cluster of nodes that execute smart contracts. To obtain the same consistent outcome, all nodes must have access to the same set of inputs, and this is called determinism. To validate the smart contract's output, Ethereum relies on this determinism property, meaning that the validating nodes must all produce the identical output while running the code. 

Maintaining this property is a rather tricky task. Since Ethereum is a general-purpose platform, the smart-contracts that it runs require data from different external sources like the internet. The usefulness of smart-contracts can be significantly restricted without access to these external data sources. On the other hand, if nodes are allowed to collect information from these external sources, even a tiny time difference may result in data discrepancy with different nodes obtaining different inputs, thus producing different outputs and violating the determinism property, which will result in a contract failure.

To avoid such issues, smart-contracts are restricted from interacting with external data sources or call any internet URL, and this is where the Oracles come to the rescue. An Oracle is a way for smart-contracts to access real-world data. Oracles grab this real-world data and push it onto the blockchain for other smart contracts to properly access it. Oracles themselves are a type of a smart contract.

Here are some examples of off-chain data storage:

Trimmed blocks: Ethereum nodes may contain a large set of data, but for optimization purposes, a node can be created with just a portion of the distributed ledger. Such nodes are known as trimmed/pruned nodes and are saved in a centralized location.

State variables: The data stored on the Ethereum blockchain cannot be changed; it is immutable. However, the contents of state variables may fluctuate with changes in account balances. The solution is to store such data off the chain.

Oracles: Discussed in this article.

Digital assets: Digitized assets often require huge data sets to define them. Given the limited size of blocks, it is not feasible to store them on the chain.

There are two main types of Oracles:

Hardware Oracles: This is when data is coming from hardware devices like barcode scanners. This type of information is useful for things like registering event occurrences.

Software Oracles: This refers to the information readily available online, such as weather forecasts, fuel rates, exchange rates, stock prices, etc. Software Oracles provide smart contracts with a wide range of up-to-date data.

Creating our Oracle

For our demonstration of working with Oracles, we will use an Oracle service called Provable. Provable is the leading Oracle service for smart contracts and blockchain applications, serving thousands of requests every day on platforms like Ethereum, Rootstock, R3 Corda, Hyperledger Fabric and EOS

For this demo, we will make a smart-contract which will obtain the current diesel fuel price in the USA.

To get started, we’ll need some test Ether. We will use Kovan which you can obtain from pasting your wallet address into the Kovan faucet gitter. A chatbot will provide you with test Ethereum currency. Make sure to install the Metamask browser extension and to create an ETH wallet.

Head over to the Ethereum Remix IDE and make a new Solidity file, for example - dieselprice.sol

Paste the following code into your new Solidity script:

pragma solidity >= 0.5.0 < 0.6.0;

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

contract DieselPrice is usingProvable {

    uint public dieselPriceUSD;

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

        update(); // First check at contract creation...

    function __callback(
        bytes32 _myid,
        string memory _result
        require(msg.sender == provable_cbAddress());
        emit LogNewDieselPrice(_result);
        dieselPriceUSD = parseInt(_result, 2); // Let's save it as cents...
        // Now do something with the USD Diesel price...

    function update()
        emit LogNewProvableQuery("Provable query was sent, standing by for the answer...");
        provable_query("URL", "xml(https://www.fueleconomy.gov/ws/rest/fuelprices).fuelPrices.diesel");

Explanation of the code above: 

Line 1: Declaring the solidity version

Line 3: Importing the latest version of the Provable API, 

Line 5: Starting our contract named DieselPrice, usingProvable refers to the API 

Lines 7-16: Creating a variable dieselPriceUSD which will store the price, instantiating our event for the price and Provable query event, making a constructor

Lines: 18-28: making a callback function which calls the smart-contract after the output is received, giving the result from callback function to our variable and converting the price from dollars to cents

Lines 30-37: Passing an output string and an API string to fetch diesel price to our constructor function, the API fetches info in XML format, fuelPrices.diesel fetches the specific tag

Compile the smart-contract and deploy it using injected Web3 (make sure to select Kovan testnet on Metamask before compiling the contract). Ignore the warning about unused variables in the code. Approve the transaction from metamask. 

Now you will see your contract under the “Deployed Contracts” section in Remix. Open the deployed contract and click on dieselPriceUSD - it will display the output under the button, similar to what’s on the image below. Sometimes you may need to wait a minute before real data is displayed. So if you’re seeing a 0 value, wait and try again.


You can refer to Provable’s official documentation for more examples and use cases.

Subscribe to our newsletter for more articles and guides on Ethereum. If you have any feedback, feel free to reach out to us via Twitter. You can always chat with us on our Discord community server, featuring some of the coolest developers you’ll ever meet :)
Ready to try QuikNode? Start your 7-day free trial

Related articles 6

Feb 25, 2021 How to create and deploy an ERC20 token

Ethereum network’s launch in 2015 created a lot of buzz in the developer community and sprouted a lot of tokens on the network. Initially there weren’t any templates or guidelines for token development. This resulted in a variety of tokens quite different from each other....

Continue reading
Mar 20, 2021 How to build an Ethereum URL shortener dApp

dApps (decentralized applications) are an integral part of the Ethereum development ecosystem. There are thousands of dApps already residing on the Ethereum blockchain. In this guide, we will learn how to build an Ethereum dApp that...

Continue reading
Mar 20, 2021 How to create and deploy an ERC-721 (NFT)

Crypto collectibles compatible with the ERC-721 standard have become very popular since the launch of Cryptokitties and have moved forward towards mass adoption in recent months. This guide will cover creating and deploying our...

Continue reading
Mar 20, 2021 How to write an Ethereum smart contract using Solidity

This article is intended for developers new to Ethereum development. In this article, we will talk about Solidity and smart contracts, What they are and what role they actually play in the ethereum development with the end goal of writing a smart contract using...

Continue reading
Mar 20, 2021 How to call another smart contract from your solidity code

Smart contracts are the most popular feature of the Ethereum network. Smart contracts have functions that sometimes need to be accessed by other smart contracts. Before understanding smart contracts' interactions, let's brush up on our basics about smart...

Continue reading
Mar 31, 2021 What is an ABI?

While interacting with a smart contract ABI is one of the essential components. In this guide, let us understand what the ABI of smart contracts is.

Continue reading