# Blocks

The building blocks for each blockchain. As such there are a number of examples for working with blocks and headers, that could be useful.

# How do I retrieve the header/extrinsic hash from blocks?

A block hash refers to the hash over the header, the extrinsic hash refers to the hash of the encoded extrinsic. Since all objects returned by the API implements the .hash => Hash getter, we can simply use this to view the actual hash.

// returns Hash
const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
// returns SignedBlock
const signedBlock = await this.api.rpc.chain.getBlock(blockHash);

// the hash for the block, always via header (Hash -> toHex()) - will be
// the same as blockHash above (also available on any header retrieved,
// subscription or once-off)
console.log(signedBlock.header.hash.toHex());

// the hash for each extrinsic in the block
signedBlock.block.extrinsics.forEach((ex, index) => {
  console.log(index, ex.hash.toHex());
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# How do I extract the block author?

The block author is encoded inside the consensus logs for the block. To extract, you need to decode the log (which the API does do) and then map the index of the validator to the list of session validators. This extraction is however available on the api derive for new head subscriptions, which returns an extended header with the author populated (assuming that the digest logs are known).

// subscribe to all new headers (with extended info)
api.derive.chain.subscribeNewHeads((header) => {
  console.log(`#${header.number}: ${header.author}`);
});
1
2
3
4

For a single header only, the derives also contain a getHeader, which once again returns a header extended with the author -

// retrieve the last header (hash optional)
const header = await api.derive.chain.getHeader();

console.log(`#${header.number}: ${header.author}`);
1
2
3
4

# How do I view block extrinsic information?

The transactions are included in a signed block as part of the extrinsics - some of these will be unsigned and generated by the block author and some of these may be submitted from external sources and be signed. (Some palettes do use unsigned transactions, so signed/unsigned is not an indication of origin). To retrieve the block and display the transaction information, we can do the following -

// no blockHash is specified, so we retrieve the latest
const signedBlock = await this.api.rpc.chain.getBlock();

// the information for each of the contained extrinsics
signedBlock.block.extrinsics.forEach((ex, index) => {
  // the extrinsics are decoded by the API
  console.log(index, ex.toHuman());
});
1
2
3
4
5
6
7
8

In the above .toHuman() is used to format into a human-readable representation. You can inspect/extract specific fields from the decoded extrinsic as required, for instance ex.method.section would return the pallete that executed this transaction.