# Solidity

## Connecting to the Oracle

To use Fetch Oracle data, you can use the [UsingFetch](https://github.com/fetchoracle/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.

{% hint style="success" %}
Check out this [sample project using Fetch Oracle](https://github.com/fetchoracle/sampleUsingFetch).
{% endhint %}

### Installation

To install `usingfetch`, run the following command:

```bash
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](https://docs.fetchoracle.com/the-basics/contract-addresses)) as a parameter:

```solidity
pragma solidity ^0.8.3;

import "usingfetch/contracts/UsingFetch.sol";

contract MyContract is UsingFetch {

  constructor(address payable _fetchAddress) UsingFetch(_fetchAddress) {

  }

  // ...

}
```

{% hint style="info" %}
**Note:** In the constructor, you need to specify the Fetch Oracle [contract address](https://docs.fetchoracle.com/the-basics/contract-addresses). For testing, you can use a Fetch Oracle Playground address.&#x20;

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

### Reading data

You can either use the [QueryID builder](https://go.fetchoracle.com/#/generate-query-id) to create a QueryID and hardcode it, or use Solidity to generate it.&#x20;

Once you have created a `QueryID`, you can add the Fetch Oracle data feed to your contract code.&#x20;

{% hint style="danger" %}
**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:&#x20;

`require(block.timestamp - _timestampRetrieved < 24 hours);`
{% endhint %}

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

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

import "usingfetch/contracts/UsingFetch.sol";

contract ExampleContract is UsingFetch {

    constructor(address payable _fetchAddress) UsingFetch(_fetchAddress) {}

    function getBtcSpotPrice() external view returns(uint256) {
    
      bytes memory _queryData = abi.encode("SpotPrice", abi.encode("btc", "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, "Data timestamp is more than 24 hours.");
      return abi.decode(_value, (uint256));
    }
}
```
