Solidity

Learn how to set up solidity integration with Fetch Oracle.

Connecting to the Oracle

To use Fetch Oracle data, you can use the UsingFetch helper contract. After connecting it to the oracle, you can read a value using your QueryId. This guide uses the PLS/USD SpotPrice as an example query.

Installation

To install usingfetch, run the following command:

npm install usingfetch

Importing

To import the UsingFetch contract into your Solidity file, pass the desired Fetch Oracle address (which can be found on the references page) as a parameter:

pragma solidity >=0.8.0;

import "usingfetch/contracts/UsingFetch.sol";

contract MyContract is UsingFetch {

  constructor(address payable _fetchAddress) UsingFetch(_fetchAddress) {

  }

  // ...

}

Note: In the constructor, you need to specify the Fetch Oracle contract address. For testing, you can use a Fetch Oracle Playground address.

When working with live data, make sure to use the Fetch Oracle address on the PulseChain network.

Reading data

You can either use the QueryID builder to create a QueryID and hardcode it, or use Solidity to generate it.

Once you have created a QueryID, you can add the Fetch Oracle data feed to your contract code.

The best practice for reading Fetch Oracle data is to use the getDataBefore function with a buffer time that allows time for bad values to be disputed:

getDataBefore(_queryId, block.timestamp - 20 minutes);

It's also best practice to require/check that the data is not too old. For example:

require(block.timestamp - _timestampRetrieved < 24 hours);

In the example below, we add a function getPlsSpotPrice that reads the PLS/USD price feed from the oracle:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;

import "usingfetch/contracts/UsingFetch.sol";

contract ExampleContract is UsingFetch {

    ...

    function getPlsSpotPrice() external view returns(uint256) {
    
      bytes memory _queryData = abi.encode("SpotPrice", abi.encode("pls", "usd"));
      bytes32 _queryId = keccak256(_queryData);
      
      (bytes memory _value, uint256 _timestampRetrieved) =
          getDataBefore(_queryId, block.timestamp - 20 minutes);
      if (_timestampRetrieved == 0) return 0;
      require(block.timestamp - _timestampRetrieved < 24 hours);
      return abi.decode(_value, (uint256);
    }

Last updated