6

How I can get the previous block time using timestamp pallet

1 Answer 1

2

To start off, when using polkadot.js the current time can be retrieved via:

api.query.timestamp.now()

Under the hood, this uses the state collection of RPC methods (state_getStorage, state_subscribeStorage, etc).

These methods take two parameters, a storage key and a blockhash.

The 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 timestamp.now query:

api.query.timestamp.now.at(previousBlockHash)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.