Code Examples

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

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:

Multi-chain Addresses

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:

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:

API Reference

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

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.

API Reference

Last updated

Was this helpful?