How do I get difficulty over time from Kulupu (polkadotjs)?

105 views Asked by At
// Import
import { ApiPromise, WsProvider } from "@polkadot/api";

// Construct
/*
https://rpc.kulupu.network
https://rpc.kulupu.network/ws
https://rpc.kulupu.corepaper.org
https://rpc.kulupu.corepaper.org/ws
*/

(async () => {
  //const wsProvider = new WsProvider('wss://rpc.polkadot.io');
  const wsProvider = new WsProvider("wss://rpc.kulupu.network/ws");
  const api = await ApiPromise.create({ provider: wsProvider });

  // Do something
  const chain = await api.rpc.system.chain();

  console.log(`You are connected to ${chain} !`);
  console.log(await api.query.difficulty.pastDifficultiesAndTimestamps.toJSON());

  console.log(api.genesisHash.toHex());
})();

1

There are 1 answers

0
Shawn Tabrizi On BEST ANSWER

The storage item pastDifficultiesAndTimestamps only holds the last 60 blocks worth of data. For getting that information you just need to fix the following:

console.log(await api.query.difficulty.pastDifficultiesAndTimestamps());

If you want to query the difficulty of a blocks in general, a loop like this will work:

let best_block = await api.derive.chain.bestNumber()

// Could be 0, but that is a lot of queries...
let first_block = best_block - 100;

for (let block = first_block; block < best_block; block++) {
  let block_hash = await api.rpc.chain.getBlockHash(block);
  let difficulty = await api.query.difficulty.currentDifficulty.at(block_hash);
  console.log(block, difficulty)
}

Note that this requires an archive node which has informaiton about all the blocks. Otherwise, by default, a node only stores ~256 previous blocks before state pruning cleans things up.

If you want to see how to make a query like this, but much more efficiently, look at my blog post here:

https://www.shawntabrizi.com/substrate/porting-web3-js-to-polkadot-js/