5

I wanted to pull the historical data stored by the reference data contracts by chainlink oracles. Since all the data is on-chain, I should be able to view it all? But currently, my contract can only see the latest answer. Any thoughts?

pragma solidity ^0.6.0;

import "@chainlink/contracts/src/v0.6/dev/AggregatorInterface.sol";

contract ReferenceConsumer {
  AggregatorInterface internal ref;

  constructor(address _aggregator) public {
    ref = AggregatorInterface(_aggregator);
  }

  function getLatestAnswer() public returns (int256) {
    return ref.latestAnswer();
  }
}

3 Answers 3

5

You can view the entire history of reference contracts, you'll want to use the getPreviousAnswer method below, and input how many answers back you'd like to go.

pragma solidity ^0.6.0;

import "@chainlink/contracts/src/v0.6/dev/AggregatorInterface.sol";

contract ReferenceConsumer {
  AggregatorInterface internal ref;

  constructor(address _aggregator) public {
    ref = AggregatorInterface(_aggregator);
  }

  function getLatestAnswer() public returns (int256) {
    return ref.latestAnswer();
  }

  function getLatestTimestamp() public returns (uint256) {
    return ref.latestTimestamp();
  }

  function getPreviousAnswer(uint256 _back) public returns (int256) {
    uint256 latest = ref.latestRound();
    require(_back <= latest, "Not enough history");
    return ref.getAnswer(latest - _back);
  }

  function getPreviousTimestamp(uint256 _back) public returns (uint256) {
    uint256 latest = ref.latestRound();
    require(_back <= latest, "Not enough history");
    return ref.getTimestamp(latest - _back);
  }
}
1
  • this will only work for the current aggregator phase and wont let you go all the way back to the first round
    – Jonah
    Feb 15, 2022 at 6:55
0

I've written a library that lets you get the prev() or next() roundId from a given roundId:

https://github.com/JonahGroendal/chainlink-round-id-calc/blob/master/contracts/ChainlinkRoundIdCalc.sol

You can use prev() to go back all the way to the very first round if you want.

0

Update September 2022

You can now easily view historical price data by using checkthechain.

Below is a minimal working example using the Python package:

from ctc.protocols import chainlink_utils

feed = '0x31e0a88fecb6ec0a411dbe0e9e76391498296ee9'

data = await chainlink_utils.async_get_feed_data(feed)

Alternatively, you can also use their API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.