v10| Execution Context for the Ethereum EVM Implementation. | | —————————————————— |
Ethereum mainnet compatible execution context for
@ethereumjs/evm
to build and run blocks and txs and update state.
@Noble crypto)To obtain the latest version, simply require the project using npm:
npm install @ethereumjs/vm
Note: Starting with the Dencun hardfork EIP-4844 related functionality has become an integrated part of the EVM functionality with the activation of the point evaluation precompile. For this precompile to work a separate installation of the KGZ library is necessary (we decided not to bundle due to large bundle sizes), see KZG Setup for instructions.
// ./examples/runTx.ts
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createLegacyTx } from '@ethereumjs/tx'
import { createAccount, createAddressFromPrivateKey, createZeroAddress, hexToBytes } from '@ethereumjs/util'
import { createVM, runTx } from '@ethereumjs/vm'
const main = async () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai })
const vm = await createVM({ common })
const senderKey = hexToBytes(`0x${'20'.repeat(32)}`)
const sender = createAddressFromPrivateKey(senderKey)
await vm.stateManager.putAccount(sender, createAccount({ nonce: 0n, balance: BigInt(1e18) }))
const tx = createLegacyTx({
gasLimit: 21000n,
gasPrice: 1_000_000_000n,
value: 1n,
to: createZeroAddress(),
}).sign(senderKey)
const res = await runTx(vm, { tx })
console.log(res.totalGasSpent) // 21000n - gas cost for simple ETH transfer
}
void main()
Additionally to the VM.runTx() method there is an API method VM.runBlock() which allows to run the whole block and execute all included transactions along.
runTx() and runBlock() surface logs through transaction receipts using the same Log tuple as @ethereumjs/evm:
type Log = [address: Uint8Array, topics: Uint8Array[], data: Uint8Array]
| API | Where to read logs |
|---|---|
runTx() |
result.receipt.logs (also result.execResult.logs before receipt assembly) |
runBlock() |
result.results[i].receipt.logs and result.receipts[i].logs |
| Block header bloom | result.logsBloom on RunBlockResult; result.bloom on each RunTxResult |
Logs from contract LOG* opcodes and fork-specific synthetic logs (e.g. EIP-7708 transfer logs on Amsterdam) share this path — no separate receipt field.
See examples/runTxTransferLogs.ts for an Amsterdam value transfer that decodes an EIP-7708 Transfer log from receipt.logs. For bytecode-level emission see @ethereumjs/evm Event logs and examples/emitLogs.ts.
Notes:
logs (Byzantium+ status: 0).DEBUG=ethjs,...) refer to development tracing, not EVM event logs.It is possible to fetch a real mainnet block via JSON-RPC and execute it locally using the VM together with the RPCStateManager from the @ethereumjs/statemanager package, which fetches account and storage data on demand from a remote provider.
Note: Running recent mainnet blocks will generate thousands of RPC requests (one for each account/storage access during EVM execution). Make sure your RPC provider can handle the load and be mindful of rate limits and quotas.
// ./examples/runBlockWithRPC.ts
import { createBlockFromJSONRPCProvider } from '@ethereumjs/block'
import { Common, Mainnet } from '@ethereumjs/common'
import { RPCStateManager } from '@ethereumjs/statemanager'
import { bytesToHex } from '@ethereumjs/util'
import { createVM, runBlock } from '@ethereumjs/vm'
import { trustedSetup } from '@paulmillr/trusted-setups/fast-peerdas.js'
import { KZG as microEthKZG } from 'micro-eth-signer/kzg.js'
const main = async () => {
const providerUrl = process.argv[2]
let blockNumber: bigint | undefined
try {
blockNumber = process.argv[3] !== undefined ? BigInt(process.argv[3]) : undefined
} catch {
// argument is not a valid block number
}
if (providerUrl === undefined || blockNumber === undefined) {
console.log('Example skipped (real-world RPC scenario)')
console.log('Usage: npx tsx runBlockWithRPC.ts <providerUrl> <blockNumber>')
return
}
const kzg = new microEthKZG(trustedSetup)
const common = new Common({ chain: Mainnet, customCrypto: { kzg } })
// 1. Fetch block from RPC
console.log(`Fetching block ${blockNumber} from ${providerUrl}...`)
const block = await createBlockFromJSONRPCProvider(providerUrl, blockNumber, {
common,
setHardfork: true,
})
console.log(`Block ${block.header.number} fetched successfully`)
console.log(` Hash: ${bytesToHex(block.hash())}`)
console.log(` Parent hash: ${bytesToHex(block.header.parentHash)}`)
console.log(` State root: ${bytesToHex(block.header.stateRoot)}`)
console.log(` Transactions: ${block.transactions.length}`)
console.log(` Gas used: ${block.header.gasUsed}`)
console.log(` Hardfork: ${block.common.hardfork()}`)
// 2. Set up RPC state manager pointing to the parent block (pre-state)
const stateManager = new RPCStateManager({
provider: providerUrl,
blockTag: blockNumber - 1n,
common,
})
// 3. Create VM with the RPC state manager
const vm = await createVM({ common, stateManager, setHardfork: true })
// 4. Run the block
console.log(`\nRunning block ${blockNumber} (${block.transactions.length} txs)...`)
const startTime = performance.now()
const result = await runBlock(vm, {
block,
generate: true,
skipHeaderValidation: true,
skipBlockValidation: true,
})
const elapsed = ((performance.now() - startTime) / 1000).toFixed(1)
// 5. Display results
console.log(`\nBlock execution completed in ${elapsed}s`)
console.log(` Tx results: ${result.results.length}`)
console.log(` Receipts root: ${bytesToHex(result.receiptsRoot)}`)
console.log(`\n Gas used: ${result.gasUsed} (expected: ${block.header.gasUsed})`)
if (result.gasUsed === block.header.gasUsed) {
console.log(` Gas used MATCHES expected block header value`)
} else {
console.log(` Gas used MISMATCH`)
}
// Note: State root comparison is informational only.
// RPCStateManager cannot produce valid Merkle state roots since it
// doesn't maintain a local trie -- it fetches state on demand via RPC.
console.log(`\n Computed state root: ${bytesToHex(result.stateRoot)}`)
console.log(` Expected state root: ${bytesToHex(block.header.stateRoot)}`)
console.log(` (State root comparison is not meaningful with RPCStateManager,`)
console.log(` which does not maintain a local Merkle trie)`)
}
void main()
Run with:
npx tsx examples/runBlockWithRPC.ts <providerUrl> <blockNumber>
The VM package can also be used to construct a new valid block by executing and then integrating txs one-by-one.
The following non-complete example gives some illustration on how to use the Block Builder API:
// ./examples/buildBlock.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createLegacyTx } from '@ethereumjs/tx'
import { Account, bytesToHex, createAddressFromPrivateKey, hexToBytes } from '@ethereumjs/util'
import { buildBlock, createVM } from '@ethereumjs/vm'
const main = async () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Prague })
const vm = await createVM({ common })
const parentBlock = createBlock(
{ header: { number: 1n } },
{ common, skipConsensusFormatValidation: true },
)
const headerData = {
number: 2n,
}
const blockBuilder = await buildBlock(vm, {
parentBlock, // the parent @ethereumjs/block Block
headerData, // header values for the new block
blockOpts: {
calcDifficultyFromHeader: parentBlock.header,
freeze: false,
skipConsensusFormatValidation: true,
putBlockIntoBlockchain: false,
},
})
const pk = hexToBytes('0x26f81cbcffd3d23eace0bb4eac5274bb2f576d310ee85318b5428bf9a71fc89a')
const address = createAddressFromPrivateKey(pk)
const account = new Account(0n, 0xfffffffffn)
await vm.stateManager.putAccount(address, account) // create a sending account and give it a big balance
const tx = createLegacyTx({ gasLimit: 0xffffff, gasPrice: 75n }).sign(pk)
await blockBuilder.addTransaction(tx)
// Add more transactions
const { block } = await blockBuilder.build()
console.log(`Built a block with hash ${bytesToHex(block.hash())}`)
}
void main()
This library by default uses JavaScript implementations for the basic standard crypto primitives like hashing or signature verification (for included txs). See @ethereumjs/common README for instructions on how to replace with e.g. a more performant WASM implementation by using a shared common instance.
See the examples folder for different meaningful examples on how to use the VM package and invoke certain aspects of it, e.g. running a complete block, a certain tx or using event listeners, among others. Some noteworthy examples to point out:
Transfer logs from a transaction receipt on Amsterdam.@ethereumjs/evm): Emits a LOG1 from bytecode via runCode().We provide hybrid ESM/CJS builds for all our libraries. With the v10 breaking release round from Spring 2025, all libraries are “pure-JS” by default and we have eliminated all hard-wired WASM code. Additionally we have substantially lowered the bundle sizes, reduced the number of dependencies, and cut out all usages of Node.js-specific primitives (like the Node.js event emitter).
It is easily possible to run a browser build of one of the EthereumJS libraries within a modern browser using the provided ESM build. For a setup example see ./examples/browser.html.
For documentation on VM instantiation, exposed API and emitted events see generated API docs.
With the breaking releases from Summer 2023 we have started to ship our libraries with both CommonJS (cjs folder) and ESM builds (esm folder), see package.json for the detailed setup.
If you use an ES6-style import in your code files from the ESM build will be used:
import { EthereumJSClass } from '@ethereumjs/[PACKAGE_NAME]'
If you use Node.js specific require, the CJS build will be used:
const { EthereumJSClass } = require('@ethereumjs/[PACKAGE_NAME]')
Using ESM will give you additional advantages over CJS beyond browser usage like static code analysis / Tree Shaking which CJS can not provide.
Starting with the VM v6 version the inner Ethereum Virtual Machine core previously included in this library has been extracted to an own package @ethereumjs/evm.
It is still possible to access all EVM functionality through the evm property of the initialized vm object, e.g.:
vm.evm.runCode()
vm.evm.events.on('step', function (data) {
console.log(`Opcode: ${data.opcode.name}\tStack: ${data.stack}`)
})
Note that it’s now also possible to pass in an own or customized EVM instance by using the optional evm constructor option.
With VM v7 a previously needed EEI interface for EVM/VM communication is not needed any more and the API has been simplified, also see the respective EVM README section. Most of the EEI related logic is now either handled internally or more generic functionality being taken over by the @ethereumjs/statemanager package, with the EVM now taking in both an (optional) stateManager and blockchain argument for the constructor (which the VM passes over by default).
With VM v6 the previously included StateManager has been extracted to its own package @ethereumjs/statemanager. The StateManager package provides a unified state interface and it is now also possible to provide a modified or custom StateManager to the VM via the optional stateManager constructor option.
The VM is a thin orchestration layer that drives the EVM at the transaction and block level. Its core processing functions are free-standing (runX(vm, opts)), not methods:
vm.ts — the VM class: holds the evm, stateManager, blockchain, common and events, and merges paramsVM into Common.runBlock.ts — runBlock: block-level processing (pre-state setup, transaction loop via runTx, withdrawals, requests, rewards, post-state validation). See Internal Structure below for the step-by-step flow.runTx.ts — runTx: transaction-level rules (nonce/balance/intrinsic-gas checks, EIP-1559/4844/7702 handling, access-list warming), the call into vm.evm.runCall, refund/coinbase accounting and receipt generation (generateTxReceipt).buildBlock.ts — buildBlock / BlockBuilder: incremental block construction for block producers.consumeBal.ts — EIP-7928 block-level access list consumption.requests.ts — consensus-layer request (EIP-7685) extraction.bloom/ — logs-bloom computation.params.ts — paramsVM, merged into Common at construction.types.ts / constructors.ts — public types/option objects and the createVM factory.The VM is customized through createVM / VMOpts (src/types.ts:101); most of its behavior is delegated to injectable collaborators:
EVM — evm? (or evmOpts?): pass an EVM you configured (e.g. with custom opcodes/precompiles — see the EVM extension points). If omitted, the VM creates one.stateManager?: StateManagerInterface (src/types.ts:27): any @ethereumjs/statemanager implementation or your own.blockchain? (src/types.ts:31): supplies block-hash lookups for the BLOCKHASH/BLOBHASH family; defaults to a minimal mock.Common — common? (src/types.ts:23): chain/hardfork/EIP configuration, shared with the inner EVM.params?: ParamsDict: override paramsVM values.vm.events (beforeBlock, afterBlock, beforeTx, afterTx) and vm.evm.events (step, beforeMessage, …) for tracing and instrumentation.Beside the default Proof-of-Stake setup coming with the Common library default, the VM also support the execution of both Ethash/PoW and Clique/PoA blocks and transactions to allow to re-execute blocks from older hardforks or testnets.
For hardfork support see the Hardfork Support section from the underlying @ethereumjs/evm instance.
An explicit HF in the VM - which is then passed on to the inner EVM - can be set with:
// ./examples/runTx.ts#L1-L8
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createLegacyTx } from '@ethereumjs/tx'
import { createAccount, createAddressFromPrivateKey, createZeroAddress, hexToBytes } from '@ethereumjs/util'
import { createVM, runTx } from '@ethereumjs/vm'
const main = async () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai })
const vm = await createVM({ common })
For initializing a custom genesis state you can use the genesisState constructor option in the Blockchain and VM library in a similar way this had been done in the Common library before.
// ./examples/vmWithGenesisState.ts
import { Chain } from '@ethereumjs/common'
import { getGenesis } from '@ethereumjs/genesis'
import { createAddressFromString } from '@ethereumjs/util'
import { createVM } from '@ethereumjs/vm'
const main = async () => {
const genesisState = getGenesis(Chain.Mainnet)
const vm = await createVM()
await vm.stateManager.generateCanonicalGenesis!(genesisState)
const accountAddress = '0x000d836201318ec6899a67540690382780743280'
const account = await vm.stateManager.getAccount(createAddressFromString(accountAddress))
if (account === undefined) {
throw new Error('Account does not exist: failed to import genesis state')
}
console.log(
`This balance for account ${accountAddress} in this chain's genesis state is ${Number(
account?.balance,
)}`,
)
}
void main()
Genesis state can be configured to contain both EOAs as well as (system) contracts with initial storage values set.
It is possible to individually activate EIP support in the VM by instantiate the Common instance passed
with the respective EIPs, e.g.:
// ./examples/vmWithEIPs.ts
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createVM } from '@ethereumjs/vm'
const main = async () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Cancun, eips: [7702] })
const vm = await createVM({ common })
console.log(
`EIP 7702 is active in isolation on top of the Cancun HF - ${vm.common.isActivatedEIP(7702)}`,
)
}
void main()
For a list with supported EIPs see the @ethereumjs/evm documentation.
This library supports the blob transaction type introduced with EIP-4844. EIP-4844 comes with a dedicated opcode BLOBHASH and has added a new point evaluation precompile at address 0x0a.
Note: Usage of the point evaluation precompile needs a manual KZG library installation and global initialization, see KZG Setup for instructions.
This library support the execution of EIP-7702 EOA code transactions (see tx library for full documentation) with runTx() or the wrapping runBlock() execution methods, see this test setup for a more complete example setup on how to run code from an EOA.
This library supports blocks including EIP-7685 requests to the consensus layer.
Starting with v8.1.0 the VM supports EIP-2935 which stores the latest 8192 block hashes in the storage of a system contract.
Note that this EIP has no effect on the resolution of the BLOCKHASH opcode, which will be a separate activation taking place by the integration of EIP-7709 in a respective Verkle/Stateless hardfork.
This section is the canonical overview for experimental Amsterdam support: which library release maps to which spec snapshot, and where to read more. Amsterdam remains unstable — expect further 10.1.x releases as the spec and testnets evolve.
Release ↔ spec tracking
| Release | Summary | EST fixtures | Testnet |
|---|---|---|---|
v10.1.2 |
First experimental Amsterdam release: full 9-EIP Hardfork.Amsterdam bundle, BAL builder/validator APIs (7928), two-dimensional block gas (8037); passes v700 mixed EST slice. |
tests-bal@v7.1.0 | BAL devnet-7 |
Master currently tracks tests-glamsterdam-devnet@v7.2.1 for the mixed Amsterdam tree. EIP-2780 / EIP-8037: intrinsic regular gas is state-independent (txGas + recipient/value/log extras + calldata + create access + perAuthBaseGas); the calldata floor is anchored on TX_BASE + those recipient extras (execution-specs#3120). Under v7.2.0+, the floor also binds each tx’s block regular-gas contribution (max(pre_refund_regular, floor)). New-account state gas and 7702 ACCOUNT_WRITE / auth state are charged at top-frame access (ACCOUNT_WRITE counts toward receipt gas). Sender nonce is incremented before that prep layer (create-tx NEW_ACCOUNT OOG still bumps nonce). Create-tx NEW_ACCOUNT spill into gas_left is credited on REVERT so receipt gas can hit the calldata floor. Inner CREATE child OOG onto a balance-only target keeps the spilled NEW_ACCOUNT as regular gas (no leftover credit) and exceptional-halts the creating frame.
The Hardfork.Amsterdam bundle activates the following EIPs. Amsterdam test fixtures and execution-spec tests typically enable the full set together rather than individual EIPs in isolation.
| EIP | Summary | Documentation |
|---|---|---|
| 2780 | Intrinsic includes recipient/value extras; floor anchored on that base | EIP-8037 section (intrinsic vs runtime) |
| 7708 | ETH transfers and burns emit logs | EVM (below), receipts from runTx() / runBlock() |
| 7843 | SLOTNUM opcode + slotNumber header field |
@ethereumjs/block |
| 7778 | Block gas accounting without refund subtraction | EIP-7778 note (below) |
| 7928 | Block Level Access Lists | EIP-7928 section (below) |
| 7954 | Raised max contract / initcode size | @ethereumjs/evm |
| 7976 | Uniform calldata floor pricing | @ethereumjs/tx |
| 7981 | Access-list byte floor pricing | @ethereumjs/tx |
| 7997 | Deterministic CREATE2 factory predeploy | Catalog only — clients must not inject at the fork boundary |
| 8024 | DUPN, SWAPN, EXCHANGE stack opcodes |
@ethereumjs/evm |
| 8037 | Two-dimensional block gas + state-gas reservoir | EIP-8037 section (below) |
| 8038 | State-access gas; SSTORE access cost before implicit read | @ethereumjs/evm |
| 8282 | Builder deposit/exit request predeploys (v7 mined addresses) | runBlock() / accumulateRequests; addresses in packages/vm/src/params.ts |
Activation: new Common({ chain: Mainnet, hardfork: Hardfork.Amsterdam }). See Release ↔ spec tracking above for supported spec snapshots; behaviour may change on patch releases.
EIP-7928 adds a block-level access list (BAL) committed via blockAccessListHash in the block header. When EIP-7928 is active, the VM accumulates state accesses automatically during runBlock() / runTx() — no extra opt-in flag is required. See Release ↔ spec tracking above for the EST / testnet snapshot this release targets.
Activation: use Hardfork.Amsterdam (experimental).
Block builder flow (generate: true): execute the block, read RunBlockResult.blockLevelAccessList, and use the returned block from the afterBlock event — its header includes blockAccessListHash (set from bal.hash()).
// ./examples/runBlockBalGenerate.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createLegacyTx } from '@ethereumjs/tx'
import {
Account,
bytesToHex,
createAddressFromPrivateKey,
createZeroAddress,
hexToBytes,
} from '@ethereumjs/util'
import { createVM, runBlock } from '@ethereumjs/vm'
import type { AfterBlockEvent } from '@ethereumjs/vm'
const main = async () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Amsterdam })
const vm = await createVM({ common })
const senderKey = hexToBytes(`0x${'20'.repeat(32)}`)
const sender = createAddressFromPrivateKey(senderKey)
await vm.stateManager.putAccount(sender, new Account(0n, BigInt(1e18)))
const parentBlock = createBlock(
{ header: { number: 1n } },
{ common, skipConsensusFormatValidation: true },
)
const tx = createLegacyTx({
gasLimit: 21000n,
gasPrice: 10n,
value: 1n,
to: createZeroAddress(),
}).sign(senderKey)
const block = createBlock(
{
header: { number: 2n, gasLimit: 30_000_000n, baseFeePerGas: 1n },
transactions: [tx],
},
{
common,
skipConsensusFormatValidation: true,
calcDifficultyFromHeader: parentBlock.header,
},
)
let afterBlock: AfterBlockEvent | undefined
vm.events.once('afterBlock', (event) => {
afterBlock = event
})
const result = await runBlock(vm, {
block,
generate: true,
skipBlockValidation: true,
})
const bal = result.blockLevelAccessList!
console.log(`BAL accounts: ${bal.toJSON().length}`)
console.log(`blockAccessListHash: ${bytesToHex(afterBlock!.block.header.blockAccessListHash!)}`)
console.log(`hash matches result: ${bytesToHex(bal.hash())}`)
}
void main()
Block validator flow: pass the BAL from an execution payload via RunBlockOpts.blockAccessList (JSON, RLP bytes, or a BlockLevelAccessList instance). runBlock() validates structure and header hash before execution and checks equality against the generated list afterward.
// ./examples/runBlockBalValidate.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createLegacyTx } from '@ethereumjs/tx'
import {
Account,
bytesToHex,
createAddressFromPrivateKey,
createZeroAddress,
hexToBytes,
} from '@ethereumjs/util'
import { createVM, runBlock } from '@ethereumjs/vm'
import type { Block } from '@ethereumjs/block'
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Amsterdam })
const senderKey = hexToBytes(`0x${'20'.repeat(32)}`)
const sender = createAddressFromPrivateKey(senderKey)
async function fundSender(vm: Awaited<ReturnType<typeof createVM>>) {
await vm.stateManager.putAccount(sender, new Account(0n, BigInt(1e18)))
}
function createTransferBlock() {
const parentBlock = createBlock(
{ header: { number: 1n } },
{ common, skipConsensusFormatValidation: true },
)
const tx = createLegacyTx({
gasLimit: 21000n,
gasPrice: 10n,
value: 1n,
to: createZeroAddress(),
}).sign(senderKey)
return createBlock(
{
header: { number: 2n, gasLimit: 30_000_000n, baseFeePerGas: 1n },
transactions: [tx],
},
{
common,
skipConsensusFormatValidation: true,
calcDifficultyFromHeader: parentBlock.header,
},
)
}
const main = async () => {
const vm = await createVM({ common })
await fundSender(vm)
let sealedBlock: Block | undefined
vm.events.once('afterBlock', (event) => {
sealedBlock = event.block
})
const generated = await runBlock(vm, {
block: createTransferBlock(),
generate: true,
skipBlockValidation: true,
})
const balJson = generated.blockLevelAccessList!.toJSON()
console.log(`Generated BAL with ${balJson.length} account(s)`)
console.log(`blockAccessListHash: ${bytesToHex(sealedBlock!.header.blockAccessListHash!)}`)
const vm2 = await createVM({ common })
await fundSender(vm2)
await runBlock(vm2, {
block: sealedBlock!,
blockAccessList: balJson,
skipBlockValidation: true,
})
console.log('Provided blockAccessList validated successfully against execution')
}
void main()
Offline parsing / validation: see the @ethereumjs/util BAL module for BlockLevelAccessList, JSON/RLP helpers, and validation utilities.
Notes:
Hardfork.Amsterdam rather than activating EIP-7928 in isolation.buildBlock() does not yet populate blockAccessListHash automatically — use runBlock({ generate: true }) for now.See Release ↔ spec tracking above for the supported Amsterdam spec snapshot.
EIP-8037 splits block gas into two independent dimensions — regular and state — and introduces a per-transaction state-gas reservoir for state-touching operations. When active, runBlock() and runTx() handle this automatically; no extra opt-in is required.
Block-level gas used: instead of summing a single gasUsed, the block header field becomes max(block_regular_gas_used, block_state_gas_used). Each transaction contributes to both dimensions via RunTxResult.txRegularGas and RunTxResult.txStateGas (undefined when EIP-8037 is inactive).
Pre-execution checks: before running each tx, runBlock() verifies that the tx’s regular and state gas contributions fit within the remaining capacity of each dimension (see computeIntrinsicGasDimensions8037() in @ethereumjs/evm for the state-independent intrinsic split — no intrinsic state gas under v7). EIP-2780 recipient/value/log extras are part of getIntrinsicGas() and the calldata floor (self-transfers skip them). New-account state gas and 7702 ACCOUNT_WRITE / indicator state are charged during execution at the top frame, keyed on pre-state (prep OOG rolls back 7702 delegations). ACCOUNT_WRITE is taken from leftover regular gas and counted in receipt totalGasSpent. The sender nonce is incremented before that nested prep layer, so a create-tx NEW_ACCOUNT OOG still bumps nonce (no contract is created). On a create-tx REVERT, NEW_ACCOUNT spill into gas_left is credited back (refill_frame_state_gas); receipt totalGasSpent still floors to calldata minimum. Inner CREATE/CREATE2 charges new-account state gas unless the target already has nonce or code; a collision consumes the 63/64 grant as regular gas without spawning a child. A child exceptional halt onto a balance-only (already-alive) target keeps that charge as regular gas and exceptional-halts the creating frame (nonce bump reverted, BAL reads kept). CREATE new-account OOG is post-target (the created address is in the BAL); 7702 top-frame delegation OOG records the recipient and not the delegation target.
RunTxResult fields (EIP-8037 active):
| Field | Meaning |
|---|---|
txRegularGas |
Regular-dimension total for this tx (max(raw_regular, calldata_floor) per EIP-7623/EIP-7976) |
txStateGas |
State-dimension total (intrinsic state + execution state gas, net of create/selfdestruct refunds) |
blockGasSpent |
Amount counted toward block gas (see EIP-7778 below) |
totalGasSpent |
Amount actually paid by the sender (includes refund subtraction) |
State-gas reservoir: during execution the EVM maintains evm.stateGasReservoir, initialized from the tx’s state-gas budget. State-touching opcodes draw from the reservoir first; overflow spills into gas_left. The delta is reflected in txStateGas.
Dependency: EIP-8037 requires EIP-7825 (maxTransactionGasLimit) — both are active on Hardfork.Amsterdam.
See Release ↔ spec tracking above for the supported Amsterdam spec snapshot.
EIP-7778 changes how gas refunds affect block-level accounting. RunTxResult.totalGasSpent is what the sender pays (refunds subtracted). RunTxResult.blockGasSpent is what counts toward the block header’s gasUsed — under EIP-7778 this does not subtract tx-level refunds (blockGasSpent = max(totalGasSpent, floorCost)). Receipt cumulativeGasUsed still uses the pre-7778 refund semantics via a separate accumulator inside runBlock().
See Release ↔ spec tracking above for the supported Amsterdam spec snapshot.
EIP-7708 adds synthetic logs for native ETH transfers and balance burns. When active, value-bearing CALL/CREATE paths and certain SELFDESTRUCT/account-removal flows append logs from the system address (0xfff…fff) with Transfer(address,address,uint256) or Burn(address,uint256) topics. These appear in RunTxResult.receipt.logs like any other log — no VM API changes are needed beyond using Hardfork.Amsterdam. See examples/runTxTransferLogs.ts.
Our TypeScript VM emits events that support async listeners (using EventEmitter3).
You can subscribe to the following events:
beforeBlock: Emits a Block right before running it.afterBlock: Emits AfterBlockEvent right after running a block.beforeTx: Emits a Transaction right before running it.afterTx: Emits a AfterTxEvent right after running a transaction.Note, if subscribing to events with an async listener, specify the second parameter of your listener as a resolve function that must be called once your listener code has finished.
// ./examples/eventListener.ts#L10-L19
// Setup an event listener on the `afterTx` event
vm.events.on('afterTx', (event, resolve) => {
console.log('asynchronous listener to afterTx', bytesToHex(event.transaction.hash()))
// we need to call resolve() to avoid the event listener hanging
resolve?.()
})
vm.events.on('afterTx', (event) => {
console.log('synchronous listener to afterTx', bytesToHex(event.transaction.hash()))
})
Please note that there are additional EVM-specific events in the @ethereumjs/evm package.
You can perform asynchronous operations from within an event handler and prevent the VM to keep running until they finish.
In order to do that, your event handler has to accept two arguments. The first one will be the event object, and the second one a function. The VM won’t continue until you call this function.
If an exception is passed to that function, or thrown from within the handler or a function called by it, the exception will bubble into the VM and interrupt it, possibly corrupting its state. It’s strongly recommended not to do that.
If you want to perform synchronous operations, you don’t need to receive a function as the handler’s second argument, nor call it.
Note that if your event handler receives multiple arguments, the second one will be the continuation function, and it must be called.
If an exception is thrown from within the handler or a function called by it, the exception will bubble into the VM and interrupt it, possibly corrupting its state. It’s strongly recommended not to throw from within event handlers.
If you want to understand your VM runs we have added a hierarchically structured list of debug loggers for your convenience which can be activated in arbitrary combinations. We also use these loggers internally for development and testing. These loggers use the debug library and can be activated on the CL with DEBUG=ethjs,[Logger Selection] node [Your Script to Run].js and produce output like the following:

The following loggers are currently available:
| Logger | Description |
|---|---|
vm:block |
Block operations (run txs, generating receipts, block rewards,…) |
vm:tx |
Transaction operations (account updates, checkpointing,…) |
vm:tx:gas |
Transaction gas logger |
vm:state |
StateManager logger |
Note that there are additional EVM-specific loggers in the @ethereumjs/evm package.
Here are some examples for useful logger combinations.
Run one specific logger:
DEBUG=ethjs,vm:tx tsx test.ts
Run all loggers currently available:
DEBUG=ethjs,vm:*,vm:*:* tsx test.ts
Run only the gas loggers:
DEBUG=ethjs,vm:*:gas tsx test.ts
Excluding the state logger:
DEBUG=ethjs,vm:*,vm:*:*,-vm:state tsx test.ts
Run some specific loggers including a logger specifically logging the SSTORE executions from the VM (this is from the screenshot above):
DEBUG=ethjs,vm:tx,vm:evm,vm:ops:sstore,vm:*:gas tsx test.ts
The VM processes state changes at several levels:
runBlock: Processes a single block.
runTx.runTx: Processes a single transaction.
vm.evm.runCall (or specific logic for contract creation).vm.evm.runCall (within @ethereumjs/evm): Executes the EVM code for a transaction (message call or contract creation).
Note: The process of iterating through the blockchain (block by block) is typically managed by components outside the core VM package, such as @ethereumjs/blockchain or a full client implementation, which then utilize the VM’s runBlock method.
Developer documentation - currently mainly with information on testing and debugging - can be found here.
The EthereumJS GitHub organization and its repositories are managed by members of the former Ethereum Foundation JavaScript team and the broader Ethereum community. If you want to join for work or carry out improvements on the libraries see the developer docs for an overview of current standards and tools and review our code of conduct.