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

4

1 回答 1

1

存储项pastDifficultiesAndTimestamps仅保存最后 60 个块的数据。要获取该信息,您只需要修复以下内容:

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

如果你想查询一个块的一般难度,这样的循环会起作用:

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

请注意,这需要一个存档节点,其中包含有关所有块的信息。否则,默认情况下,在状态修剪清理之前,节点仅存储约 256 个先前的块。

如果您想了解如何进行这样的查询,但效率更高,请在此处查看我的博客文章:

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

于 2020-09-04T00:02:03.340 回答