Search code examples
blockchainsmartcontractsbinance-smart-chainethers.js

Ethers.js token price chart


I'm using Ethers.js to get the token price from BSC using getReserves successfully.

  const nodeRandom = !node ? wssNodes() : node;
  const provider = new ethers.providers.WebSocketProvider(nodeRandom);
  const pairAddress = await pancake.getPair(token0, token1);

  if (pairAddress === "0x0000000000000000000000000000000000000000") {
    return {
      status: "Pair not found",
    };
  }

  const pairContract = new ethers.Contract(pairAddress, pancakePair, provider);
  const reserves = await pairContract.getReserves();

I want to create a price chart for that token, but I get into trouble when I don't know how to get the historical price data from BSC.

Does Ethers.js support getting the token price history, or should we store the price we get into our database? If then, is there any way we can build the price chart of a token from the very beginning of the first block when we don't have that in our DB?

Any idea?


Solution

  • You can use the blockTag field of the overrides object - docs. It queries the node to return the value from a specific block instead of the current.

    const reserves = await pairContract.getReserves({
        blockTag: <blockNumer>
    });
    

    Note that it depends on the node provider if they support these historical queries or not. Most providers support it only in higher tier plans or not at all.