Marketplace has launched, further enabling blockchain developers! Learn more

How to create your own Oracle with an Ethereum smart contract

September 23, 2022

Overview

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);

    constructor()
        public
    {
        update(); // First check at contract creation...
    }

    function __callback(
        bytes32 _myid,
        string memory _result
    )
        public
    {
        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()
        public
        payable
    {
        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.
 


Conclusion

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 :)

Related articles 26

Solidity vs Vyper
Published: Aug 18, 2021
Updated: Sep 23, 2022

With the introduction to smart contracts on the Ethereum blockchain, it was only a matter of time until a language other than Solidity was made to write smart contract code. Vyper is one such...

Continue reading
How to Create a BEP20 Token
Published: Jul 3, 2021
Updated: Sep 23, 2022

BEP20 is the Binance Smart Chain equivalent to the popular ERC20 specification for tokens on the Ethereum network. The difference is the BEP20 Token isn't run on the Ethereum Network, but the...

Continue reading
What is an ABI?
Published: Mar 20, 2021
Updated: Sep 23, 2022

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
How to create and deploy an ERC20 token
Published: Feb 3, 2021
Updated: Sep 23, 2022

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...

Continue reading
How to Create and Deploy an ERC-1155 NFT
Published: Mar 14, 2022
Updated: Sep 23, 2022

ERC1155 has emerged as a gold standard to create NFTs; every major marketplace lists new tokens as an ERC1155 standard. In this guide, we will learn about the ERC1155 token standard and how to...

Continue reading
Como crear un Token BEP20
Published: Jan 10, 2022
Updated: Sep 23, 2022

BEP20 es en Binance Smart Chain el equivalente al popular token ERC20 de la red de Ethereum. La diferencia es que el token BEP20 no corre en la red de Ethereum sino en la red de Binance Smart...

Continue reading