or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

block-operations.mdconsensus-operations.mdheader-operations.mdindex.mdutility-functions.md
tile.json

utility-functions.mddocs/

Utility Functions

Helper functions for trie root calculations, data conversions, and blockchain-specific operations.

Capabilities

Trie Root Generation

Functions for generating Merkle Patricia Trie roots for various block components.

/**
 * Generates transactions trie root for a block
 * Creates a Merkle Patricia Trie from the transaction list and returns the root hash
 * @param txs - Array of typed transactions
 * @param emptyTrie - Optional pre-initialized empty trie for optimization
 * @returns Promise resolving to transaction trie root hash
 */
function genTransactionsTrieRoot(
  txs: TypedTransaction[],
  emptyTrie?: MerklePatriciaTrie
): Promise<Uint8Array>;

/**
 * Generates withdrawals trie root for a block (EIP-4895)
 * Creates a Merkle Patricia Trie from the withdrawals list and returns the root hash
 * @param wts - Array of withdrawal objects
 * @param emptyTrie - Optional pre-initialized empty trie for optimization
 * @returns Promise resolving to withdrawals trie root hash
 */
function genWithdrawalsTrieRoot(
  wts: Withdrawal[],
  emptyTrie?: MerklePatriciaTrie
): Promise<Uint8Array>;

/**
 * Generates requests trie root for a block (EIP-7685)
 * Creates a trie from consensus layer requests and returns the root hash
 * @param requests - Array of consensus layer requests
 * @param sha256Function - SHA256 hash function to use
 * @returns Requests trie root hash
 */
function genRequestsRoot(
  requests: CLRequest<CLRequestType>[],
  sha256Function: (data: Uint8Array) => Uint8Array
): Uint8Array;

Usage Examples:

import { 
  genTransactionsTrieRoot, 
  genWithdrawalsTrieRoot,
  genRequestsRoot 
} from "@ethereumjs/block";
import { MerklePatriciaTrie } from "@ethereumjs/mpt";
import { sha256 } from "ethereum-cryptography/sha256.js";

// Generate transaction trie root
const transactions = [
  // ... array of TypedTransaction objects
];

const txTrieRoot = await genTransactionsTrieRoot(transactions);
console.log("Transaction trie root:", txTrieRoot);

// Optimize with pre-initialized trie
const emptyTrie = new MerklePatriciaTrie();
const optimizedTxTrieRoot = await genTransactionsTrieRoot(transactions, emptyTrie);

// Generate withdrawals trie root (EIP-4895)
const withdrawals = [
  {
    index: 0,
    validatorIndex: 1234,
    address: Address.fromString("0x..."),
    amount: 32000000000n, // 32 ETH in gwei
  },
  // ... more withdrawals
];

const withdrawalsTrieRoot = await genWithdrawalsTrieRoot(withdrawals);
console.log("Withdrawals trie root:", withdrawalsTrieRoot);

// Generate requests trie root (EIP-7685)
const requests = [
  // ... array of CLRequest objects
];

const requestsRoot = genRequestsRoot(requests, sha256);
console.log("Requests root:", requestsRoot);

Data Conversion Functions

Functions for converting between different data formats used in Ethereum blocks.

/**
 * Converts raw header bytes array to HeaderData object
 * Transforms RLP-decoded bytes into a structured header data object
 * @param values - Array of header field bytes
 * @returns HeaderData object with named fields
 */
function valuesArrayToHeaderData(values: BlockHeaderBytes): HeaderData;

/**
 * Converts string number to hex string with 0x prefix
 * Handles conversion of numeric strings to prefixed hex format
 * @param input - Optional string number to convert
 * @returns Hex string with 0x prefix, or undefined if input is undefined
 */
function numberToHex(input?: string): PrefixedHexString | undefined;

/**
 * Gets difficulty value from header data
 * Extracts and converts difficulty field to bigint
 * @param headerData - Header data object
 * @returns Difficulty as bigint, or null if not present
 */
function getDifficulty(headerData: HeaderData): bigint | null;

Usage Examples:

import { 
  valuesArrayToHeaderData, 
  numberToHex, 
  getDifficulty 
} from "@ethereumjs/block";

// Convert raw bytes to header data
const rawHeaderBytes = [
  // ... array of Uint8Array field values from RLP decoding
];

const headerData = valuesArrayToHeaderData(rawHeaderBytes);
console.log("Converted header data:", {
  number: headerData.number,
  gasLimit: headerData.gasLimit,
  timestamp: headerData.timestamp,
});

// Convert numbers to hex strings
const blockNumber = "12345678";
const hexNumber = numberToHex(blockNumber);
console.log("Hex number:", hexNumber); // "0xbc614e"

// Extract difficulty from header data
const difficulty = getDifficulty(headerData);
console.log("Block difficulty:", difficulty);

Beacon Chain Integration

Functions for integrating with the beacon chain and Engine API.

/**
 * Converts beacon block execution payload JSON to ExecutionPayload
 * Transforms beacon chain payload format to execution layer format
 * @param payload - Beacon payload JSON object  
 * @returns ExecutionPayload object for block creation
 */
function executionPayloadFromBeaconPayload(payload: BeaconPayloadJSON): ExecutionPayload;

/**
 * BeaconPayloadJSON type definition
 * Represents the execution payload format from beacon chain
 */
type BeaconPayloadJSON = ExecutionPayload;

Usage Examples:

import { 
  executionPayloadFromBeaconPayload,
  createBlockFromExecutionPayload 
} from "@ethereumjs/block";

// Beacon chain execution payload
const beaconPayload = {
  parentHash: "0x1234...",
  feeRecipient: "0x5678...",
  stateRoot: "0x9abc...",
  receiptsRoot: "0xdef0...",
  logsBloom: "0x0000...",
  prevRandao: "0x1111...",
  blockNumber: "0x123456",
  gasLimit: "0x1c9c380",
  gasUsed: "0x47e7c4",
  timestamp: "0x60a7d8c0",
  extraData: "0x",
  baseFeePerGas: "0x3b9aca00",
  blockHash: "0x2468...",
  transactions: ["0xf86c...", "0xf86d..."],
  withdrawals: [
    {
      index: "0x0",
      validatorIndex: "0x4d2",
      address: "0x...",
      amount: "0x76a700",
    }
  ],
};

// Convert beacon payload to execution payload
const executionPayload = executionPayloadFromBeaconPayload(beaconPayload);

// Create block from execution payload
const block = await createBlockFromExecutionPayload(executionPayload);
console.log("Block created from beacon payload:", block.hash());

EIP-4844 Blob Utilities

Helper functions for working with blob transactions and blob gas calculations.

/**
 * Counts the number of blob transactions in a transaction array
 * Used for blob gas calculations and fee market operations
 * @param transactions - Array of typed transactions
 * @returns Number of blob transactions (type 3)
 */
function getNumBlobs(transactions: TypedTransaction[]): number;

/**
 * Computes blob gas price using exponential formula (EIP-4844)
 * Calculates current blob gas price based on excess blob gas
 * @param excessBlobGas - Current excess blob gas value
 * @param common - Common instance for network configuration
 * @returns Blob gas price in wei
 */
function computeBlobGasPrice(excessBlobGas: bigint, common: Common): bigint;

/**
 * Approximates exponential function using Taylor expansion
 * Used internally for blob gas price calculations
 * @param factor - Exponential factor  
 * @param numerator - Numerator for the calculation
 * @param denominator - Denominator for the calculation
 * @returns Approximated exponential result
 */
function fakeExponential(factor: bigint, numerator: bigint, denominator: bigint): bigint;

Usage Examples:

import { 
  getNumBlobs, 
  computeBlobGasPrice,
  createBlock 
} from "@ethereumjs/block";
import { Common } from "@ethereumjs/common";

// Create block with blob transactions
const blockWithBlobs = createBlock({
  header: {
    number: 19426587n, // Post-Cancun
    blobGasUsed: 393216n, // 3 blobs worth
    excessBlobGas: 0n,
  },
  transactions: [
    // ... mix of regular and blob transactions
  ],
});

// Count blob transactions
const numBlobs = getNumBlobs(blockWithBlobs.transactions);
console.log("Number of blob transactions:", numBlobs);

// Calculate blob gas price
const common = new Common({ chain: 'mainnet', hardfork: 'cancun' });
const excessBlobGas = 1000000n; // Some excess blob gas
const blobGasPrice = computeBlobGasPrice(excessBlobGas, common);
console.log("Blob gas price:", blobGasPrice);

// The price increases exponentially with excess blob gas
const higherExcess = 5000000n;
const higherPrice = computeBlobGasPrice(higherExcess, common);
console.log("Higher excess blob gas price:", higherPrice);
console.log("Price multiplier:", Number(higherPrice / blobGasPrice));

Block Parameter Access

Functions for accessing block parameters defined by various EIPs.

/**
 * Block parameters dictionary organized by EIP
 * Contains gas limits, difficulty adjustments, and other consensus parameters
 */
const paramsBlock: ParamsDict;

/**
 * Parameter dictionary interface
 * Organizes parameters by EIP number and provides access to consensus values
 */
interface ParamsDict {
  [eipNumber: string]: {
    [parameterName: string]: any;
  };
}

Usage Examples:

import { paramsBlock } from "@ethereumjs/block";

// Access EIP-1559 parameters
const eip1559Params = paramsBlock['1559'];
console.log("Base fee max change denominator:", eip1559Params?.baseFeeMaxChangeDenominator);
console.log("Elasticity multiplier:", eip1559Params?.elasticityMultiplier);

// Access EIP-4844 parameters  
const eip4844Params = paramsBlock['4844'];
console.log("Blob gas per blob:", eip4844Params?.blobGasPerBlob);
console.log("Target blob gas per block:", eip4844Params?.targetBlobGasPerBlock);

// Access difficulty bomb parameters
const difficultyParams = paramsBlock['100']; // Ice Age
console.log("Difficulty bomb delay:", difficultyParams?.difficultyBombDelay);

// Access gas limit parameters
const gasParams = paramsBlock['1'];
console.log("Min gas limit:", gasParams?.minGasLimit);
console.log("Gas limit bound divisor:", gasParams?.gasLimitBoundDivisor);

Hash and Encoding Utilities

Additional utility functions for common blockchain operations.

/**
 * Common hash constants used throughout the library
 */
interface HashConstants {
  /** Keccak hash of empty RLP encoding */
  KECCAK256_RLP: Uint8Array;
  
  /** Keccak hash of empty RLP array */
  KECCAK256_RLP_ARRAY: Uint8Array;
}

/**
 * Utility functions for bytes and hex operations
 */
interface BytesUtilities {
  /** Converts bytes to hex string with 0x prefix */
  bytesToHex(bytes: Uint8Array): PrefixedHexString;
  
  /** Checks if two byte arrays are equal */
  equalsBytes(a: Uint8Array, b: Uint8Array): boolean;
}

Usage Examples:

import { 
  KECCAK256_RLP, 
  KECCAK256_RLP_ARRAY,
  bytesToHex,
  equalsBytes 
} from "@ethereumjs/util"; // Re-exported from @ethereumjs/block

// Use empty hash constants
console.log("Empty RLP hash:", bytesToHex(KECCAK256_RLP));
console.log("Empty RLP array hash:", bytesToHex(KECCAK256_RLP_ARRAY));

// Convert bytes to hex
const blockHash = new Uint8Array(32).fill(0x12);
const hexHash = bytesToHex(blockHash);
console.log("Block hash:", hexHash);

// Compare byte arrays
const hash1 = new Uint8Array([1, 2, 3, 4]);
const hash2 = new Uint8Array([1, 2, 3, 4]);
const hash3 = new Uint8Array([1, 2, 3, 5]);

console.log("hash1 equals hash2:", equalsBytes(hash1, hash2)); // true
console.log("hash1 equals hash3:", equalsBytes(hash1, hash3)); // false