What is ethereumjs-vm?
The ethereumjs-vm package is a JavaScript implementation of the Ethereum Virtual Machine (EVM). It allows developers to execute smart contracts, run Ethereum transactions, and simulate the Ethereum blockchain environment. This package is useful for testing, development, and research purposes.
What are ethereumjs-vm's main functionalities?
Execute Smart Contracts
This feature allows you to execute smart contracts within the Ethereum Virtual Machine. The code sample demonstrates how to set up the VM, create an account, and run a simple contract code.
const { VM } = require('ethereumjs-vm');
const { Account, Address } = require('ethereumjs-util');
const { default: Common } = require('@ethereumjs/common');
const common = new Common({ chain: 'mainnet' });
const vm = new VM({ common });
const runCode = async () => {
const code = '0x6001600101600055'; // Simple contract code
const address = Address.fromString('0x1234567890123456789012345678901234567890');
const account = new Account({ balance: '0x10000000000000' });
await vm.stateManager.putAccount(address, account);
const result = await vm.runCode({
code: Buffer.from(code, 'hex'),
gasLimit: Buffer.from('ffffffff', 'hex'),
address,
});
console.log(result);
};
runCode();
Run Ethereum Transactions
This feature allows you to run Ethereum transactions within the VM. The code sample demonstrates how to create a transaction and execute it using the VM.
const { VM } = require('ethereumjs-vm');
const { Transaction } = require('ethereumjs-tx');
const { default: Common } = require('@ethereumjs/common');
const common = new Common({ chain: 'mainnet' });
const vm = new VM({ common });
const runTransaction = async () => {
const txData = {
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x',
};
const tx = new Transaction(txData, { common });
const result = await vm.runTx({ tx });
console.log(result);
};
runTransaction();
Simulate Blockchain Environment
This feature allows you to simulate a blockchain environment by running blocks within the VM. The code sample demonstrates how to create a block and execute it using the VM.
const { VM } = require('ethereumjs-vm');
const { Block } = require('@ethereumjs/block');
const { default: Common } = require('@ethereumjs/common');
const common = new Common({ chain: 'mainnet' });
const vm = new VM({ common });
const simulateBlockchain = async () => {
const block = Block.fromBlockData({}, { common });
const result = await vm.runBlock({ block, generate: true, skipBlockValidation: true });
console.log(result);
};
simulateBlockchain();
Other packages similar to ethereumjs-vm
ganache-cli
Ganache CLI is a fast and customizable blockchain emulator that allows you to run a personal Ethereum blockchain. It is often used for development and testing purposes. Compared to ethereumjs-vm, Ganache CLI provides a more user-friendly interface and additional features like snapshotting and forking.
truffle
Truffle is a development framework for Ethereum that includes a suite of tools for smart contract development, testing, and deployment. It integrates with Ganache for local blockchain simulation. While ethereumjs-vm focuses on the EVM execution, Truffle provides a more comprehensive development environment.
hardhat
Hardhat is a development environment for Ethereum that helps developers manage and automate the recurring tasks inherent to building smart contracts and DApps. It includes a local Ethereum network for testing. Hardhat offers more advanced features like debugging and stack traces compared to ethereumjs-vm.
SYNOPSIS


Implements Ethereum's VM in Javascript.
Fork Support
The VM currently supports the following hardfork rules:
Byzantium
Constantinople
Petersburg
(default)Istanbul
MuirGlacier
(only mainnet
and ropsten
)
If you are still looking for a Spurious Dragon compatible version of this library install the latest of the 2.2.x
series (see Changelog).
MuirGlacier Hardfork Support
An Ethereum test suite compliant MuirGlacier
HF implementation is available
since the v4.1.3
VM release. You can activate a MuirGlacier
VM by using the
muirGlacier
hardfork
option flag.
Note: The original v4.1.2
release contains a critical bug preventing the
MuirGlacier
VM to work properly and there is the need to update.
Istanbul Harfork Support
An Ethereum test suite compliant Istanbul
HF implementation is available
since the v4.1.1
VM release. You can activate an Istanbul
VM by using the
istanbul
hardfork
option flag.
Supported Istanbul
EIPs:
INSTALL
npm install ethereumjs-vm
USAGE
const BN = require('bn.js')
var VM = require('ethereumjs-vm').default
const vm = new VM()
const STOP = '00'
const ADD = '01'
const PUSH1 = '60'
const code = [PUSH1, '03', PUSH1, '05', ADD, STOP]
vm.on('step', function(data) {
console.log(`Opcode: ${data.opcode.name}\tStack: ${data.stack}`)
})
vm.runCode({
code: Buffer.from(code.join(''), 'hex'),
gasLimit: new BN(0xffff),
})
.then(results => {
console.log('Returned : ' + results.returnValue.toString('hex'))
console.log('gasUsed : ' + results.gasUsed.toString())
})
.catch(err => console.log('Error : ' + err))
Example
This projects contain the following examples:
- ./examples/run-blockchain: Loads tests data, including accounts and blocks, and runs all of them in the VM.
- ./examples/run-code-browser: Show how to use this library in a browser.
- ./examples/run-solidity-contract: Compiles a Solidity contract, and calls constant and non-constant functions.
- ./examples/run-transactions-complete: Runs a contract-deployment transaction and then calls one of its functions.
- ./examples/decode-opcodes: Decodes a binary EVM program into its opcodes.
All of the examples have their own README.md
explaining how to run them.
BROWSER
To build the VM for standalone use in the browser, see: Running the VM in a browser.
API
VM
For documentation on VM
instantiation, exposed API and emitted events
see generated API docs.
StateManger
The API for the StateManager
is currently in Beta
, separate documentation can be found here, see also release notes from the v2.5.0
VM release for details on the StateManager
rewrite.
Internal Structure
The VM processes state changes at many levels.
- runBlockchain
- for every block, runBlock
- runBlock
- for every tx, runTx
- pay miner and uncles
- runTx
- check sender balance
- check sender nonce
- runCall
- transfer gas charges
- runCall
- checkpoint state
- transfer value
- load code
- runCode
- materialize created contracts
- revert or commit checkpoint
- runCode
- iterate over code
- run op codes
- track gas usage
- OpFns
- run individual op code
- modify stack
- modify memory
- calculate fee
The opFns for CREATE
, CALL
, and CALLCODE
call back up to runCall
.
VM's tracing events
You can subscribe to the following events of the VM:
beforeBlock
: Emits a Block
right before running it.afterBlock
: Emits RunBlockResult
right after running a block.beforeTx
: Emits a Transaction
right before running it.afterTx
: Emits a RunTxResult
right after running a transaction.beforeMessage
: Emits a Message
right after running it.afterMessage
: Emits an EVMResult
right after running a message.step
: Emits an InterpreterStep
right before running an EVM step.newContract
: Emits a NewContractEvent
right before creating a contract. This event contains the deployment code, not the deployed code, as the creation message may not return such a code.
Asynchronous event handlers
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.
Synchronous event handlers
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 withing 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 withing
event handlers.
DEVELOPMENT
Developer documentation - currently mainly with information on testing and debugging - can be found here.
EthereumJS
See our organizational documentation for an introduction to EthereumJS
as well as information on current standards and best practices.
If you want to join for work or do improvements on the libraries have a look at our contribution guidelines.
LICENSE
MPL-2.0