Skip to main content

Fetching Block Data

The getBlock and getBlocks methods allow you to retrieve detailed information about a single block or multiple blocks on the OP_NET network. You can fetch blocks by their height or hash.


Available Methods

1. Fetching a Single Block

getBlock(blockNumberOrHash: BlockTag, prefetchTxs?: boolean): Promise<Block>;
  • Parameters:

    • blockNumberOrHash: BlockTag: The block number or hash to fetch.
    • prefetchTxs?: boolean: Optional. If true, fetches the transactions within the block.
  • Returns:

    • Promise<Block>: A Block object containing detailed information.

2. Fetching Multiple Blocks

getBlocks(blockNumbers: BlockTag[], prefetchTxs?: boolean): Promise<Block[]>;
  • Parameters:

    • blockNumbers: BlockTag[]: An array of block numbers or hashes.
    • prefetchTxs?: boolean: Optional. If true, fetches the transactions for each block.
  • Returns:

    • Promise<Block[]>: An array of Block objects.

Object Definitions

Block Object
PropertyTypeDescription
heightBigNumberishThe block height.
hashstringThe block's hash.
previousBlockHashstringHash of the previous block.
timenumberThe block's timestamp.
transactionsTransactionBase<OPNetTransactionTypes>[]An array of transactions within the block.
gasUsedbigintTotal gas used in the block.
emabigintExponentially weighted moving average of gas usage.
baseGasbigintBase gas cost for transactions in the block.

Example Usage

Fetching a Single Block

const block = await provider.getBlock(100);
console.log("Block details:", block);

Fetching Multiple Blocks

const blocks = await provider.getBlocks([100, 101, 102]);
console.log("Fetched blocks:", blocks);

Best Practices

  • Use prefetchTxs to fetch transactions within the blocks. Set to false to save bandwidth if transaction data is unnecessary.
  • Use getBlocks for better performance when retrieving multiple blocks.

What’s Next?