import { Common } from '@tevm/common'; import { Trie } from '@tevm/trie'; import { TxData, TransactionType, JsonTx, JsonRpcTx, TypedTransaction } from '@tevm/tx'; import { EthjsAddress, BytesLike, AddressLike, BigIntLike, WithdrawalData, Hex, JsonRpcWithdrawal, Withdrawal } from '@tevm/utils'; /** * Interface for consensus layer request types. * Defines the common structure for different types of consensus layer requests. * @example * ```typescript * import { CLRequestType } from '@tevm/block' * * // Usually implemented by specific request classes * const value: CLRequestType = { * type: 1, * bytes: new Uint8Array([0x01, 0x02, 0x03]), * serialize: () => new Uint8Array([0x01, 0x01, 0x02, 0x03]) * } * ``` */ interface CLRequestType { readonly type: number; readonly bytes: Uint8Array; serialize(): Uint8Array; } /** * Base implementation of a consensus layer request. * Used to create and serialize requests between the execution and consensus layers. * @example * ```typescript * import { ClRequest } from '@tevm/block' * * // Create a request with type 1 and some payload data * const instance = new ClRequest(1, new Uint8Array([0x01, 0x02, 0x03])) * const serialized = instance.serialize() // Type byte followed by payload * ``` */ declare class ClRequest implements CLRequestType { type: number; bytes: Uint8Array; constructor(type: number, bytes: Uint8Array); serialize(): Uint8Array; } interface HeaderCache { hash: Uint8Array | undefined; } /** * An object that represents the block header. */ declare class BlockHeader { readonly parentHash: Uint8Array; readonly uncleHash: Uint8Array; readonly coinbase: EthjsAddress; readonly stateRoot: Uint8Array; readonly transactionsTrie: Uint8Array; readonly receiptTrie: Uint8Array; readonly logsBloom: Uint8Array; readonly difficulty: bigint; readonly number: bigint; readonly gasLimit: bigint; readonly gasUsed: bigint; readonly timestamp: bigint; readonly extraData: Uint8Array; readonly mixHash: Uint8Array; readonly nonce: Uint8Array; readonly baseFeePerGas?: bigint; readonly withdrawalsRoot?: Uint8Array; readonly blobGasUsed?: bigint; readonly excessBlobGas?: bigint; readonly parentBeaconBlockRoot?: Uint8Array; readonly requestsRoot?: Uint8Array; readonly common: Common; protected keccakFunction: (msg: Uint8Array) => Uint8Array; protected cache: HeaderCache; /** * EIP-4399: After merge to PoS, `mixHash` supplanted as `prevRandao` */ get prevRandao(): Uint8Array; /** * Static constructor to create a block header from a header data dictionary * * @param headerData * @param opts */ static fromHeaderData(headerData: HeaderData, opts: BlockOptions): BlockHeader; /** * Static constructor to create a block header from a RLP-serialized header * * @param serializedHeaderData * @param opts */ static fromRLPSerializedHeader(serializedHeaderData: Uint8Array, opts: BlockOptions): BlockHeader; /** * Static constructor to create a block header from an array of Bytes values * * @param values * @param opts */ static fromValuesArray(values: BlockHeaderBytes, opts: BlockOptions): BlockHeader; /** * This constructor takes the values, validates them, assigns them and freezes the object. * * @deprecated Use the public static factory methods to assist in creating a Header object from * varying data types. For a default empty header, use {@link BlockHeader.fromHeaderData}. * */ constructor(headerData: HeaderData, opts: BlockOptions); /** * Validates correct buffer lengths, throws if invalid. */ protected _genericFormatValidation(): void; /** * Checks static parameters related to consensus algorithm * @throws if any check fails */ protected _consensusFormatValidation(): void; /** * Validates if the block gasLimit remains in the boundaries set by the protocol. * Throws if out of bounds. * * @param parentBlockHeader - the header from the parent `Block` of this header */ validateGasLimit(parentBlockHeader: BlockHeader): void; /** * Calculates the base fee for a potential next block */ calcNextBaseFee(): bigint; /** * Returns the price per unit of blob gas for a blob transaction in the current/pending block * @returns the price in gwei per unit of blob gas spent */ getBlobGasPrice(): bigint; /** * Returns the blob gas price depending upon the `excessBlobGas` value * @param excessBlobGas */ private _getBlobGasPrice; /** * Returns the total fee for blob gas spent for including blobs in block. * * @param numBlobs number of blobs in the transaction/block * @returns the total blob gas fee for numBlobs blobs */ calcDataFee(numBlobs: number): bigint; /** * Calculates the excess blob gas for next (hopefully) post EIP 4844 block. */ calcNextExcessBlobGas(): bigint; /** * Calculate the blob gas price of the block built on top of this one * @returns The blob gas price */ calcNextBlobGasPrice(): bigint; /** * Returns a Uint8Array Array of the raw Bytes in this header, in order. */ raw(): BlockHeaderBytes; /** * Returns the hash of the block header. */ hash(): Uint8Array; /** * Checks if the block header is a genesis header. */ isGenesis(): boolean; protected _requireClique(name: string): void; /** * Returns the canonical difficulty for this block. * * @param parentBlockHeader - the header from the parent `Block` of this header */ ethashCanonicalDifficulty(parentBlockHeader: BlockHeader): bigint; /** * PoA clique signature hash without the seal. */ cliqueSigHash(): Uint8Array; /** * Checks if the block header is an epoch transition * header (only clique PoA, throws otherwise) */ cliqueIsEpochTransition(): boolean; /** * Returns extra vanity data * (only clique PoA, throws otherwise) */ cliqueExtraVanity(): Uint8Array; /** * Returns extra seal data * (only clique PoA, throws otherwise) */ cliqueExtraSeal(): Uint8Array; /** * Seal block with the provided signer. * Returns the final extraData field to be assigned to `this.extraData`. * @hidden */ private cliqueSealBlock; /** * Returns a list of signers * (only clique PoA, throws otherwise) * * This function throws if not called on an epoch * transition block and should therefore be used * in conjunction with {@link BlockHeader.cliqueIsEpochTransition} */ cliqueEpochTransitionSigners(): EthjsAddress[]; /** * Verifies the signature of the block (last 65 bytes of extraData field) * (only clique PoA, throws otherwise) * * Method throws if signature is invalid */ cliqueVerifySignature(signerList: EthjsAddress[]): boolean; /** * Returns the signer address */ cliqueSigner(): EthjsAddress; /** * Returns the rlp encoding of the block header. */ serialize(): Uint8Array; /** * Returns the block header in JSON format. */ toJSON(): JsonHeader; /** * Validates extra data is DAO_ExtraData for DAO_ForceExtraDataRange blocks after DAO * activation block (see: https://blog.slock.it/hard-fork-specification-24b889e70703) */ protected _validateDAOExtraData(): void; /** * Return a compact error string representation of the object */ errorStr(): string; /** * Helper function to create an annotated error message * * @param msg Base error message * @hidden */ protected _errorMsg(msg: string): string; } /** * An object to set to which blockchain the blocks and their headers belong. This could be specified * using a {@link Common} object, or `chain` and `hardfork`. Defaults to mainnet without specifying a * hardfork. */ interface BlockOptions { /** * A {@link Common} object defining the chain and the hardfork a block/block header belongs to. * * Object will be internally copied so that tx behavior don't incidentally * change on future HF changes. * * Default: {@link Common} object set to `mainnet` and the HF currently defined as the default * hardfork in the {@link Common} class. * * Current default hardfork: `merge` */ common: Common; /** * Set the hardfork either by timestamp (for HFs from Shanghai onwards) or by block number * for older Hfs. * * Additionally it is possible to pass in a specific TD value to support live-Merge-HF * transitions. Note that this should only be needed in very rare and specific scenarios. * * Default: `false` (HF is set to whatever default HF is set by the {@link Common} instance) */ setHardfork?: boolean | BigIntLike; /** * If a preceding {@link BlockHeader} (usually the parent header) is given the preceding * header will be used to calculate the difficulty for this block and the calculated * difficulty takes precedence over a provided static `difficulty` value. * * Note that this option has no effect on networks other than PoW/Ethash networks * (respectively also deactivates on the Merge HF switching to PoS/Casper). */ calcDifficultyFromHeader?: BlockHeader; /** * A block object by default gets frozen along initialization. This gives you * strong additional security guarantees on the consistency of the block parameters. * It also enables block hash caching when the `hash()` method is called multiple times. * * If you need to deactivate the block freeze - e.g. because you want to subclass block and * add additional properties - it is strongly encouraged that you do the freeze yourself * within your code instead. * * Default: true */ freeze?: boolean; /** * Provide a clique signer's privateKey to seal this block. * Will throw if provided on a non-PoA chain. */ cliqueSigner?: Uint8Array; /** * Skip consensus format validation checks on header if set. Defaults to false. */ skipConsensusFormatValidation?: boolean; executionWitness?: VerkleExecutionWitness; } /** * Represents a Verkle proof used for state verification * * Verkle trees are an upgrade to Merkle Patricia trees that use vector commitments * instead of hash-based commitments, resulting in smaller proof sizes. * This interface contains the elements needed for Verkle proof verification. * * @see https://eips.ethereum.org/EIPS/eip-6800 for more details on Verkle trees in Ethereum * * @example * ```typescript * import { VerkleProof } from '@tevm/block' * * // Example of verifying a Verkle proof * function verifyProof(proof: VerkleProof, key: Hex, value: Hex, commitment: Hex): boolean { * // Verkle proof verification implementation would go here * return true * } * ``` */ interface VerkleProof { commitmentsByPath: Hex[]; d: Hex; depthExtensionPresent: Hex; ipaProof: { cl: Hex[]; cr: Hex[]; finalEvaluation: Hex; }; otherStems: Hex[]; } /** * Represents the state differences in a Verkle tree between two states * * Used to describe state changes between blocks in a more efficient way than * recording the entire state. Contains a mapping of stems (path prefixes) to * their corresponding state changes, along with proofs to verify these changes. * * Part of Ethereum's statelessness roadmap, enabling clients to validate blocks * without storing the entire state. * * @example * ```typescript * import { VerkleStateDiff } from '@tevm/block' * * // Example of applying state changes from a diff * function applyStateDiff(currentState: Map, diff: VerkleStateDiff): Map { * const updatedState = new Map(currentState) * * // Apply each change from the state diff * for (const [stem, changes] of Object.entries(diff.stateDiff)) { * for (const [key, value] of Object.entries(changes)) { * const fullKey = stem + key * if (value === null) { * updatedState.delete(fullKey) * } else { * updatedState.set(fullKey, value) * } * } * } * * return updatedState * } * ``` */ interface VerkleStateDiff { stem: Hex; suffixDiffs: { currentValue: Hex | null; newValue: Hex | null; suffix: number | string; }[]; } /** * Experimental, object format could eventual change. * An object that provides the state and proof necessary for verkle stateless execution * */ interface VerkleExecutionWitness { /** * An array of state diffs. * Each item corresponding to state accesses or state modifications of the block. * In the current design, it also contains the resulting state of the block execution (post-state). */ stateDiff: VerkleStateDiff[]; /** * The verkle proof for the block. * Proves that the provided stateDiff belongs to the canonical verkle tree. */ verkleProof: VerkleProof; } /** * A block header's data. */ interface HeaderData { parentHash?: BytesLike | string; uncleHash?: BytesLike | string; coinbase?: AddressLike | string; stateRoot?: BytesLike | string; transactionsTrie?: BytesLike | string; receiptTrie?: BytesLike | string; logsBloom?: BytesLike | string; difficulty?: BigIntLike | string; number?: BigIntLike | string; gasLimit?: BigIntLike | string; gasUsed?: BigIntLike | string; timestamp?: BigIntLike | string; extraData?: BytesLike | string; mixHash?: BytesLike | string; nonce?: BytesLike | string; baseFeePerGas?: BigIntLike | string; withdrawalsRoot?: BytesLike | string; blobGasUsed?: BigIntLike | string; excessBlobGas?: BigIntLike | string; parentBeaconBlockRoot?: BytesLike | string; requestsRoot?: BytesLike | string; } /** * A block's data. */ interface BlockData { /** * Header data for the block */ header?: HeaderData; transactions?: Array; uncleHeaders?: Array; withdrawals?: Array; requests?: Array; /** * EIP-6800: Verkle Proof Data (experimental) */ executionWitness?: VerkleExecutionWitness | null; } /** * Represents the raw byte representation of Ethereum withdrawal objects * * Each element in the array is a serialized withdrawal object from the Beacon chain. * Used in post-merge Ethereum as part of the engine API and block structure for * processing withdrawals from the consensus layer to the execution layer. * * @example * ```typescript * import { WithdrawalsBytes } from '@tevm/block' * * // Decode withdrawals from their byte representation * function decodeWithdrawals(withdrawalBytes: WithdrawalsBytes): WithdrawalV1[] { * return withdrawalBytes.map(bytes => { * // Implement decoding logic to extract withdrawal data * return { * index: getUint64FromBytes(bytes, 0), * validatorIndex: getUint64FromBytes(bytes, 8), * address: getAddressFromBytes(bytes, 16), * amount: getUint64FromBytes(bytes, 48) * } * }) * } * ``` */ type WithdrawalsBytes = Uint8Array[]; /** * Represents serialized consensus layer requests in byte format * * Used in the Cancun upgrade (EIP-4788) for including consensus layer data * in execution layer blocks. Each element in the array is a serialized request * with data from the consensus layer. * * @see https://eips.ethereum.org/EIPS/eip-4788 for more details * * @example * ```typescript * import { RequestsBytes } from '@tevm/block' * * // Process consensus layer requests from their byte representation * function processRequests(requestsBytes: RequestsBytes): void { * for (const requestBytes of requestsBytes) { * // Parse request data * const parentBeaconBlockRoot = requestBytes.slice(0, 32) * * // Process the consensus layer request * storeBeaconBlockRoot(parentBeaconBlockRoot) * } * } * ``` */ type RequestsBytes = Uint8Array[]; /** * Represents the serialized form of execution witness data * * Used in stateless Ethereum to provide witnesses (proofs) needed for * transaction execution without requiring the full state. Contains * Verkle proofs and state differences needed to validate state transitions. * * Part of Ethereum's roadmap towards statelessness with Verkle trees. * * @example * ```typescript * import { ExecutionWitnessBytes, VerkleExecutionWitness } from '@tevm/block' * import { decode } from '@tevm/rlp' * * // Decode execution witness from its serialized form * function decodeWitness(witnessBytes: ExecutionWitnessBytes): VerkleExecutionWitness { * const decoded = decode(witnessBytes) as unknown[] * * // Extract the witness components (simplified example) * return { * stateDiff: deserializeStateDiffs(decoded[0]), * verkleProof: deserializeVerkleProof(decoded[1]) * } * } * ``` */ type ExecutionWitnessBytes = Uint8Array; /** * Represents the serialized form of an Ethereum block * * The structure is a tuple of components, with variations depending on the Ethereum hardfork: * - First element: Block header bytes * - Second element: Transactions bytes * - Third element: Uncle headers bytes * - Fourth element (optional): Withdrawals bytes (post-Shanghai) * - Fifth element (optional): Requests bytes (post-Cancun) * - Sixth element (optional): Execution witness bytes (for stateless Ethereum) * * The format evolves with new Ethereum upgrades as additional block components are added. * * @example * ```typescript * import { BlockBytes, Block } from '@tevm/block' * import { decode } from '@tevm/rlp' * * // Decode a complete block from its serialized form * function decodeBlock(blockBytes: BlockBytes): Block { * // Determine format based on array length * if (blockBytes.length === 3) { * // Pre-Shanghai format * const [headerBytes, txBytes, uncleBytes] = blockBytes * return { * header: decodeHeader(headerBytes), * transactions: decodeTxs(txBytes), * uncleHeaders: decodeUncles(uncleBytes), * } * } else if (blockBytes.length === 4) { * // Post-Shanghai format with withdrawals * const [headerBytes, txBytes, uncleBytes, withdrawalBytes] = blockBytes * return { * header: decodeHeader(headerBytes), * transactions: decodeTxs(txBytes), * uncleHeaders: decodeUncles(uncleBytes), * withdrawals: decodeWithdrawals(withdrawalBytes), * } * } * // Handle other formats as needed * } * ``` */ type BlockBytes = [BlockHeaderBytes, TransactionsBytes, UncleHeadersBytes] | [BlockHeaderBytes, TransactionsBytes, UncleHeadersBytes, WithdrawalsBytes] | [BlockHeaderBytes, TransactionsBytes, UncleHeadersBytes, WithdrawalsBytes, RequestsBytes] | [BlockHeaderBytes, TransactionsBytes, UncleHeadersBytes, WithdrawalsBytes, RequestsBytes, ExecutionWitnessBytes]; /** * BlockHeaderBuffer is a Buffer array, except for the Verkle PreState which is an array of prestate arrays. */ type BlockHeaderBytes = Uint8Array[]; /** * Represents the serialized form of an Ethereum block body * * Contains all block components except the header. The structure is: * - First element: Transactions bytes * - Second element: Uncle headers bytes * - Third element (optional): Withdrawals bytes (post-Shanghai) * - Fourth element (optional): Additional data (like consensus layer requests) * * Used when transmitting or processing block bodies separately from headers, * typically in Ethereum's P2P protocols. * * @example * ```typescript * import { BlockBodyBytes, BlockBody } from '@tevm/block' * * // Decode a block body * function decodeBlockBody(bodyBytes: BlockBodyBytes): BlockBody { * const [txBytes, uncleBytes, withdrawalBytes] = bodyBytes * * return { * transactions: decodeTxs(txBytes), * uncleHeaders: decodeUncles(uncleBytes), * ...(withdrawalBytes ? { withdrawals: decodeWithdrawals(withdrawalBytes) } : {}) * } * } * * // For network transmission * function getBlockBody(block: Block): BlockBodyBytes { * const body: BlockBodyBytes = [ * encodeTxs(block.transactions), * encodeUncles(block.uncleHeaders) * ] * * if (block.withdrawals) { * body.push(encodeWithdrawals(block.withdrawals)) * } * * return body * } * ``` */ type BlockBodyBytes = [TransactionsBytes, UncleHeadersBytes, WithdrawalsBytes?, Uint8Array?]; /** * TransactionsBytes can be an array of serialized txs for Typed Transactions or an array of Uint8Array Arrays for legacy transactions. */ type TransactionsBytes = Uint8Array[][] | Uint8Array[]; /** * Represents serialized uncle (ommer) block headers * * Uncle blocks are valid blocks that weren't included in the main chain. * In Ethereum's PoW era, miners would include references to these blocks * and receive a partial reward. Each element is a serialized block header. * * While uncles are not relevant in post-merge Ethereum (PoS), the data * structure remains for backward compatibility. * * @example * ```typescript * import { UncleHeadersBytes, BlockHeader } from '@tevm/block' * * // Decode uncle headers from their serialized form * function decodeUncleHeaders(uncleBytes: UncleHeadersBytes): BlockHeader[] { * return uncleBytes.map(headerBytes => { * // Process each uncle header using the same header decoding logic * return decodeBlockHeader(headerBytes) * }) * } * * // Check if a block has uncles * function hasUncles(uncleBytes: UncleHeadersBytes): boolean { * return uncleBytes.length > 0 * } * ``` */ type UncleHeadersBytes = Uint8Array[][]; /** * An object with the block's data represented as strings. */ interface JsonBlock { /** * Header data for the block */ header?: JsonHeader; transactions?: JsonTx[]; uncleHeaders?: JsonHeader[]; withdrawals?: JsonRpcWithdrawal[]; requests?: Hex[] | null; executionWitness?: VerkleExecutionWitness | null; } /** * An object with the block header's data represented as 0x-prefixed hex strings. */ interface JsonHeader { parentHash?: Hex | string; uncleHash?: Hex | string; coinbase?: Hex | string; stateRoot?: Hex | string; transactionsTrie?: Hex | string; receiptTrie?: Hex | string; logsBloom?: Hex | string; difficulty?: Hex | string; number?: Hex | string; gasLimit?: Hex | string; gasUsed?: Hex | string; timestamp?: Hex | string; extraData?: Hex | string; mixHash?: Hex | string; nonce?: Hex | string; baseFeePerGas?: Hex | string; withdrawalsRoot?: Hex | string; blobGasUsed?: Hex | string; excessBlobGas?: Hex | string; parentBeaconBlockRoot?: Hex | string; requestsRoot?: Hex | string; } interface JsonRpcBlock { number: Hex | string; hash: Hex | string; parentHash: Hex | string; mixHash?: Hex | string; nonce: Hex | string; sha3Uncles: Hex | string; logsBloom: Hex | string; transactionsRoot: Hex | string; stateRoot: Hex | string; receiptsRoot: Hex | string; miner: Hex | string; difficulty: Hex | string; totalDifficulty: Hex | string; extraData: Hex | string; size: Hex | string; gasLimit: Hex | string; gasUsed: Hex | string; timestamp: Hex | string; transactions: Array; uncles: Hex[] | string[]; baseFeePerGas?: Hex | string; withdrawals?: Array; withdrawalsRoot?: Hex | string; blobGasUsed?: Hex | string; excessBlobGas?: Hex | string; parentBeaconBlockRoot?: Hex | string; executionWitness?: VerkleExecutionWitness | null; requestsRoot?: Hex | string; requests?: Array; } /** * Represents an Ethereum withdrawal from the consensus layer to the execution layer * * Introduced in the Shanghai/Capella upgrade (EIP-4895), these withdrawals allow validators * to receive ETH from the beacon chain to their execution layer accounts. * * @see https://eips.ethereum.org/EIPS/eip-4895 for detailed information * * @example * ```typescript * import { WithdrawalV1 } from '@tevm/block' * * // Example withdrawal object * const withdrawal: WithdrawalV1 = { * index: '0x42', // Sequential index * validatorIndex: '0x7b', // Index of the validator * address: '0x0c54fccd2e384b4bb6f2e405bf5cbc15a017aafb', // Recipient address * amount: '0x1bc16d674ec80000' // Amount in Gwei (2 ETH) * } * * // Process withdrawals in a block * function processWithdrawals(withdrawals: WithdrawalV1[]): void { * for (const withdrawal of withdrawals) { * // Credit the amount to the recipient's account * creditAccount(withdrawal.address, BigInt(withdrawal.amount)) * } * } * ``` */ type WithdrawalV1 = { index: Hex; validatorIndex: Hex; address: Hex; amount: Hex; }; /** * Represents the execution layer data of an Ethereum block * * Introduced with The Merge (Paris fork), the ExecutionPayload is passed between * the consensus layer and execution layer as part of the Engine API. It contains * all the information needed for transaction execution and state updates. * * The structure has evolved over time with various Ethereum upgrades: * - The Merge (Paris): Basic structure with transactions * - Shanghai: Added withdrawals field * - Cancun: Added blobGasUsed, excessBlobGas, parentBeaconBlockRoot * - Prague (planned): Will add verkle-related fields * * @see https://github.com/ethereum/execution-apis/blob/main/src/engine/shanghai.md * * @example * ```typescript * import { ExecutionPayload } from '@tevm/block' * * // Engine API handler receiving a payload from the consensus layer * async function handleNewPayload(payload: ExecutionPayload): Promise<{status: string}> { * // Validate the payload * const validationResult = await validateExecutionPayload(payload) * * if (validationResult.valid) { * // Execute transactions and update state * await executeTransactions(payload.transactions) * * // Process withdrawals if present * if (payload.withdrawals) { * await processWithdrawals(payload.withdrawals) * } * * return { status: 'VALID' } * } else { * return { status: 'INVALID', validationError: validationResult.error } * } * } * ``` */ type ExecutionPayload = { parentHash: Hex | string; feeRecipient: Hex | string; stateRoot: Hex | string; receiptsRoot: Hex | string; logsBloom: Hex | string; prevRandao: Hex | string; blockNumber: Hex | string; gasLimit: Hex | string; gasUsed: Hex | string; timestamp: Hex | string; extraData: Hex | string; baseFeePerGas: Hex | string; blockHash: Hex | string; transactions: Hex[] | string[]; withdrawals?: WithdrawalV1[]; blobGasUsed?: Hex | string; excessBlobGas?: Hex | string; parentBeaconBlockRoot?: Hex | string; executionWitness?: VerkleExecutionWitness | null; requestsRoot?: Hex | string | null; }; type BeaconWithdrawal = { index: Hex; validator_index: Hex; address: Hex; amount: Hex; }; /** * Represents the JSON structure of an execution payload from the Beacon API * * This type uses snake_case property names as returned by the Beacon API, * as opposed to the camelCase used internally in Tevm. Used when fetching * execution payloads from a consensus layer client. * * @see https://ethereum.github.io/beacon-APIs/ for the Beacon API specification * * @example * ```typescript * import { BeaconPayloadJson, executionPayloadFromBeaconPayload } from '@tevm/block' * * // Fetch the payload from a Beacon API * async function getExecutionPayload(blockNumber: number) { * const response = await fetch( * `http://localhost:5052/eth/v2/beacon/blocks/${blockNumber}` * ) * const data = await response.json() * * // Extract and parse the execution payload * const beaconPayload: BeaconPayloadJson = data.data.message.body.execution_payload * * // Convert to Tevm's internal ExecutionPayload format * return executionPayloadFromBeaconPayload(beaconPayload) * } * ``` */ type BeaconPayloadJson = { parent_hash: Hex; fee_recipient: Hex; state_root: Hex; receipts_root: Hex; logs_bloom: Hex; prev_randao: Hex; block_number: Hex; gas_limit: Hex; gas_used: Hex; timestamp: Hex; extra_data: Hex; base_fee_per_gas: Hex; block_hash: Hex; transactions: Hex[]; withdrawals?: BeaconWithdrawal[]; blob_gas_used?: Hex; excess_blob_gas?: Hex; parent_beacon_block_root?: Hex; execution_witness?: VerkleExecutionWitness; }; /** * Converts a beacon block execution payload JSON object {@link BeaconPayloadJson} to the {@link ExecutionPayload} data needed to construct a {@link Block}. * The JSON data can be retrieved from a consensus layer (CL) client on this Beacon API `/eth/v2/beacon/blocks/[block number]` */ declare function executionPayloadFromBeaconPayload(payload: BeaconPayloadJson): ExecutionPayload; /** * An object that represents the block. */ declare class Block { readonly header: BlockHeader; readonly transactions: TypedTransaction[]; readonly uncleHeaders: BlockHeader[]; readonly withdrawals?: Withdrawal[] | undefined; readonly requests?: ClRequest[] | undefined; readonly common: Common; protected keccakFunction: (msg: Uint8Array) => Uint8Array; /** * EIP-6800: Verkle Proof Data (experimental) * null implies that the non default executionWitness might exist but not available * and will not lead to execution of the block via vm with verkle stateless manager */ readonly executionWitness?: VerkleExecutionWitness | null | undefined; protected cache: { txTrieRoot?: Uint8Array; withdrawalsTrieRoot?: Uint8Array; requestsRoot?: Uint8Array; }; /** * Returns the withdrawals trie root for array of Withdrawal. * @param wts array of Withdrawal to compute the root of * @param optional emptyTrie to use to generate the root */ static genWithdrawalsTrieRoot(wts: Withdrawal[], emptyTrie?: Trie): Promise>; /** * Returns the txs trie root for array of TypedTransaction * @param txs array of TypedTransaction to compute the root of * @param optional emptyTrie to use to generate the root */ static genTransactionsTrieRoot(txs: TypedTransaction[], emptyTrie?: Trie): Promise>; /** * Returns the requests trie root for an array of CLRequests * @param requests - an array of CLRequests * @param emptyTrie optional empty trie used to generate the root * @returns a 32 byte Uint8Array representing the requests trie root */ static genRequestsTrieRoot(requests: ClRequest[], emptyTrie?: Trie): Promise>; /** * Static constructor to create a block from a block data dictionary * * @param blockData * @param opts * @deprecated Use createBlock() instead - this method is kept for compatibility */ static fromBlockData(blockData: BlockData, opts: BlockOptions): Block; /** * Static constructor to create a block from a RLP-serialized block * * @param serialized * @param opts * @deprecated Use createBlockFromRLP() instead - this method is kept for compatibility */ static fromRLPSerializedBlock(serialized: Uint8Array, opts: BlockOptions): Block; /** * Static constructor to create a block from an array of Bytes values * * @param values * @param opts * @deprecated Use createBlockFromValuesArray() instead - this method is kept for compatibility */ static fromValuesArray(values: BlockBytes, opts: BlockOptions): Block; /** * Method to retrieve a block from an execution payload * @param execution payload constructed from beacon payload * @param opts {@link BlockOptions} * @returns the block constructed block */ static fromExecutionPayload(payload: ExecutionPayload, opts: BlockOptions): Promise; /** * Method to retrieve a block from a beacon payload json * @param payload json of a beacon beacon fetched from beacon apis * @param opts {@link BlockOptions} * @returns the block constructed block */ static fromBeaconPayloadJson(payload: BeaconPayloadJson, opts: BlockOptions): Promise; /** * This constructor takes the values, validates them, assigns them and freezes the object. * Use the static factory methods to assist in creating a Block object from varying data types and options. */ constructor(opts: BlockOptions, header?: BlockHeader, transactions?: TypedTransaction[], uncleHeaders?: BlockHeader[], withdrawals?: Withdrawal[], requests?: ClRequest[], executionWitness?: VerkleExecutionWitness | null); /** * Returns a Array of the raw Bytes Arrays of this block, in order. */ raw(): BlockBytes; /** * Returns the hash of the block. */ hash(): Uint8Array; /** * Determines if this block is the genesis block. */ isGenesis(): boolean; /** * Returns the rlp encoding of the block. */ serialize(): Uint8Array; /** * Generates transaction trie for validation. */ genTxTrie(): Promise; /** * Validates the transaction trie by generating a trie * and do a check on the root hash. * @returns True if the transaction trie is valid, false otherwise */ transactionsTrieIsValid(): Promise; requestsTrieIsValid(): Promise; /** * Validates transaction signatures and minimum gas requirements. * @returns {string[]} an array of error strings */ getTransactionsValidationErrors(): string[]; /** * Validates transaction signatures and minimum gas requirements. * @returns True if all transactions are valid, false otherwise */ transactionsAreValid(): boolean; /** * Validates the block data, throwing if invalid. * This can be checked on the Block itself without needing access to any parent block * It checks: * - All transactions are valid * - The transactions trie is valid * - The uncle hash is valid * @param onlyHeader if only passed the header, skip validating txTrie and unclesHash (default: false) * @param verifyTxs if set to `false`, will not check for transaction validation errors (default: true) */ validateData(onlyHeader?: boolean, verifyTxs?: boolean): Promise; /** * Validates that blob gas fee for each transaction is greater than or equal to the * blobGasPrice for the block and that total blob gas in block is less than maximum * blob gas per block * @param parentHeader header of parent block */ validateBlobTransactions(parentHeader: BlockHeader): void; /** * Validates the uncle's hash. * @returns true if the uncle's hash is valid, false otherwise. */ uncleHashIsValid(): boolean; /** * Validates the withdrawal root * @returns true if the withdrawals trie root is valid, false otherwise */ withdrawalsTrieIsValid(): Promise; /** * Consistency checks for uncles included in the block, if any. * * Throws if invalid. * * The rules for uncles checked are the following: * Header has at most 2 uncles. * Header does not count an uncle twice. */ validateUncles(): void; /** * Returns the canonical difficulty for this block. * * @param parentBlock - the parent of this `Block` */ ethashCanonicalDifficulty(parentBlock: Block): bigint; /** * Validates if the block gasLimit remains in the boundaries set by the protocol. * Throws if invalid * * @param parentBlock - the parent of this `Block` */ validateGasLimit(parentBlock: Block): void; /** * Returns the block in JSON format. */ toJSON(): JsonBlock; toExecutionPayload(): ExecutionPayload; /** * Return a compact error string representation of the object */ errorStr(): string; /** * Internal helper function to create an annotated error message * * @param msg Base error message * @hidden */ protected _errorMsg(msg: string): string; } /** * Creates a new block object from Ethereum JSON RPC. * * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) * @param uncles - Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) * @param options - An object describing the blockchain * @deprecated */ declare function blockFromRpc(blockParams: JsonRpcBlock, options: BlockOptions, uncles?: any[]): Block; /** * Converts a BlockHeaderBytes array to a HeaderData object * @param {BlockHeaderBytes} values - Array of raw header bytes containing block header fields * @returns {HeaderData} The converted header data object with named properties * @example * ```typescript * import { valuesArrayToHeaderData } from '@tevm/block' * * // Convert raw header bytes to a structured HeaderData object * const headerData = valuesArrayToHeaderData(blockHeaderBytes) * console.log(headerData.parentHash, headerData.stateRoot) * ``` */ declare function valuesArrayToHeaderData(values: BlockHeaderBytes): HeaderData; /** * Extracts the difficulty value from block header data * @param {HeaderData} headerData - The header data object to extract difficulty from * @returns {bigint | null} The difficulty as a bigint, or null if not present * @example * ```typescript * import { getDifficulty } from '@tevm/block' * * // Get the difficulty from a block header * const difficulty = getDifficulty(blockHeader) * if (difficulty !== null) { * console.log(`Block difficulty: ${difficulty}`) * } * ``` */ declare function getDifficulty(headerData: HeaderData): bigint | null; /** * Creates a block from a block data dictionary * @param blockData - The block data * @param opts - Options for the block * @returns A new Block instance * @see Block.fromBlockData */ declare function createBlock(blockData: BlockData, opts: BlockOptions): Block; /** * Creates a block from a RLP-serialized block * @param serialized - The serialized block data * @param opts - Options for the block * @returns A new Block instance * @see Block.fromRLPSerializedBlock */ declare function createBlockFromRLP(serialized: Uint8Array, opts: BlockOptions): Block; /** * Creates a block from an array of Bytes values * @param values - The block values array * @param opts - Options for the block * @returns A new Block instance * @see Block.fromValuesArray */ declare function createBlockFromValuesArray(values: BlockBytes, opts: BlockOptions): Block; /** * Creates a block from an execution payload * @param payload - The execution payload * @param opts - Options for the block * @returns A promise that resolves to a new Block instance * @see Block.fromExecutionPayload */ declare function createBlockFromExecutionPayload(payload: ExecutionPayload, opts: BlockOptions): Promise; /** * Creates a block from a beacon payload JSON * @param payload - The beacon payload JSON * @param opts - Options for the block * @returns A promise that resolves to a new Block instance * @see Block.fromBeaconPayloadJson */ declare function createBlockFromBeaconPayload(payload: BeaconPayloadJson, opts: BlockOptions): Promise; /** * Creates a block header from header data * @param headerData - The header data * @param opts - Options for the block header * @returns A new BlockHeader instance * @see BlockHeader.fromHeaderData */ declare function createBlockHeader(headerData: HeaderData, opts: BlockOptions): BlockHeader; /** * Creates a block header from a RLP-serialized header * @param serializedHeaderData - The serialized header data * @param opts - Options for the block header * @returns A new BlockHeader instance * @see BlockHeader.fromRLPSerializedHeader */ declare function createBlockHeaderFromRLP(serializedHeaderData: Uint8Array, opts: BlockOptions): BlockHeader; /** * Creates a block header from an array of Bytes values * @param values - The header values array * @param opts - Options for the block header * @returns A new BlockHeader instance * @see BlockHeader.fromValuesArray */ declare function createBlockHeaderFromValuesArray(values: BlockHeaderBytes, opts: BlockOptions): BlockHeader; export { type BeaconPayloadJson, Block, type BlockBodyBytes, type BlockBytes, type BlockData, BlockHeader, type BlockHeaderBytes, type BlockOptions, ClRequest, type ExecutionPayload, type ExecutionWitnessBytes, type HeaderData, type JsonBlock, type JsonHeader, type JsonRpcBlock, type RequestsBytes, type TransactionsBytes, type UncleHeadersBytes, type VerkleExecutionWitness, type VerkleProof, type VerkleStateDiff, type WithdrawalV1, type WithdrawalsBytes, blockFromRpc, createBlock, createBlockFromBeaconPayload, createBlockFromExecutionPayload, createBlockFromRLP, createBlockFromValuesArray, createBlockHeader, createBlockHeaderFromRLP, createBlockHeaderFromValuesArray, executionPayloadFromBeaconPayload, getDifficulty, valuesArrayToHeaderData };