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(); } }

Keenan Olsen
  • 359
  • 2
  • 7

3 Answers3

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); } }

Patrick Collins
  • 11,186
  • 5
  • 44
  • 97
  • 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 '22 at 06: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.

Jonah
  • 655
  • 1
  • 7
  • 17
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.

Markus Schick
  • 1,228
  • 3
  • 15