DEV Community


Posted on • Updated on

A simple web app to display ETH to USD price feed using DIA Oracle

What are oracles?

Oracles are data feeds that connect blockchains to off-chain, real-world information so that you can query data in your smart contracts. Your smart contracts will be able to execute based upon inputs and outputs from the real world. They typically provide a way for web3 ecosystems to access existing data sources and advanced computations. They are very useful for data analysts, data providers and data users.

DIA Oracle

One of such existing oracle is the DIA oracle. DIA provides a reliable and verifiable bridge between off-chain data from various sources and on-chain smart contracts that can be used to build a variety of financial dApps. There are quite a number of things you can do with DIA. You can develop applications and sources on top of DIA. In this article, I would be creating a simple app that displays ETH/USD price. Presently, DIA allows you do several other pairs such as BTC, DIA, USDC, FTM, SDN, KSM, MOVR which are all USD based.

Time to code
Let's get to code, shall we! I will be using javascript and html for this.

Create/Navigate to your project folder:

mkdir pricefeed
cd pricefeed
Enter fullscreen mode Exit fullscreen mode

Now create index.html and index.js files:

touch index.html
touch index.js
Enter fullscreen mode Exit fullscreen mode

I will be using one of DIA's deployed contracts. For this writeup, I would be using the smart contract address deployed on Binance mainnet.

Nagivate to the contract tab on bscscan

Contract's screenshot

Here is the contract's source code

pragma solidity 0.7.4;                                                                                                                                                                                                                      

contract DIACoinmarketcapOracle {                                                  
    mapping (string => uint256) public values;                                     
    address oracleUpdater;                                                         

    event OracleUpdate(string key, uint128 value, uint128 timestamp);              
    event UpdaterAddressChange(address newUpdater);                                

    constructor() {                                                                
        oracleUpdater = msg.sender;                                                

    function setValue(string memory key, uint128 value, uint128 timestamp) public {
        require(msg.sender == oracleUpdater);                                      
        uint256 cValue = (((uint256)(value)) << 128) + timestamp;                  
        values[key] = cValue;                                                      
        emit OracleUpdate(key, value, timestamp);                                  

    function getValue(string memory key) public view returns (uint128, uint128) {
        uint256 cValue = values[key];                                              
        uint128 timestamp = (uint128)(cValue % 2**128);                            
        uint128 value = (uint128)(cValue >> 128);                                  
        return (value, timestamp);                                                 

    function updateOracleUpdaterAddress(address newOracleUpdaterAddress) public {
        require(msg.sender == oracleUpdater);                                      
        oracleUpdater = newOracleUpdaterAddress;                                   
        emit UpdaterAddressChange(newOracleUpdaterAddress);                        
Enter fullscreen mode Exit fullscreen mode

Scroll down to also find the contract's ABI as we would be using it shortly.

Contract's ABI screenshot

Now looking at the contract, there is a getValue method, in order to get the response from the method, make a call to the method as shown below. Remember also that we are using the key ‘ETH’

Your code should look like this

const currentPriceResponse = await contract.methods.getValue('ETH').call()
Enter fullscreen mode Exit fullscreen mode

Copy the ABI as we would also be using it in our code. In the end, your js file would look something close to this

async function connect() {
    const priceElem = document.querySelector('#price')
    try {
        priceElem.textContent = 'Updating price...';

        const ABI = [ABI]

        const web3 = new Web3(new Web3.providers.HttpProvider(""))
        const contract = new web3.eth.Contract(ABI);
        contract.options.address = "0xbAFEe71d40baBC12a3D0B2b8937ee62D3A070835";
        const currentPriceResponse = await contract.methods.getValue('ETH').call()
        if (currentPriceResponse[0]) {
            const formatter = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                minimumFractionDigits: 2,
            priceElem.textContent = formatter.format(currentPriceResponse[0] / 100000);

    } catch (e) {
        priceElem.textContent = 'An error occurred while updating the price, please refresh your page.';

window.onload = function() {
Enter fullscreen mode Exit fullscreen mode

Let's give some edits to the index.html file. You can write something as simple as a div or a header.


    <span>Current Value: <i id="price"></i></span>
Enter fullscreen mode Exit fullscreen mode

Run your app and you would see that you are getting ETH/USD prices in real time. That’s pretty much it! A sample is deployed here. Feel free to check out the Source Code.
Thanks for reading! I hope you learnt a thing or two.

Off-chain: Off-chain transactions refer to those transactions occurring on a cryptocurrency network that move the value outside of the blockchain. Due to their zero/low cost, off-chain transactions are gaining popularity, especially among large participants. Read more

On-chain: On-chain transactions refer to cryptocurrency transactions that occur on the blockchain and remain dependent on the state of the blockchain for their validity. On-chain transactions are considered valid only when the blockchain has been updated to reflect the transactions on the public ledger. Read more

Smart contracts: A "smart contract" is simply a program that runs on a blockchain. It's a collection of code (its functions) and data (its state) that resides at a specific address on the blockchain. Read more

ABI : The Contract Application Binary Interface (ABI) is the standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain and for contract-to-contract interaction. Data is encoded according to its type, as described in this specification. The encoding is not self describing and thus requires a schema in order to decode. Read more

Top comments (1)

oluwaseyi profile image