How I can get the previous block time using timestamp pallet
To start off, when using polkadot.js the current time can be retrieved via:
Under the hood, this uses the
state collection of RPC methods (
These methods take two parameters, a
storage key and a
storage key is the encoded format of the key for the storage you want to query.
The block hash is optional, and if omitted the query will default to the current block.
So first we need to fetch the
blockhash of the block you want to query, i.e.
the previous block:
// get the latest block number const blockNumber = await api.query.system.number() // determine the previous block number const previousBlockNumber = blockNumber.subn(1) // fetch the previous block hash const previousBlockHash = await api.query.system.blockHash(previousBlockNumber)
Then we need to pass this
blockhash to the