### Install and Start EthereumJS Client Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Install the EthereumJS client using npm or from source and start it. Use CLI parameters to specify network configurations. ```shell npm installation hereumjs # Source installation ``` ```shell npm run client:start ``` ```shell # npm installation hereumjs --network=sepolia # Source installation ``` ```shell npm run client:start -- --network=sepolia ``` -------------------------------- ### Install EthereumJS Monorepo Packages Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/mpt/examples/merkle_patricia_trees/README.md Clone the repository and install necessary packages using npm. Navigate to the 'trie' package directory to run examples. ```bash git clone git@github.com:ethereumjs/ethereumjs-monorepo.git cd ethereumjs-monorepo/ npm install cd packages/trie ``` -------------------------------- ### Start Manual Ethereumjs Client Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/EOF.md Manually start the ethereumjs client for a custom network setup. Ensure the DATADIR is clean and properly structured. Requires specific geth genesis configuration. ```bash npm run client:start -- --datadir data/eof/ethereumjs --gethGenesis test/sim/configs/geth-genesis.json --rpc --rpcEngine --rpcEngineAuth false ``` -------------------------------- ### Setup EthereumJS with Lodestar Quickstart Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Use this command to initialize the EthereumJS client when running with the Lodestar quick-start repository. It specifies the network, data directory, and the execution client. ```shell ./setup.sh --network sepolia --dataDir sepolia-data --elClient ethereumjs ``` -------------------------------- ### Benchmark Results Summary Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/test/tester/scripts/benchmarkBAL.md This is an example of the output generated by the benchmark script, showing the setup, processing, and validation times for both `runBlock()` and `consumeBal()` methods, along with the total process speedup. ```text Summary runBlock setup=1217.30ms process=471664.39ms validate=634.67ms total=473516.36ms consumeBal setup=463.41ms process=28967.96ms validate=439.14ms total=29870.50ms total process speedup=16.28x ``` -------------------------------- ### Start Geth Instance for Debugging Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/examples/local-debugging.md Start a Geth instance with optional sync mode and verbosity settings for debugging purposes. ```shell geth [--syncmode=full] [--verbosity=5] ``` -------------------------------- ### Start Manual Lodestar Client (Docker) Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/EOF.md Manually start the lodestar client using Docker for a custom network setup. Requires the genesis hash and timestamp from the ethereumjs client. For Mac users, use the lodestar binary directly. ```bash docker run --rm --name beacon --network host chainsafe/lodestar:latest dev --dataDir data/eof/lodestar --genesisValidators 8 --startValidators 0..7 --enr.ip 127.0.0.1 --genesisEth1Hash 0x3feda37f61eaa3d50deaa39cf04e352af0b54c521b0f16d26f826b54edeef756 --params.ALTAIR_FORK_EPOCH 0 --params.BELLATRIX_FORK_EPOCH 0 --params.TERMINAL_TOTAL_DIFFICULTY 0x01 --genesisTime 1664538222 ``` ```bash lodestar dev --dataDir data/eof/lodestar --genesisValidators 8 --startValidators 0..7 --enr.ip 127.0.0.1 --genesisEth1Hash $GENESIS_HASH --params.ALTAIR_FORK_EPOCH 0 --params.BELLATRIX_FORK_EPOCH 0 --params.TERMINAL_TOTAL_DIFFICULTY 0x01 --genesisTime 1664538222 ``` -------------------------------- ### Start Peer 2 in Multi-Peer Setup Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/EOF.md Initiates the second peer after the first peer has started and the countdown to genesis is visible. Ensure lodestar is stable. The default Docker image used is `chainsafe/lodestar:latest` if `LODE_BINARY` is omitted. ```bash NETWORK=eof DATADIR=/data/eof LODE_BINARY=lodestar MULTIPEER=peer2 test/sim/./single-run.sh ``` -------------------------------- ### Initialize KZG for EIP-4844 Blob Transactions Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/README.md Manually install and initialize KZG using the micro-eth-signer and trusted-setups packages. This setup is required for creating EIP-4844 blob transactions and other KZG-related proof functionalities within the `common` instance. ```typescript // ./examples/initKzg.ts import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { trustedSetup } from '@paulmillr/trusted-setups/fast-peerdas.js' import { KZG as microEthKZG } from 'micro-eth-signer/kzg.js' const main = async () => { const kzg = new microEthKZG(trustedSetup) // Instantiate `common` const common = new Common({ chain: Mainnet, hardfork: Hardfork.Cancun, customCrypto: { kzg }, }) console.log(common.customCrypto.kzg) // should output the KZG API as an object } void main() ``` -------------------------------- ### Install Dependencies Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/README.md Install all project dependencies using npm after cloning the repository. ```sh npm install ``` -------------------------------- ### setup Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/blockchain/docs/classes/EthashConsensus.md Sets up the consensus mechanism with provided options. ```APIDOC ## setup(__namedParameters) ### Description Set up consensus mechanism. ### Parameters #### Parameters - ** __namedParameters** (`ConsensusOptions`) - Options for setting up the consensus mechanism. ### Returns - `Promise` - A promise that resolves when the setup is complete. ``` -------------------------------- ### Changelog Preparation Prompt Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/DEVELOPER.md An example prompt to guide AI in preparing changelog updates for package releases. It specifies release details, commit history, and filtering criteria for relevant changes. ```markdown I want to do a new release round for all active packages listed in @README.md. Version bump has already been done, see an exemplary [ REFERENCE package.json FILE ] file, release is target for today. Last release round has been done on [ ENTER DATE IN FORMAT: April 29 2025 ] along commit [ ENTER COMMIT HASH, e.g.: 9e461f54312bf20c710b43ab73f7d3ad753f8765 ]. An exemplary CHANGELOG.md file is [ REFERENCE e.g. block CHANGELOG.md file ]. Can you please add new sections in the CHANGELOG files and add one-line summaries for the user-facing changes? For this please go for the commits since last release, one commit represents one PR due to our (squash) merge policy. You can leave out PRs only updating documentation, code in the examples folder or tests. Also tooling infrastructure (linting,...) and CI updating PRs can be left out. New support for new and deprecation for older Node.js as well as TypeScript versions should be added. Version updates for external dependencies - so not from within the monorepo - should be added as well. Here is an example for the format of a change/PR entry: - New default hardfork: `Shanghai` -> `Cancun`, see PR [#3566](https://github.com/ethereumjs/ethereumjs-monorepo/pull/3566) For the CHANGELOG files you have not added lines in this step please nevertheless add a CHANGELOG entry (we do releases for all active packages no matter the changeset) and enter the following sentence: Maintenance release, no active changes. ``` -------------------------------- ### Install EthereumJS Client via NPM Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Installs the latest version of the EthereumJS client globally using npm. Ensure Node.js is installed. ```shell npm install -g @ethereumjs/client ``` -------------------------------- ### Run EIP-8024 Stack Opcodes Example Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/evm/README.md Command to execute the TypeScript example demonstrating DUPN, SWAPN, and EXCHANGE opcodes. Ensure you are in the 'packages/evm' directory when running this command. ```shell npx tsx examples/opcodes/0xe6-e8-eip8024-stack-opcodes.ts ``` -------------------------------- ### Install @ethereumjs/rlp Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/rlp/README.md Install the latest version of the @ethereumjs/rlp package using npm. Use the -g flag for global installation to access the CLI. ```shell npm install @ethereumjs/rlp ``` -------------------------------- ### Command to Run RPC Mainnet Block Example Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/README.md This command shows how to execute the provided TypeScript example for running a mainnet block using an RPC provider. Replace `` and `` with your specific values. ```bash npx tsx examples/runBlockWithRPC.ts ``` -------------------------------- ### Install EthereumJS VM Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/README.md Install the latest version of the EthereumJS VM package using npm. ```shell npm install @ethereumjs/vm ``` -------------------------------- ### Install @ethereumjs/statemanager Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/statemanager/README.md Install the latest version of the StateManager package using npm. ```shell npm install @ethereumjs/statemanager ``` -------------------------------- ### Install @ethereumjs/util Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/util/README.md Install the latest version of the @ethereumjs/util package using npm. ```shell npm install @ethereumjs/util ``` -------------------------------- ### Install @ethereumjs/mpt Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/mpt/README.md Install the latest version of the @ethereumjs/mpt package using npm. ```shell npm install @ethereumjs/mpt ``` -------------------------------- ### Install @ethereumjs/evm Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/evm/README.md Install the latest version of the @ethereumjs/evm package using npm. ```shell npm install @ethereumjs/evm ``` -------------------------------- ### Install @ethereumjs/e2store Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/e2store/README.md Install the latest version of the @ethereumjs/e2store package using npm. ```shell npm install @ethereumjs/e2store ``` -------------------------------- ### Start Peer 1 in Multi-Peer Setup Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/EOF.md Initiates the first peer in a multi-peer test environment. Ensure lodestar is stable. The default Docker image used is `chainsafe/lodestar:latest` if `LODE_BINARY` is omitted. ```bash NETWORK=eof DATADIR=/data/eof LODE_BINARY=lodestar MULTIPEER=peer1 test/sim/./single-run.sh ``` -------------------------------- ### Start Second EthereumJS Client with Bootnode Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/examples/local-debugging.md Start a second EthereumJS client, connecting it to a previously started client using its enode address. Ensure to replace '[DEV1_NODE_ID]' with the actual node ID and use '127.0.0.1' for the IP address. ```shell DEBUG=ethjs,devp2p:* npm run client:start:dev2 -- --bootnodes=enode://[DEV1_NODE_ID]@127.0.0.1:30303 ``` -------------------------------- ### Install @ethereumjs/common Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/common/README.md Install the latest version of the @ethereumjs/common package using npm. ```shell npm install @ethereumjs/common ``` -------------------------------- ### Install @ethereumjs/block Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/block/README.md Install the latest version of the @ethereumjs/block package using npm. ```shell npm install @ethereumjs/block ``` -------------------------------- ### Install @ethereumjs/ethash Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/ethash/README.md Use npm to install the latest version of the @ethereumjs/ethash library. ```shell npm install @ethereumjs/ethash ``` -------------------------------- ### Start EthereumJS Client for Debugging Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/examples/local-debugging.md Use this script to start a first EthereumJS client for debugging. It listens on the default port and uses the default data directory. Set DEBUG environment variable for detailed logs. ```shell DEBUG=ethjs,devp2p:* npm run client:start:dev1 ``` ```shell DEBUG=ethjs,devp2p:* npm run client:start:dev1 -- --datadir=datadir-dev1 ``` -------------------------------- ### Install @ethereumjs/genesis Package Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/genesis/README.md Use npm to install the @ethereumjs/genesis package. This command is typically run in your project's terminal. ```shell npm i @ethereumjs/genesis ``` -------------------------------- ### JSON-RPC Response Example Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Example of a successful JSON-RPC response for the `web3_clientVersion` method. ```json { "id": "1", "jsonrpc": "2.0", "result": "EthereumJS/0.0.5/darwin/node12.15.0" } ``` -------------------------------- ### Start Development Network (PoA) Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Start a local PoA clique network for development. This command prefunds an account and mines blocks at 10-second intervals. It is recommended to pair with --rpc for a full development environment. ```shell ethereumjs --dev=poa --rpc ``` -------------------------------- ### Connect Geth to EthereumJS Instance Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/examples/local-debugging.md Connect a Geth client to a running EthereumJS instance. You will need the enode address from the EthereumJS client started with `client:start:dev1`. ```shell geth --maxpeers=1 --bootnodes=enode://[DEV1_NODE_ID]@127.0.0.1:30303 ``` -------------------------------- ### Install Browser Dependencies for Vitest/Playwright Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/DEVELOPER.md Command to install Chromium browser dependencies required for running browser tests with Vitest and Playwright. This is a one-time setup. ```sh npm run install-browser-deps ``` -------------------------------- ### REPL Command Example: Get Block by Number Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Example of using the REPL to fetch a block by its number using the .eth_getBlockByNumber command. The second argument 'true' indicates that transaction details should be included. ```shell EthJS > .eth_getBlockByNumber ["latest", true] ``` -------------------------------- ### Server Constructor Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/devp2p/docs/classes/Server.md Initializes a new Server instance. It requires a DPT instance, a private key, and optional server options. ```APIDOC ## Server Constructor ### Description Initializes a new Server instance. ### Parameters #### Parameters - **dpt** (DPT) - The DPT instance to associate with this server. - **privateKey** (Uint8Array) - The private key for the server. - **options** (DPTServerOptions) - Optional configuration options for the server. ``` -------------------------------- ### Display EthereumJS Client Help Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Run the EthereumJS client with the --help flag to view all available client options. ```shell ethereumjs --help ``` -------------------------------- ### Start External Geth Client for Simulation Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/snapsync.md Initiates an external Geth client for simulation purposes. Ensure the ethereumjs-monorepo is built and prerequisites are met. This command sets up the network and client parameters. ```bash NETWORK=mainnet NETWORKID=1337903 ELCLIENT=geth EXTRA_CL_PARAMS="--params.CAPELLA_FORK_EPOCH 0" DATADIR=/usr/app/ethereumjs/packages/client/data test/sim/single-run.sh ``` -------------------------------- ### Instantiate Fee Market EIP-1559 Transaction Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/README.md Example of how to instantiate a Fee Market EIP-1559 transaction. This is the recommended transaction type starting with the London hardfork. ```typescript // ./examples/londonTx.ts import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import type { FeeMarketEIP1559TxData } from '@ethereumjs/tx' import { createFeeMarket1559Tx } from '@ethereumjs/tx' import { bytesToHex } from '@ethereumjs/util' const common = new Common({ chain: Mainnet, hardfork: Hardfork.London }) const txData: FeeMarketEIP1559TxData = { data: '0x1a8451e600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', gasLimit: '0x02625a00', maxPriorityFeePerGas: '0x01', maxFeePerGas: '0xff', nonce: '0x00', to: '0xcccccccccccccccccccccccccccccccccccccccc', value: '0x0186a0', v: '0x01', r: '0xafb6e247b1c490e284053c87ab5f6b59e219d51f743f7a4d83e400782bc7e4b9', s: '0x479a268e0e0acd4de3f1e28e4fac2a6b32a4195e8dfa9d19147abe8807aa6f64', chainId: '0x01', accessList: [], type: '0x02', } const tx = createFeeMarket1559Tx(txData, { common }) console.log(bytesToHex(tx.hash())) // 0x6f9ef69ccb1de1aea64e511efd6542541008ced321887937c95b03779358ec8a ``` -------------------------------- ### Get Hashed Message to Sign Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/docs/classes/LegacyTx.md Obtains the hashed serialized unsigned transaction payload. This hash is typically used for signing the transaction, for example, when interacting with hardware wallets. ```typescript import { LegacyTx } from "@ethereumjs/tx"; // Assuming tx is an instance of LegacyTx const hashedMessage = tx.getHashedMessageToSign(); console.log(hashedMessage); ``` -------------------------------- ### Get Ethereumjs Genesis Hash Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/EOF.md Retrieve the genesis block hash from a running ethereumjs client using curl and jq. This hash is required for starting the lodestar client. ```bash curl --location --request POST 'http://localhost:8545' --header 'Content-Type: application/json' --data-raw '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": [ "0x0", true ], "id": 1 }' 2>/dev/null | jq ".result.hash" ``` -------------------------------- ### Get Mainnet Genesis State Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/genesis/README.md Import and use the getGenesis function with Chain.Mainnet to retrieve the genesis state for the Ethereum main network. The example logs the balance of a specific account. ```typescript // ./examples/simple.ts import { Chain } from '@ethereumjs/common' // or directly use chain ID import { getGenesis } from '@ethereumjs/genesis' const mainnetGenesis = getGenesis(Chain.Mainnet) console.log( `This balance for account 0x000d836201318ec6899a67540690382780743280 in this chain's genesis state is ${parseInt( mainnetGenesis!['0x000d836201318ec6899a67540690382780743280'] as string, )}"`, ) ``` -------------------------------- ### Instantiate and Use RLPx Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/devp2p/README.md Instantiate an RLPx object with a common instance and private key. This example demonstrates setting up RLPx with specific capabilities and logging its active status. ```typescript import { Common, Mainnet } from '@ethereumjs/common' import { ETH, RLPx } from '@ethereumjs/devp2p' import { hexToBytes } from '@ethereumjs/util' const main = async () => { const common = new Common({ chain: Mainnet }) const PRIVATE_KEY = hexToBytes( '0xed6df2d4b7e82d105538e4a1279925a16a84e772243e80a561e1b201f2e78220', ) const rlpx = new RLPx(PRIVATE_KEY, { maxPeers: 25, capabilities: [ETH.eth65, ETH.eth64], common, }) console.log(`RLPx is active - ${rlpx._isAlive()}`) rlpx.destroy() } void main() ``` -------------------------------- ### Get and Parse E2HS Block Index Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/e2store/README.md Use getBlockIndex to retrieve the block index information from an E2HS file, then use readBlockIndex to parse the starting number and offsets of the blocks. ```typescript // ./examples/e2hs.ts#L18-L28 const blockIndex = getBlockIndex(e2hsFile) console.log('blockIndex', { type: blockIndex.type, count: blockIndex.count, recordStart: blockIndex.recordStart, data: blockIndex.data.length + ' bytes', }) const { startingNumber, offsets } = readBlockIndex(blockIndex.data, blockIndex.count) console.log('startingNumber', startingNumber) console.log('offsets', offsets.length) ``` -------------------------------- ### Instantiate and Use Blockchain Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/blockchain/README.md Example demonstrating how to instantiate a Blockchain object, add blocks, and iterate through them. Validation is skipped for simplicity. Ensure to consult @ethereumjs/block for block creation details. ```typescript // ./examples/simple.ts import { createBlock } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { bytesToHex } from '@ethereumjs/util' const main = async () => { const common = new Common({ chain: Mainnet, hardfork: Hardfork.London }) // Use the safe static constructor which awaits the init method const blockchain = await createBlockchain({ validateBlocks: false, // Skipping validation so we can make a simple chain without having to provide complete blocks validateConsensus: false, common, }) // We use minimal data to provide a sequence of blocks (increasing number, difficulty, and then setting parent hash to previous block) const block = createBlock( { header: { number: 1n, parentHash: blockchain.genesisBlock.hash(), difficulty: blockchain.genesisBlock.header.difficulty + 1n, }, }, { common, setHardfork: true }, ) const block2 = createBlock( { header: { number: 2n, parentHash: block.header.hash(), difficulty: block.header.difficulty + 1n, }, }, { common, setHardfork: true }, ) // See @ethereumjs/block for more details on how to create a block await blockchain.putBlock(block) await blockchain.putBlock(block2) // We iterate over the blocks in the chain to the current head (block 2) await blockchain.iterator('i', (block) => { const blockNumber = block.header.number.toString() const blockHash = bytesToHex(block.hash()) console.log(`Block ${blockNumber}: ${blockHash}`) }) // Block 1: 0xa1a061528d74ba81f560e1ebc4f29d6b58171fc13b72b876cdffe6e43b01bdc5 // Block 2: 0x5583be91cf9fb14f5dbeb03ad56e8cef19d1728f267c35a25ba5a355a528f602 } void main() ``` -------------------------------- ### Run a Transaction with EthereumJS VM Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/README.md Example of running a simple ETH transfer transaction using the EthereumJS VM. Ensure necessary imports and setup for common, state, and transaction creation. ```typescript // ./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() ``` -------------------------------- ### Run MODEXP Precompile with Different Hardforks Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/evm/README.md Example for the MODEXP precompile (address 0x05), demonstrating how to construct input data for the calculation 2^3 mod 5. It shows how to run the precompile with different hardforks (default and Cancun). ```typescript // ./examples/precompiles/05-modexp.ts import { Hardfork } from '@ethereumjs/common' import { runPrecompile } from './util.ts' const main = async () => { // MODEXP precompile (address 0x05) // Calculate: 2^3 mod 5 = 8 mod 5 = 3 // // Input format: // - First 32 bytes: base length (0x01 = 1 byte) // - Next 32 bytes: exponent length (0x01 = 1 byte) // - Next 32 bytes: modulus length (0x01 = 1 byte) // - Next 1 byte: base value (0x02 = 2) // - Next 1 byte: exponent value (0x03 = 3) // - Next 1 byte: modulus value (0x05 = 5) const baseLen = '0000000000000000000000000000000000000000000000000000000000000001' // 1 byte const expLen = '0000000000000000000000000000000000000000000000000000000000000001' // 1 byte const modLen = '0000000000000000000000000000000000000000000000000000000000000001' // 1 byte const base = '02' // 2 const exponent = '03' // 3 const modulus = '05' // 5 const data = `0x${baseLen}${expLen}${modLen}${base}${exponent}${modulus}` await runPrecompile('MODEXP', '0x05', data) await runPrecompile('MODEXP', '0x05', data, Hardfork.Cancun) } void main() ``` -------------------------------- ### Initialize VM with Shanghai Hardfork Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/README.md Sets up a new VM instance configured for the Shanghai hardfork using the Common library. This is useful for executing transactions within a specific hardfork context. ```typescript 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 }) ``` -------------------------------- ### Get Raw Message to Sign for Blob4844Tx Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/docs/classes/Blob4844Tx.md Retrieves the raw serialized unsigned transaction payload, which can be used for signing, for example, with a hardware wallet. This is the direct message to be signed, unlike its hashed counterpart. Implements the TransactionInterface. ```javascript const serializedMessage = tx.getMessageToSign() // use this for the HW wallet input ``` -------------------------------- ### Run Beaconsync Simulation with Geth Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/beaconsync.md Initiates the Beaconsync simulation using Geth as the execution client on the mainnet configuration. Ensure all prerequisites are met before execution. ```bash BEACON_SYNC=true NETWORK=mainnet NETWORKID=1337903 ELCLIENT=geth npx vitest run test/sim/beaconsync.spec.ts ``` -------------------------------- ### Browser Wallet Creation Example Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/wallet/examples/browser.html Use this snippet to create a wallet instance from a public key in a browser environment. Ensure you have imported the necessary modules from '@ethereumjs/wallet' and '@ethereumjs/util'. ```javascript import { Wallet } from '@ethereumjs/wallet' import { hexToBytes, bytesToHex } from '@ethereumjs/util' const publicKey = '0x5d4392f450262b276652c1fc037606abac500f3160830ce9df53aa70d95ce7cfb8b06010b2f3691c78c65c21eb4cf3dfdbfc0745d89b664ee10435bb3a0f906c' const wallet = Wallet.fromPublicKey(hexToBytes(publicKey)) console.log(bytesToHex(wallet.getAddress())) ``` -------------------------------- ### Run EIP-4844 Spec Tests with Vitest (Steps 1 & 3) Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/4844-devnet.md Command to execute EIP-4844 specification tests using Vitest. This command automatically starts the necessary nodes and runs the tests against them. It combines the devnet setup with the spec tests. ```bash LODE_IMAGE=g11tech/lodestar:36-7b0e9f DATADIR=path/to/your/data/directory npx vitest test/sim/sharding.spec.ts ``` -------------------------------- ### Run Benchmarks Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/DEVELOPER.md Execute the benchmarks with 'mainnetBlocks'. You can specify the number of samples to run by appending a colon and a number. ```bash npm run benchmarks -- mainnetBlocks ``` ```bash npm run benchmarks -- mainnetBlocks:10 ``` -------------------------------- ### Delete Key-Value Pair from Trie Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/mpt/examples/merkle_patricia_trees/README.md Demonstrates deleting a key-value pair from a Merkle Patricia Trie using the 'del' method after performing put and get operations. This example shows how deleting the last entry returns the trie to its initial empty state. ```jsx async function test() { const key = utf8ToBytes('testKey') const value = utf8ToBytes('testValue') await trie.put(key, value) // We update (using "put") the trie with the key-value pair "testKey": "testValue" const valuePre = await trie.get(key) // We retrieve (using "get") the value at key "testKey" console.log('Value (String): ', bytesToUtf8(valuePre)) // We retrieve our value console.log('Updated trie root:', bytesToHex(trie.root())) // The new trie root await trie.del(key) const valuePost = await trie.get(key) // We try to retrieve the value at (deleted) key "testKey" console.log('Value at key "testKey": ', valuePost) // Key not found. Value is therefore null. console.log('Trie root after deletion:', bytesToHex(trie.root())) // Our trie root is back to its initial value } test() // RESULT Empty trie root: 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421 Value (String): testValue Updated trie root: 0x8e8143672133dd5ab00dfc4b011460ea2a7b00d910dc4278942ae9105cb62074 Value at key "testKey": null Trie root after deletion: 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421 ``` -------------------------------- ### Run REPL with Custom Genesis Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Start the EthereumJS client REPL and pass a custom genesis file using the --gethGenesis flag. ```shell npm run repl -- --gethGenesis /data/genesis.json ``` -------------------------------- ### createVM() Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/docs/functions/createVM.md Asynchronously creates and initializes a VM engine instance. ```APIDOC ## createVM() ### Description Asynchronously creates and initializes a VM engine instance. ### Method N/A (This is a function constructor) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```json { "opts": { "exampleOption": "value" } } ``` ### Response #### Success Response (Promise) - **VM** (object) - An initialized VM instance. #### Response Example ```json { "vmInstance": "[VM Object]" } ``` ``` -------------------------------- ### Sign Legacy and EIP-1559 Transactions with Ledger Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/README.md Example demonstrating how to sign both legacy and EIP-1559 transactions using a Ledger hardware wallet. It covers setting up the transport, creating transaction data, obtaining the message to sign, and adding the signature back to the transaction object. Ensure you have `@ledgerhq/hw-app-eth` and `@ledgerhq/hw-transport-node-hid` installed. ```typescript // examples/ledgerSigner.mts import { Common, Sepolia } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { type FeeMarketEIP1559TxData, type LegacyTxData, createFeeMarket1559Tx, createLegacyTx, } from '@ethereumjs/tx' import { bytesToHex } from '@ethereumjs/util' import Eth from '@ledgerhq/hw-app-eth' import TransportNodeHid from '@ledgerhq/hw-transport-node-hid' const transport = await TransportNodeHid.default.open() const eth = new Eth.default(transport) const common = new Common({ chain: Sepolia }) // Signing with the first key of the derivation path const bip32Path = "44'/60'/0'/0/0" const legacyTxData: LegacyTxData = { nonce: '0x0', gasPrice: '0x09184e72a000', gasLimit: '0x2710', to: '0x0000000000000000000000000000000000000000', value: '0x00', data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', } const eip1559TxData: FeeMarketEIP1559TxData = { data: '0x1a8451e600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', gasLimit: '0x02625a00', maxPriorityFeePerGas: '0x01', maxFeePerGas: '0xff', nonce: '0x00', to: '0xcccccccccccccccccccccccccccccccccccccccc', value: '0x0186a0', accessList: [], type: '0x02', } const run = async () => { // Signing a legacy tx const tx1 = createLegacyTx(legacyTxData, { common }) const unsignedTx1 = tx1.getMessageToSign() // Ledger signTransaction API expects it to be serialized // Ledger returns unprefixed hex strings without 0x for v, r, s values const { v, r, s } = await eth.signTransaction( bip32Path, bytesToHex(RLP.encode(unsignedTx1)).slice(2), null, ) const signedTx1 = tx1.addSignature(BigInt(`0x${v}`), BigInt(`0x${r}`), BigInt(`0x${s}`)) const from = signedTx1.getSenderAddress().toString() console.log(`signedTx: ${bytesToHex(tx1.serialize())}\nfrom: ${from}`) // Signing a 1559 tx const tx2 = createFeeMarket1559Tx(eip1559TxData, { common }) // Ledger returns unprefixed hex strings without 0x for v, r, s values const unsignedTx2 = tx2.getMessageToSign() const { v2, r2, s2 } = await eth.signTransaction( bip32Path, bytesToHex(unsignedTx2).slice(2), null, ) const signedTx2 = tx2.addSignature(BigInt(`0x${v2}`), BigInt(`0x${r2}`), BigInt(`0x${s2}`)) const from2 = signedTx2.getSenderAddress().toString() console.log(`signedTx: ${bytesToHex(tx2.serialize())}\nfrom: ${from2}`) } run() ``` -------------------------------- ### Profile Benchmarks with 0x Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/DEVELOPER.md Use this command to profile benchmarks with detailed performance analysis using the 0x tool. It will generate a link to view the results. ```bash npm run profiling -- mainnetBlocks:10 ``` -------------------------------- ### Start EthereumJS Client with Private Network Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/examples/private-geth-network.md Launches the EthereumJS client, configuring it to use custom genesis parameters and connect to the private Geth network using the obtained bootnode enode address. ```bash npm run client:start -- --gethGenesis=path/to/poa.json --bootnodes=[enode address of your geth node] --port=30305 ``` -------------------------------- ### Registering and Using a Custom Addition Precompile Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/evm/README.md Demonstrates how to define and register a custom precompile for addition, then use it within the EVM. This example shows setting up the EVM with a custom precompile and executing a call to it. ```typescript // ./examples/precompiles/customPrecompile.ts import { Common, Hardfork, Mainnet } from '@ethereumjs/common' import { createEVM } from '@ethereumjs/evm' import { bigIntToBytes, bytesToBigInt, bytesToHex, createAddressFromString, setLengthLeft, } from '@ethereumjs/util' import type { ExecResult, PrecompileInput } from '@ethereumjs/evm' // Custom precompile that adds two 32-byte big-endian unsigned integers (mod 2^256). const ADDITION_GAS = 15n function additionPrecompile(input: PrecompileInput): ExecResult { const a = bytesToBigInt(input.data.subarray(0, 32)) const b = bytesToBigInt(input.data.subarray(32, 64)) const sum = (a + b) % 2n ** 256n return { executionGasUsed: ADDITION_GAS, returnValue: setLengthLeft(bigIntToBytes(sum), 32), } } const main = async () => { const common = new Common({ chain: Mainnet, hardfork: Hardfork.Prague }) const ADDRESS = '0x000000000000000000000000000000000000ff01' // Register the custom precompile with a hex string address const evm = await createEVM({ common, customPrecompiles: [{ address: ADDRESS, function: additionPrecompile }], }) // Verify it is registered const fn = evm.getPrecompile(ADDRESS) console.log(`Precompile registered at ${ADDRESS}: ${fn !== undefined}`) // Build call data: two 32-byte values (7 + 35) const a = setLengthLeft(bigIntToBytes(7n), 32) const b = setLengthLeft(bigIntToBytes(35n), 32) const callData = new Uint8Array(64) callData.set(a, 0) callData.set(b, 32) // Execute via runCall const result = await evm.runCall({ to: createAddressFromString(ADDRESS), gasLimit: BigInt(30000), data: callData, }) console.log('--------------------------------') console.log('Custom Addition Precompile') console.log(`Input : 7 + 35`) console.log(`Result : ${bytesToBigInt(result.execResult.returnValue)} (${bytesToHex(result.execResult.returnValue)})`) console.log(`Gas used : ${result.execResult.executionGasUsed}`) console.log('--------------------------------') } void main() ``` -------------------------------- ### Constructor Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/evm/docs/classes/EVMMockBlockchain.md Initializes a new instance of the EVMMockBlockchain class. ```APIDOC ## Constructor ### Description Initializes a new instance of the EVMMockBlockchain class. ### Returns - `EVMMockBlockchain`: An instance of the EVMMockBlockchain class. ``` -------------------------------- ### Install @ethereumjs/blockchain Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/blockchain/README.md Install the latest version of the @ethereumjs/blockchain package using npm. ```shell npm install @ethereumjs/blockchain ``` -------------------------------- ### Install EthereumJS Transaction Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/README.md Install the latest version of the @ethereumjs/tx package using npm. ```shell npm install @ethereumjs/tx ``` -------------------------------- ### Combine Add State and Snapsync in Single Step Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/test/sim/snapsync.md Combines the steps of adding state and running Snapsync into a single command. This is useful for streamlining the simulation setup and testing process. ```bash rm -rf ./datadir; EXTERNAL_RUN=true SNAP_SYNC=true DEBUG_SNAP=client:* DATADIR=/usr/app/ethereumjs/packages/client/data npx vitest test/sim/snapsync.spec.ts ``` -------------------------------- ### JSON-RPC Response Example for Eth GetBlockByNumber Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Example of a successful JSON-RPC response for the `eth_getBlockByNumber` method. ```json { "jsonrpc": "2.0", "id": "1", "result": { "number": "0x1b4", "hash": "0xdc0818cf78f21a8e70579cb46a43643f78291264dda342ae31049421c82d21ae", "parentHash": "0xe99e022112df268087ea7eafaf4790497fd21dbeeb6bd7a1721df161a6657a54", "nonce": "0x689056015818adbe", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "stateRoot": "0xddc8b0234c2e0cad087c8b389aa7ef01f7d79b2570bccb77ce48648aa61c904d", "receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "miner": "0xbb7b8287f3f0a933474a79eae42cbca977791171", "difficulty": "0x4ea3f27bc", "totalDifficulty": "0x78ed983323d", "extraData": "0x476574682f4c5649562f76312e302e302f6c696e75782f676f312e342e32", "size": "0x747", "gasLimit": "0x1388", "gasUsed": "0x0", "timestamp": "0x55ba467c", "transactions": [], "uncles": [] } } ``` -------------------------------- ### FeeMarket1559Tx Constructor Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/tx/docs/classes/FeeMarket1559Tx.md Initializes a new FeeMarket1559Tx instance. It's recommended to use static factory methods instead of direct instantiation. ```APIDOC ## new FeeMarket1559Tx(txData, opts) ### Description This constructor takes the values, validates them, assigns them and freezes the object. It is not recommended to use this constructor directly. Instead use the static factory methods to assist in creating a Transaction object from varying data types. ### Parameters #### txData - **txData** (`FeeMarketEIP1559TxData`) - Description of txData #### opts - **opts** (`TxOptions`) - Optional, defaults to `{}` ### Returns - `FeeMarket1559Tx` - A new FeeMarket1559Tx instance. ``` -------------------------------- ### Install Dependencies for LevelDB Integration Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/mpt/UPGRADING.md Installs exact versions of required packages for LevelDB integration to prevent supply chain attacks. ```shell npm i @ethereumjs/trie @ethereumjs/util abstract-level level memory-level --save-exact ``` -------------------------------- ### Instantiate and Use SimpleStateManager Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/statemanager/README.md Demonstrates how to instantiate SimpleStateManager and use its putAccount and getAccount methods. Ensure @ethereumjs/util is installed for account and address creation. ```typescript // ./examples/simple.ts import { Account, createAddressFromPrivateKey, randomBytes } from '@ethereumjs/util' import { SimpleStateManager } from '../src/index.ts' const main = async () => { const sm = new SimpleStateManager() const address = createAddressFromPrivateKey(randomBytes(32)) const account = new Account(0n, 0xfffffn) await sm.putAccount(address, account) console.log(await sm.getAccount(address)) } void main() ``` -------------------------------- ### RLP CLI Decoding Example Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/rlp/README.md Example of using the RLP CLI to decode a 0x-prefixed hex string into its original JSON representation. ```shell rlp decode 0xc88363617483646f67 ``` -------------------------------- ### RLPx Class Constructor Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/devp2p/docs/classes/RLPx.md Initializes a new RLPx instance with a private key and options. ```APIDOC ## new RLPx() ### Description Initializes a new RLPx instance. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **privateKey** (Uint8Array) - The private key for the RLPx instance. - **options** (RLPxOptions) - Configuration options for the RLPx instance. ### Request Example ```javascript const privateKey = new Uint8Array([...]); const options = { ... }; // RLPxOptions object const rlpx = new RLPx(privateKey, options); ``` ### Response #### Success Response (200) Returns the initialized RLPx instance. #### Response Example ```javascript // RLPx instance ``` ``` -------------------------------- ### CLI Autocompletion Example Source: https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/README.md Example of how CLI autocompletion appears after configuration and terminal restart/sourcing. Pressing 'tab' after '--d' shows available parameters. ```shell dist/bin/cli.js --d ```