Skip to main content

Overview

BlockHash is a branded Uint8Array type representing a 32-byte block identifier in Ethereum. Every block has a unique hash computed from its header.
import * as BlockHash from '@tevm/primitives/BlockHash'

const hash = BlockHash.fromHex(
  '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890'
)

Type Definition

type BlockHashType = Uint8Array & {
  readonly [brand]: "BlockHash";
  readonly length: 32;
}

Creating BlockHashes

from

Universal constructor accepting hex string or bytes.
// From hex string
const hash1 = BlockHash.from(
  '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890'
)

// From bytes
const bytes = new Uint8Array(32)
const hash2 = BlockHash.from(bytes)

fromHex

Parse from hex string (with or without 0x prefix).
const hash = BlockHash.fromHex(
  'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890'
)
Validation: Must be 64 hex characters (32 bytes).

fromBytes

Create from Uint8Array.
const bytes = new Uint8Array(32)
const hash = BlockHash.fromBytes(bytes)
Validation: Must be exactly 32 bytes.

Converting BlockHashes

toHex

Convert to lowercase hex string with 0x prefix.
const hex = BlockHash.toHex(hash)
// '0xabcdef1234567890...'

Comparing BlockHashes

equals

Check equality using constant-time byte comparison.
const a = BlockHash.fromHex('0xabcd...')
const b = BlockHash.fromHex('0xabcd...')

if (BlockHash.equals(a, b)) {
  console.log('Hashes are equal')
}

Errors

InvalidBlockHashLengthError: Bytes length is not 32. InvalidBlockHashFormatError: Invalid hex format or unsupported type.

See Also