LogoLogo
WebsiteDiscordTelegramTwitter
  • 🏠Witnet Oracle Docs
  • Introduction
    • ❓What is Witnet?
      • ⚙️Oracle Architecture
      • 🪙The Witnet Coin (Wit)
      • 👛Wallets
      • 🤔Frequently Asked Questions
      • 😎Awesome Witnet
    • 🚀Quick Tutorials
      • 📈Price Feeds
      • 🎲Randomness
      • 🌐APIs and HTTP GET/POST
      • ⛏️Mining Wit
  • Smart contracts developers
    • ⛓️Supported chains
    • 🔮Wit/Oracle
      • HTTP GET Requests in Solidity
      • HTTP POST Requests in Solidity
      • Query GraphQL APIs in Solidity
      • Dynamic Requests in Solidity
      • UsingWitnet Inheritance
      • API Reference
        • Solidity API
          • Solidity Contracts
            • WitnetRequestBoard
        • Javascript API
        • RADON API
          • RADON Type System
          • RADON Errors
      • Multi-chain Addresses
    • 💹Wit/Price Feeds
      • How To Use Witnet Price Feeds
      • Update Conditions
      • Code Examples
      • API Reference
      • Multi-chain Addresses
        • Arbitrum Price Feeds
        • Avalanche Price Feeds
        • Base Price Feeds
        • Boba Price Feeds
        • Celo Price Feeds
        • Conflux Price Feeds
        • Cronos Price Feeds
        • Dogechain Price Feeds
        • Elastos Price Feeds
        • Ethereum Price Feeds
        • Gnosis Chain Price Feeds
        • Kaia Price Feeds
        • Kava Price Feeds
        • KCC Price Feeds
        • Mantle Price Feeds
        • Meter Price Feeds
        • Metis Price Feeds
        • Moonbeam Price Feeds
        • OKX Price Feeds
        • Optimism Price Feeds
        • Polygon Price Feeds
        • Reef Price Feeds
        • Scroll Price Feeds
        • Syscoin Price Feeds
        • Ultron Price Feeds
        • Request new price feed or chain support
    • 🎲Wit/Randomness
      • Generating Randomness
      • WitnetRandomness Contract
      • Low-level Requests
      • Code Examples
      • API Reference
      • Multi-chain Addresses
    • 🏗️Guides
      • 📖Solidity Contracts
        • Appliances
          • 📃WitnetPriceFeeds
          • 📃WitnetRandomness
        • Core
          • 📃WitnetOracle
          • 📃WitnetRadonRegistry
          • 📃WitnetRequest
          • 📃WitnetRequestFactory
          • 📃WitnetRequestTemplate
        • Mockups
          • 📃UsingWitnet
          • 📃UsingWitnetRandomness
          • 📃UsingWitnetRequest
          • 📃UsingWitnetRequestTemplate
          • 📃WitnetRandomnessRequestConsumer
          • 📃WitnetRequestConsumer
          • 📃WitnetRequestTemplateConsumer
      • 🧙Solidity Wizard
    • 🎓Tutorials
      • Building a Satoshi/Wei custom price feed
  • Witnet SDK
    • 👋Introduction
    • 🚀Getting Started
    • 🏗️How-to Guides
      • Connect to a Wit/RPC provider
      • Query stake entries in Witnet
      • Manage Witnet wallets
      • Manage Witnet UTXOs
      • Manage Witnet transactions
    • 🎓Tutorials
    • 📚Reference Material
      • 🔌APIs
        • Wit/Node JSON-RPC API
  • Witnet Validators
    • 💻Node Requirements
    • 🚀Getting Started (Docker)
    • 🔎Next steps
    • 🤓Advanced Setups
      • Run node as a systemd service
      • Run node with docker compose
      • Paranoid mode (Witnet over proxies and Tor)
      • Configuration file
    • ⌨️CLI Reference
  • 🗜️Compile from Source Code
Powered by GitBook
On this page
  • Reading multiple price pairs from the router
  • Solidity example
  • Javascript example
  • Reading last price and timestamp from a Price Feed contract serving a specific pair
  • Solidity example
  • Forcing an update on a Witnet-powered currency pair
  • Solidity example

Was this helpful?

Edit on GitHub
  1. Smart contracts developers
  2. Wit/Price Feeds

Code Examples

PreviousUpdate ConditionsNextAPI Reference

Last updated 5 months ago

Was this helpful?

Reading multiple price pairs from the router

The Price Router contract is the easiest and most convenient way to consume Witnet price feeds on any of the .

Solidity example

To read price values from the Price Router contract, you need first to identify the WitnetPriceRouter address specific to the chain in which you plan to deploy your contracts:

The example below shows how to read the price of two different assets from the Witnet Price Router:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;

import "witnet-solidity-bridge/contracts/interfaces/IWitnetPriceRouter.sol";

contract MyContract {
    IWitnetPriceRouter immutable public router;
    
    /**
     * IMPORTANT: pass the WitnetPriceRouter address depending on 
     * the network you are using! Please find available addresses here:
     * https://docs.witnet.io/smart-contracts/price-feeds/contract-addresses
     */
    constructor(IWitnetPriceRouter _router) {
        router = _router;
    }
    
    /// Returns the BTC / USD price (6 decimals), ultimately provided by the Witnet oracle.
    function getBtcUsdPrice() public view returns (int256 _price) {
        (_price,,) = router.valueFor(bytes4(0x24beead4));
    }
    
    /// Returns the ETH / USD price (6 decimals), ultimately provided by the Witnet oracle.
    function getEthUsdPrice() public view returns (int256 _price) {
        (_price,,) = router.valueFor(bytes4(0x3d15f701));
    }
    
    /// Returns the BTC / ETH price (6 decimals), derived from the ETH/USD and 
    /// the BTC/USD pairs that were ultimately provided by the Witnet oracle.
    function getBtcEthPrice() public view returns (int256 _price) {
        return (1000000 * getBtcUsdPrice()) / getEthUsdPrice();
    }
}

As Solidity does not support float types, all prices are provided as int256 values, with a fixed number of decimals digits.

For instance, if the BTC/USD price is $41,847.762289, the Price Router contract will give 41847762289 for the currency pair identified as "Price-BTC/USD-6".

Javascript example

You may also read the latest price of any of the supported currency pairs from your Web3 application by interacting directly with the Price Router contract:

web3 = Web3(Web3.HTTPProvider('https://mainnet.boba.network'))
abi = '[{ "inputs": [{ "internalType": "bytes32", "name": "_id", "type": "bytes32" }], "name": "valueFor", "outputs": [{ "internalType": "int256", "name": "", "type": "int256" }, { "internalType": "uint256", "name": "", "type": "uint256" }, { "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }]'
addr = '0x36928Aeedaaf7D85bcA39aDfB2A39ec529ce221a'
contract = web3.eth.contract(address=addr, abi=abi)
// get last value for "Price-BOBA/USDT-6"
valueFor = contract.functions.valueFor().call("0xf723bde1")
print("Price-BOBA/USDT-6:", valueFor[0])
print("> lastTimestamp:", valueFor[1])
print("> latestUpdateStatus:", valueFor[2])

The WitnetPriceRouter contract offers a series of methods that can be used to list the currency pairs that are currently maintained by the Witnet Foundation, as well as their human-readable captions, and the Price Feed contracts currently serving updates for each one of them:

Reading last price and timestamp from a Price Feed contract serving a specific pair

Solidity example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;

import "witnet-solidity-bridge/contracts/interfaces/IWitnetPriceRouter.sol";
import "witnet-solidity-bridge/contracts/interfaces/IWitnetPriceFeed.sol";

contract MyContract {

    IWitnetPriceRouter immutable public witnetPriceRouter;
    IWitnetPriceFeed public celoEurPrice;
    
    /**
     * IMPORTANT: pass the WitnetPriceRouter address depending on 
     * the network you are using! Please find available addresses here:
     * https://docs.witnet.io/smart-contracts/price-feeds/contract-addresses
     */
    constructor(IWitnetPriceRouter _router)
        witnetPriceRouter = _router;
        updateCeloEurPriceFeed();
    }
    
    /// Detects if the WitnetPriceRouter is now pointing to a different IWitnetPriceFeed implementation:
    function updateCeloEurPriceFeed() public {
        IERC165 _newPriceFeed = witnetPriceRouter.getPriceFeed(bytes4(0x21a79821));
        if (address(_newPriceFeed) != address(0)) {
            celoEurPrice = IWitnetPriceFeed(address(_newPriceFeed));
        }
    }
    
    /// Returns the CELO / EUR price (6 decimals), ultimately provided by the Witnet oracle, and
    /// the timestamps at which the price was reported back from the Witnet oracle's sidechain 
    /// to Celo Alfajores.
    function getCeloEurPrice() external view returns (int256 _lastPrice, uint256 _lastTimestamp) {
        (_lastPrice, _lastTimestamp,,) = celoEurPrice.lastValue();
    }
    
    // ...
}

When interacting with a IWitnetPriceFeed contract, you can get not only the last valid price value (and timestamp) solved by the Witnet oracle, but also the hash of the transaction within the Witnet's sidechain that triggered that last valid update request. This Witnet transaction hash can be used as a means to verify and track the whole resolution process that took in place within the Witnet oracle's sidechain.

Moreover, you can also detect whether there is a recent price update pending to be solved, or if the latest update attempt could not get solved for whatever reason.

Forcing an update on a Witnet-powered currency pair

Solidity example

First, get from the WitnetPriceRouter contract the IWitnetPriceFeed address that is currently serving price updates on any given currency pair.

Then, just call the requestUpdate() payable method.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;

import "witnet-solidity-bridge/contracts/interfaces/IWitnetPriceRouter.sol";
import "witnet-solidity-bridge/contracts/interfaces/IWitnetPriceFeed.sol";

contract MyContract {
    IWitnetPriceRouter immutable public router;
    
    /**
     * IMPORTANT: pass the WitnetPriceRouter address depending on 
     * the network you are using! Please find available addresses here:
     * https://docs.witnet.io/smart-contracts/price-feeds/contract-addresses
     */
    constructor(IWitnetPriceRouter _router)
        router = _router;
    }
    
    receive () external payable {}
    
    /// Force udpate on the CFX / USDT currency pair
    function forceCfxUsdtUpdate() external payable {
        IWitnetPriceFeed _priceFeed = router.getPriceFeed(bytes4(0x65784185));
        uint _updateFee = _priceFeed.estimateFee(tx.gasprice);
        _priceFeed.requestUpdate{value: _updateFee}();
        if (msg.value > _updateFee) {
            payable(msg.sender).transfer(msg.value - _updateFee);
        }
    }
    
    // ...
}
💹
supported chains
Multi-chain Addresses
API Reference
API Reference