@feelyourprotocol/vm 8141.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +583 -0
  3. package/dist/cjs/bloom/index.d.ts +29 -0
  4. package/dist/cjs/bloom/index.d.ts.map +1 -0
  5. package/dist/cjs/bloom/index.js +76 -0
  6. package/dist/cjs/bloom/index.js.map +1 -0
  7. package/dist/cjs/buildBlock.d.ts +118 -0
  8. package/dist/cjs/buildBlock.d.ts.map +1 -0
  9. package/dist/cjs/buildBlock.js +363 -0
  10. package/dist/cjs/buildBlock.js.map +1 -0
  11. package/dist/cjs/constructors.d.ts +9 -0
  12. package/dist/cjs/constructors.d.ts.map +1 -0
  13. package/dist/cjs/constructors.js +75 -0
  14. package/dist/cjs/constructors.js.map +1 -0
  15. package/dist/cjs/emitEVMProfile.d.ts +9 -0
  16. package/dist/cjs/emitEVMProfile.d.ts.map +1 -0
  17. package/dist/cjs/emitEVMProfile.js +130 -0
  18. package/dist/cjs/emitEVMProfile.js.map +1 -0
  19. package/dist/cjs/index.d.ts +11 -0
  20. package/dist/cjs/index.d.ts.map +1 -0
  21. package/dist/cjs/index.js +36 -0
  22. package/dist/cjs/index.js.map +1 -0
  23. package/dist/cjs/package.json +3 -0
  24. package/dist/cjs/params.d.ts +3 -0
  25. package/dist/cjs/params.d.ts.map +1 -0
  26. package/dist/cjs/params.js +105 -0
  27. package/dist/cjs/params.js.map +1 -0
  28. package/dist/cjs/requests.d.ts +11 -0
  29. package/dist/cjs/requests.d.ts.map +1 -0
  30. package/dist/cjs/requests.js +208 -0
  31. package/dist/cjs/requests.js.map +1 -0
  32. package/dist/cjs/runBlock.d.ts +35 -0
  33. package/dist/cjs/runBlock.d.ts.map +1 -0
  34. package/dist/cjs/runBlock.js +797 -0
  35. package/dist/cjs/runBlock.js.map +1 -0
  36. package/dist/cjs/runFrameTx.d.ts +18 -0
  37. package/dist/cjs/runFrameTx.d.ts.map +1 -0
  38. package/dist/cjs/runFrameTx.js +313 -0
  39. package/dist/cjs/runFrameTx.js.map +1 -0
  40. package/dist/cjs/runTx.d.ts +18 -0
  41. package/dist/cjs/runTx.d.ts.map +1 -0
  42. package/dist/cjs/runTx.js +900 -0
  43. package/dist/cjs/runTx.js.map +1 -0
  44. package/dist/cjs/types.d.ts +452 -0
  45. package/dist/cjs/types.d.ts.map +1 -0
  46. package/dist/cjs/types.js +3 -0
  47. package/dist/cjs/types.js.map +1 -0
  48. package/dist/cjs/vm.d.ts +75 -0
  49. package/dist/cjs/vm.d.ts.map +1 -0
  50. package/dist/cjs/vm.js +111 -0
  51. package/dist/cjs/vm.js.map +1 -0
  52. package/dist/esm/bloom/index.d.ts +29 -0
  53. package/dist/esm/bloom/index.d.ts.map +1 -0
  54. package/dist/esm/bloom/index.js +72 -0
  55. package/dist/esm/bloom/index.js.map +1 -0
  56. package/dist/esm/buildBlock.d.ts +118 -0
  57. package/dist/esm/buildBlock.d.ts.map +1 -0
  58. package/dist/esm/buildBlock.js +358 -0
  59. package/dist/esm/buildBlock.js.map +1 -0
  60. package/dist/esm/constructors.d.ts +9 -0
  61. package/dist/esm/constructors.d.ts.map +1 -0
  62. package/dist/esm/constructors.js +72 -0
  63. package/dist/esm/constructors.js.map +1 -0
  64. package/dist/esm/emitEVMProfile.d.ts +9 -0
  65. package/dist/esm/emitEVMProfile.d.ts.map +1 -0
  66. package/dist/esm/emitEVMProfile.js +127 -0
  67. package/dist/esm/emitEVMProfile.js.map +1 -0
  68. package/dist/esm/index.d.ts +11 -0
  69. package/dist/esm/index.d.ts.map +1 -0
  70. package/dist/esm/index.js +11 -0
  71. package/dist/esm/index.js.map +1 -0
  72. package/dist/esm/package.json +3 -0
  73. package/dist/esm/params.d.ts +3 -0
  74. package/dist/esm/params.d.ts.map +1 -0
  75. package/dist/esm/params.js +102 -0
  76. package/dist/esm/params.js.map +1 -0
  77. package/dist/esm/requests.d.ts +11 -0
  78. package/dist/esm/requests.d.ts.map +1 -0
  79. package/dist/esm/requests.js +204 -0
  80. package/dist/esm/requests.js.map +1 -0
  81. package/dist/esm/runBlock.d.ts +35 -0
  82. package/dist/esm/runBlock.d.ts.map +1 -0
  83. package/dist/esm/runBlock.js +790 -0
  84. package/dist/esm/runBlock.js.map +1 -0
  85. package/dist/esm/runFrameTx.d.ts +18 -0
  86. package/dist/esm/runFrameTx.d.ts.map +1 -0
  87. package/dist/esm/runFrameTx.js +310 -0
  88. package/dist/esm/runFrameTx.js.map +1 -0
  89. package/dist/esm/runTx.d.ts +18 -0
  90. package/dist/esm/runTx.d.ts.map +1 -0
  91. package/dist/esm/runTx.js +896 -0
  92. package/dist/esm/runTx.js.map +1 -0
  93. package/dist/esm/types.d.ts +452 -0
  94. package/dist/esm/types.d.ts.map +1 -0
  95. package/dist/esm/types.js +2 -0
  96. package/dist/esm/types.js.map +1 -0
  97. package/dist/esm/vm.d.ts +75 -0
  98. package/dist/esm/vm.d.ts.map +1 -0
  99. package/dist/esm/vm.js +107 -0
  100. package/dist/esm/vm.js.map +1 -0
  101. package/dist/tsconfig.prod.cjs.tsbuildinfo +1 -0
  102. package/dist/tsconfig.prod.esm.tsbuildinfo +1 -0
  103. package/package.json +117 -0
  104. package/src/bloom/index.ts +83 -0
  105. package/src/buildBlock.ts +470 -0
  106. package/src/constructors.ts +91 -0
  107. package/src/emitEVMProfile.ts +151 -0
  108. package/src/index.ts +10 -0
  109. package/src/params.ts +104 -0
  110. package/src/requests.ts +293 -0
  111. package/src/runBlock.ts +1022 -0
  112. package/src/runFrameTx.ts +411 -0
  113. package/src/runTx.ts +1203 -0
  114. package/src/types.ts +511 -0
  115. package/src/vm.ts +147 -0
package/README.md ADDED
@@ -0,0 +1,583 @@
1
+ # @ethereumjs/vm `v10`
2
+
3
+ [![NPM Package][vm-npm-badge]][vm-npm-link]
4
+ [![GitHub Issues][vm-issues-badge]][vm-issues-link]
5
+ [![Actions Status][vm-actions-badge]][vm-actions-link]
6
+ [![Code Coverage][vm-coverage-badge]][vm-coverage-link]
7
+ [![Discord][discord-badge]][discord-link]
8
+
9
+ | Execution Context for the Ethereum EVM Implementation. |
10
+ | ------------------------------------------------------ |
11
+
12
+ Ethereum `mainnet` compatible execution context for
13
+ [@ethereumjs/evm](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/evm)
14
+ to build and run blocks and txs and update state.
15
+
16
+ - 🦄 All hardforks up till **Osaka**
17
+ - 🌴 Tree-shakeable API
18
+ - 👷🏼 Controlled dependency set (7 external + `@Noble` crypto)
19
+ - 🧩 Flexible EIP on/off engine
20
+ - 📲 **EIP-7702** ready
21
+ - 📬 Flexible state retrieval (Merkle, RPC,...)
22
+ - 🔎 Passes official #Ethereum tests
23
+ - 🛵 668KB bundle size (170KB gzipped)
24
+ - 🏄🏾‍♂️ WASM-free default + Fully browser ready
25
+
26
+ ## Table of Contents
27
+
28
+ - [Installation](#installation)
29
+ - [Usage](#usage)
30
+ - [Running a Transaction](#running-a-transaction)
31
+ - [Running an RPC Mainnet Block](#running-an-rpc-mainnet-block)
32
+ - [Building a Block](#building-a-block)
33
+ - [WASM Crypto Support](#wasm-crypto-support)
34
+ - [Examples](#examples)
35
+ - [Browser](#browser)
36
+ - [API](#api)
37
+ - [Docs](#docs)
38
+ - [Hybrid CJS/ESM Builds](#hybrid-cjsesm-builds)
39
+ - [Architecture](#architecture)
40
+ - [VM/EVM Relation](#vmevm-relation)
41
+ - [State and Blockchain Information](#state-and-blockchain-information)
42
+ - [Setup](#setup)
43
+ - [Chains](#chains)
44
+ - [Hardforks](#hardforks)
45
+ - [Custom Genesis State](#custom-genesis-state)
46
+ - [Supported EIPs](#supported-eips)
47
+ - [EIP-4844 Shard Blob Transactions Support (Cancun)](#eip-4844-shard-blob-transactions-support-cancun)
48
+ - [EIP-7702 EAO Code Transactions Support (Prague)](#eip-7702-eao-code-transactions-support-prague)
49
+ - [EIP-7685 Requests Support (Prague)](#eip-7685-requests-support-prague)
50
+ - [EIP-2935 Serve Historical Block Hashes from State (Prague)](#eip-2935-serve-historical-block-hashes-from-state-prague)
51
+ - [Events](#events)
52
+ - [Tracing Events](#tracing-events)
53
+ - [Asynchronous event handlers](#asynchronous-event-handlers)
54
+ - [Synchronous event handlers](#synchronous-event-handlers)
55
+ - [Understanding the VM](#understanding-the-vm)
56
+ - [Internal Structure](#internal-structure)
57
+ - [Development](#development)
58
+ - [EthereumJS](#ethereumjs)
59
+ - [License](#license)
60
+
61
+ ## Installation
62
+
63
+ To obtain the latest version, simply require the project using `npm`:
64
+
65
+ ```shell
66
+ npm install @ethereumjs/vm
67
+ ```
68
+
69
+ **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](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/tx/README.md#kzg-setup) for instructions.
70
+
71
+ ## Usage
72
+
73
+ ### Running a Transaction
74
+
75
+ ```ts
76
+ // ./examples/runTx.ts
77
+
78
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
79
+ import { createLegacyTx } from '@ethereumjs/tx'
80
+ import { createZeroAddress } from '@ethereumjs/util'
81
+ import { createVM, runTx } from '@ethereumjs/vm'
82
+
83
+ const main = async () => {
84
+ const common = new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai })
85
+ const vm = await createVM({ common })
86
+
87
+ const tx = createLegacyTx({
88
+ gasLimit: BigInt(21000),
89
+ gasPrice: BigInt(1000000000),
90
+ value: BigInt(1),
91
+ to: createZeroAddress(),
92
+ v: BigInt(37),
93
+ r: BigInt('62886504200765677832366398998081608852310526822767264927793100349258111544447'),
94
+ s: BigInt('21948396863567062449199529794141973192314514851405455194940751428901681436138'),
95
+ })
96
+ const res = await runTx(vm, { tx, skipBalance: true })
97
+ console.log(res.totalGasSpent) // 21000n - gas cost for simple ETH transfer
98
+ }
99
+
100
+ void main()
101
+ ```
102
+
103
+ 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.
104
+
105
+ ### Running an RPC Mainnet Block
106
+
107
+ 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.
108
+
109
+ > **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.
110
+
111
+ ```ts
112
+ // ./examples/runBlockWithRPC.ts
113
+
114
+ import { createBlockFromJSONRPCProvider } from '@ethereumjs/block'
115
+ import { Common, Mainnet } from '@ethereumjs/common'
116
+ import { RPCStateManager } from '@ethereumjs/statemanager'
117
+ import { bytesToHex } from '@ethereumjs/util'
118
+ import { createVM, runBlock } from '@ethereumjs/vm'
119
+ import { trustedSetup } from '@paulmillr/trusted-setups/fast-peerdas.js'
120
+ import { KZG as microEthKZG } from 'micro-eth-signer/kzg.js'
121
+
122
+ const main = async () => {
123
+ const providerUrl = process.argv[2]
124
+ const blockNumber = process.argv[3] !== undefined ? BigInt(process.argv[3]) : undefined
125
+
126
+ if (providerUrl === undefined || blockNumber === undefined) {
127
+ console.log('Example skipped (real-world RPC scenario)')
128
+ console.log('Usage: npx tsx runBlockWithRPC.ts <providerUrl> <blockNumber>')
129
+ return
130
+ }
131
+
132
+ const kzg = new microEthKZG(trustedSetup)
133
+ const common = new Common({ chain: Mainnet, customCrypto: { kzg } })
134
+
135
+ // 1. Fetch block from RPC
136
+ console.log(`Fetching block ${blockNumber} from ${providerUrl}...`)
137
+ const block = await createBlockFromJSONRPCProvider(providerUrl, blockNumber, {
138
+ common,
139
+ setHardfork: true,
140
+ })
141
+
142
+ console.log(`Block ${block.header.number} fetched successfully`)
143
+ console.log(` Hash: ${bytesToHex(block.hash())}`)
144
+ console.log(` Parent hash: ${bytesToHex(block.header.parentHash)}`)
145
+ console.log(` State root: ${bytesToHex(block.header.stateRoot)}`)
146
+ console.log(` Transactions: ${block.transactions.length}`)
147
+ console.log(` Gas used: ${block.header.gasUsed}`)
148
+ console.log(` Hardfork: ${block.common.hardfork()}`)
149
+
150
+ // 2. Set up RPC state manager pointing to the parent block (pre-state)
151
+ const stateManager = new RPCStateManager({
152
+ provider: providerUrl,
153
+ blockTag: blockNumber - 1n,
154
+ common,
155
+ })
156
+
157
+ // 3. Create VM with the RPC state manager
158
+ const vm = await createVM({ common, stateManager, setHardfork: true })
159
+
160
+ // 4. Run the block
161
+ console.log(`\nRunning block ${blockNumber} (${block.transactions.length} txs)...`)
162
+ const startTime = performance.now()
163
+
164
+ const result = await runBlock(vm, {
165
+ block,
166
+ generate: true,
167
+ skipHeaderValidation: true,
168
+ skipBlockValidation: true,
169
+ })
170
+
171
+ const elapsed = ((performance.now() - startTime) / 1000).toFixed(1)
172
+
173
+ // 5. Display results
174
+ console.log(`\nBlock execution completed in ${elapsed}s`)
175
+ console.log(` Tx results: ${result.results.length}`)
176
+ console.log(` Receipts root: ${bytesToHex(result.receiptsRoot)}`)
177
+
178
+ console.log(`\n Gas used: ${result.gasUsed} (expected: ${block.header.gasUsed})`)
179
+ if (result.gasUsed === block.header.gasUsed) {
180
+ console.log(` Gas used MATCHES expected block header value`)
181
+ } else {
182
+ console.log(` Gas used MISMATCH`)
183
+ }
184
+
185
+ // Note: State root comparison is informational only.
186
+ // RPCStateManager cannot produce valid Merkle state roots since it
187
+ // doesn't maintain a local trie -- it fetches state on demand via RPC.
188
+ console.log(`\n Computed state root: ${bytesToHex(result.stateRoot)}`)
189
+ console.log(` Expected state root: ${bytesToHex(block.header.stateRoot)}`)
190
+ console.log(` (State root comparison is not meaningful with RPCStateManager,`)
191
+ console.log(` which does not maintain a local Merkle trie)`)
192
+ }
193
+
194
+ void main()
195
+ ```
196
+
197
+ Run with:
198
+
199
+ ```sh
200
+ npx tsx examples/runBlockWithRPC.ts <providerUrl> <blockNumber>
201
+ ```
202
+
203
+ ### Building a Block
204
+
205
+ The VM package can also be used to construct a new valid block by executing and then integrating txs one-by-one.
206
+
207
+ The following non-complete example gives some illustration on how to use the Block Builder API:
208
+
209
+ ```ts
210
+ // ./examples/buildBlock.ts
211
+
212
+ import { createBlock } from '@ethereumjs/block'
213
+ import { Common, Mainnet } from '@ethereumjs/common'
214
+ import { createLegacyTx } from '@ethereumjs/tx'
215
+ import { Account, bytesToHex, createAddressFromPrivateKey, hexToBytes } from '@ethereumjs/util'
216
+ import { buildBlock, createVM } from '@ethereumjs/vm'
217
+
218
+ const main = async () => {
219
+ const common = new Common({ chain: Mainnet })
220
+ const vm = await createVM({ common })
221
+
222
+ const parentBlock = createBlock(
223
+ { header: { number: 1n } },
224
+ { skipConsensusFormatValidation: true },
225
+ )
226
+ const headerData = {
227
+ number: 2n,
228
+ }
229
+ const blockBuilder = await buildBlock(vm, {
230
+ parentBlock, // the parent @ethereumjs/block Block
231
+ headerData, // header values for the new block
232
+ blockOpts: {
233
+ calcDifficultyFromHeader: parentBlock.header,
234
+ freeze: false,
235
+ skipConsensusFormatValidation: true,
236
+ putBlockIntoBlockchain: false,
237
+ },
238
+ })
239
+
240
+ const pk = hexToBytes('0x26f81cbcffd3d23eace0bb4eac5274bb2f576d310ee85318b5428bf9a71fc89a')
241
+ const address = createAddressFromPrivateKey(pk)
242
+ const account = new Account(0n, 0xfffffffffn)
243
+ await vm.stateManager.putAccount(address, account) // create a sending account and give it a big balance
244
+ const tx = createLegacyTx({ gasLimit: 0xffffff, gasPrice: 75n }).sign(pk)
245
+ await blockBuilder.addTransaction(tx)
246
+
247
+ // Add more transactions
248
+
249
+ const { block } = await blockBuilder.build()
250
+ console.log(`Built a block with hash ${bytesToHex(block.hash())}`)
251
+ }
252
+
253
+ void main()
254
+
255
+ ```
256
+
257
+ ### WASM Crypto Support
258
+
259
+ 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](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/common) for instructions on how to replace with e.g. a more performant WASM implementation by using a shared `common` instance.
260
+
261
+ ## Examples
262
+
263
+ See the [examples](./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:
264
+
265
+ 1. [./examples/run-blockchain](./examples/run-blockchain.ts): Loads tests data, including accounts and blocks, and runs all of them in the VM.
266
+ 2. [./examples/run-solidity-contract](./examples/run-solidity-contract.ts): Compiles a Solidity contract, and calls constant and non-constant functions.
267
+
268
+ ## Browser
269
+
270
+ 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).
271
+
272
+ 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](./examples/browser.html).
273
+
274
+ ## API
275
+
276
+ ### Docs
277
+
278
+ For documentation on `VM` instantiation, exposed API and emitted `events` see generated [API docs](./docs/README.md).
279
+
280
+ ### Hybrid CJS/ESM Builds
281
+
282
+ 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.
283
+
284
+ If you use an ES6-style `import` in your code files from the ESM build will be used:
285
+
286
+ ```ts
287
+ import { EthereumJSClass } from '@ethereumjs/[PACKAGE_NAME]'
288
+ ```
289
+
290
+ If you use Node.js specific `require`, the CJS build will be used:
291
+
292
+ ```ts
293
+ const { EthereumJSClass } = require('@ethereumjs/[PACKAGE_NAME]')
294
+ ```
295
+
296
+ Using ESM will give you additional advantages over CJS beyond browser usage like static code analysis / Tree Shaking which CJS can not provide.
297
+
298
+ ## Architecture
299
+
300
+ ### VM/EVM Relation
301
+
302
+ 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](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/evm).
303
+
304
+ It is still possible to access all `EVM` functionality through the `evm` property of the initialized `vm` object, e.g.:
305
+
306
+ ```ts
307
+ vm.evm.runCode()
308
+ vm.evm.events.on('step', function (data) {
309
+ console.log(`Opcode: ${data.opcode.name}\tStack: ${data.stack}`)
310
+ })
311
+ ```
312
+
313
+ Note that it's now also possible to pass in an own or customized `EVM` instance by using the optional `evm` constructor option.
314
+
315
+ ### State and Blockchain Information
316
+
317
+ 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).
318
+
319
+ With `VM` v6 the previously included `StateManager` has been extracted to its own package [@ethereumjs/statemanager](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/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.
320
+
321
+ ## Setup
322
+
323
+ ### Chains
324
+ 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.
325
+
326
+ ### Hardforks
327
+
328
+ For hardfork support see the [Hardfork Support](../evm#hardfork-support) section from the underlying `@ethereumjs/evm` instance.
329
+
330
+ An explicit HF in the `VM` - which is then passed on to the inner `EVM` - can be set with:
331
+
332
+ ```ts
333
+ // ./examples/runTx.ts#L1-L8
334
+
335
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
336
+ import { createLegacyTx } from '@ethereumjs/tx'
337
+ import { createZeroAddress } from '@ethereumjs/util'
338
+ import { createVM, runTx } from '@ethereumjs/vm'
339
+
340
+ const main = async () => {
341
+ const common = new Common({ chain: Mainnet, hardfork: Hardfork.Shanghai })
342
+ const vm = await createVM({ common })
343
+ ```
344
+
345
+ ### Custom Genesis State
346
+
347
+ 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.
348
+
349
+ ```ts
350
+ // ./examples/vmWithGenesisState.ts
351
+
352
+ import { Chain } from '@ethereumjs/common'
353
+ import { getGenesis } from '@ethereumjs/genesis'
354
+ import { createAddressFromString } from '@ethereumjs/util'
355
+ import { createVM } from '@ethereumjs/vm'
356
+
357
+ const main = async () => {
358
+ const genesisState = getGenesis(Chain.Mainnet)
359
+
360
+ const vm = await createVM()
361
+ await vm.stateManager.generateCanonicalGenesis!(genesisState)
362
+ const accountAddress = '0x000d836201318ec6899a67540690382780743280'
363
+ const account = await vm.stateManager.getAccount(createAddressFromString(accountAddress))
364
+
365
+ if (account === undefined) {
366
+ throw new Error('Account does not exist: failed to import genesis state')
367
+ }
368
+
369
+ console.log(
370
+ `This balance for account ${accountAddress} in this chain's genesis state is ${Number(
371
+ account?.balance,
372
+ )}`,
373
+ )
374
+ }
375
+ void main()
376
+
377
+ ```
378
+
379
+ Genesis state can be configured to contain both EOAs as well as (system) contracts with initial storage values set.
380
+
381
+ ## Supported EIPs
382
+
383
+ It is possible to individually activate EIP support in the VM by instantiate the `Common` instance passed
384
+ with the respective EIPs, e.g.:
385
+
386
+ ```ts
387
+ // ./examples/vmWithEIPs.ts
388
+
389
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
390
+ import { createVM } from '@ethereumjs/vm'
391
+
392
+ const main = async () => {
393
+ const common = new Common({ chain: Mainnet, hardfork: Hardfork.Cancun, eips: [7702] })
394
+ const vm = await createVM({ common })
395
+ console.log(
396
+ `EIP 7702 is active in isolation on top of the Cancun HF - ${vm.common.isActivatedEIP(7702)}`,
397
+ )
398
+ }
399
+ void main()
400
+
401
+ ```
402
+
403
+ For a list with supported EIPs see the [@ethereumjs/evm](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/evm) documentation.
404
+
405
+ ### EIP-4844 Shard Blob Transactions Support (Cancun)
406
+
407
+ This library supports the blob transaction type introduced with [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844). EIP-4844 comes with a dedicated opcode `BLOBHASH` and has added a new point evaluation precompile at address `0x0a`.
408
+
409
+ **Note:** Usage of the point evaluation precompile needs a manual KZG library installation and global initialization, see [KZG Setup](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/tx/README.md#kzg-setup) for instructions.
410
+
411
+ ### EIP-7702 EAO Code Transactions Support (Prague)
412
+
413
+ This library support the execution of [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) EOA code transactions (see tx library for full documentation) with `runTx()` or the wrapping `runBlock()` execution methods, see [this test setup](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/vm/test/api/EIPs/eip-7702.spec.ts) for a more complete example setup on how to run code from an EOA.
414
+
415
+ ### EIP-7685 Requests Support (Prague)
416
+
417
+ This library supports blocks including [EIP-7685](https://eips.ethereum.org/EIPS/eip-7685) requests to the consensus layer.
418
+
419
+ ### EIP-2935 Serve Historical Block Hashes from State (Prague)
420
+
421
+ Starting with `v8.1.0` the VM supports [EIP-2935](https://eips.ethereum.org/EIPS/eip-2935) which stores the latest 8192 block hashes in the storage of a system contract.
422
+
423
+ 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](https://eips.ethereum.org/EIPS/eip-7709) in a respective Verkle/Stateless hardfork.
424
+
425
+ ## Events
426
+
427
+ ### Tracing Events
428
+
429
+ Our `TypeScript` VM emits events that support async listeners (using [EventEmitter3](https://github.com/primus/eventemitter3)).
430
+
431
+ You can subscribe to the following events:
432
+
433
+ - `beforeBlock`: Emits a `Block` right before running it.
434
+ - `afterBlock`: Emits `AfterBlockEvent` right after running a block.
435
+ - `beforeTx`: Emits a `Transaction` right before running it.
436
+ - `afterTx`: Emits a `AfterTxEvent` right after running a transaction.
437
+
438
+ 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.
439
+
440
+ ```ts
441
+ // ./examples/eventListener.ts#L10-L19
442
+
443
+ // Setup an event listener on the `afterTx` event
444
+ vm.events.on('afterTx', (event, resolve) => {
445
+ console.log('asynchronous listener to afterTx', bytesToHex(event.transaction.hash()))
446
+ // we need to call resolve() to avoid the event listener hanging
447
+ resolve?.()
448
+ })
449
+
450
+ vm.events.on('afterTx', (event) => {
451
+ console.log('synchronous listener to afterTx', bytesToHex(event.transaction.hash()))
452
+ })
453
+ ```
454
+
455
+ Please note that there are additional EVM-specific events in the [@ethereumjs/evm](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/evm) package.
456
+
457
+ ### Asynchronous event handlers
458
+
459
+ You can perform asynchronous operations from within an event handler
460
+ and prevent the VM to keep running until they finish.
461
+
462
+ In order to do that, your event handler has to accept two arguments.
463
+ The first one will be the event object, and the second one a function.
464
+ The VM won't continue until you call this function.
465
+
466
+ If an exception is passed to that function, or thrown from within the
467
+ handler or a function called by it, the exception will bubble into the
468
+ VM and interrupt it, possibly corrupting its state. It's strongly
469
+ recommended not to do that.
470
+
471
+ ### Synchronous event handlers
472
+
473
+ If you want to perform synchronous operations, you don't need
474
+ to receive a function as the handler's second argument, nor call it.
475
+
476
+ Note that if your event handler receives multiple arguments, the second
477
+ one will be the continuation function, and it must be called.
478
+
479
+ If an exception is thrown from within the handler or a function called
480
+ by it, the exception will bubble into the VM and interrupt it, possibly
481
+ corrupting its state. It's strongly recommended not to throw from within
482
+ event handlers.
483
+
484
+ ## Understanding the VM
485
+
486
+ 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](https://github.com/visionmedia/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:
487
+
488
+ ![EthereumJS VM Debug Logger](./debug.png?raw=true)
489
+
490
+ The following loggers are currently available:
491
+
492
+ | Logger | Description |
493
+ | ----------- | ------------------------------------------------------------------ |
494
+ | `vm:block` | Block operations (run txs, generating receipts, block rewards,...) |
495
+ | `vm:tx` | Transaction operations (account updates, checkpointing,...) |
496
+ | `vm:tx:gas` | Transaction gas logger |
497
+ | `vm:state` | StateManager logger |
498
+
499
+ Note that there are additional EVM-specific loggers in the [@ethereumjs/evm](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/evm) package.
500
+
501
+ Here are some examples for useful logger combinations.
502
+
503
+ Run one specific logger:
504
+
505
+ ```shell
506
+ DEBUG=ethjs,vm:tx tsx test.ts
507
+ ```
508
+
509
+ Run all loggers currently available:
510
+
511
+ ```shell
512
+ DEBUG=ethjs,vm:*,vm:*:* tsx test.ts
513
+ ```
514
+
515
+ Run only the gas loggers:
516
+
517
+ ```shell
518
+ DEBUG=ethjs,vm:*:gas tsx test.ts
519
+ ```
520
+
521
+ Excluding the state logger:
522
+
523
+ ```shell
524
+ DEBUG=ethjs,vm:*,vm:*:*,-vm:state tsx test.ts
525
+ ```
526
+
527
+ Run some specific loggers including a logger specifically logging the `SSTORE` executions from the VM (this is from the screenshot above):
528
+
529
+ ```shell
530
+ DEBUG=ethjs,vm:tx,vm:evm,vm:ops:sstore,vm:*:gas tsx test.ts
531
+ ```
532
+
533
+ ## Internal Structure
534
+
535
+ The VM processes state changes at several levels:
536
+
537
+ - **[`runBlock`](./src/runBlock.ts)**: Processes a single block.
538
+ - Performs initial setup: Validates hardfork compatibility, sets the state root (if provided), applies DAO fork logic if necessary.
539
+ - Manages state checkpoints before and after processing.
540
+ - Iterates through transactions within the block:
541
+ - For each transaction, calls `runTx`.
542
+ - Processes withdrawals (post-Shanghai/EIP-4895).
543
+ - Calculates and assigns block rewards to the miner (and uncles, pre-Merge).
544
+ - Finalizes the block state (state root, receipts root, logs bloom).
545
+ - Commits or reverts state changes based on success.
546
+ - **[`runTx`](./src/runTx.ts)**: Processes a single transaction.
547
+ - Performs pre-execution checks: Sender balance sufficient for gas+value, sender nonce validity, transaction gas limit against block gas limit, EIP activations (e.g., 2930 Access Lists, 1559 Fee Market, 4844 Blobs).
548
+ - Warms up state access based on Access Lists (EIP-2929/2930).
549
+ - Pays intrinsic gas cost.
550
+ - Executes the transaction code using `vm.evm.runCall` (or specific logic for contract creation).
551
+ - Calculates gas used and refunds remaining gas.
552
+ - Transfers gas fees to the fee recipient (recipient receives all pre EIP-1559, base fee is burned post EIP-1559).
553
+ - Generates a transaction receipt.
554
+ - Manages state checkpoints and commits/reverts changes for the transaction.
555
+ - **[`vm.evm.runCall`](../evm/src/evm.ts)** (within `@ethereumjs/evm`): Executes the EVM code for a transaction (message call or contract creation).
556
+ - Steps through EVM opcodes.
557
+ - Manages memory, stack, and storage changes.
558
+ - Handles exceptions and gas consumption during execution.
559
+
560
+ 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.
561
+
562
+ ## Development
563
+
564
+ Developer documentation - currently mainly with information on testing and debugging - can be found [here](./DEVELOPER.md).
565
+
566
+ ## EthereumJS
567
+
568
+ 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](../../DEVELOPER.md) for an overview of current standards and tools and review our [code of conduct](../../CODE_OF_CONDUCT.md).
569
+
570
+ ## License
571
+
572
+ [MPL-2.0](<https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)>)
573
+
574
+ [discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue
575
+ [discord-link]: https://discord.gg/TNwARpR
576
+ [vm-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/vm.svg
577
+ [vm-npm-link]: https://www.npmjs.com/package/@ethereumjs/vm
578
+ [vm-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20vm?label=issues
579
+ [vm-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+vm"
580
+ [vm-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/VM/badge.svg
581
+ [vm-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22VM%22
582
+ [vm-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=vm
583
+ [vm-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/vm
@@ -0,0 +1,29 @@
1
+ import type { Common } from '@feelyourprotocol/common';
2
+ export declare class Bloom {
3
+ bitvector: Uint8Array;
4
+ keccakFunction: (msg: Uint8Array) => Uint8Array;
5
+ /**
6
+ * Represents a Bloom filter.
7
+ */
8
+ constructor(bitvector?: Uint8Array, common?: Common);
9
+ /**
10
+ * Adds an element to a bit vector of a 64 byte bloom filter.
11
+ * @param e - The element to add
12
+ */
13
+ add(e: Uint8Array): void;
14
+ /**
15
+ * Checks if an element is in the bloom.
16
+ * @param e - The element to check
17
+ */
18
+ check(e: Uint8Array): boolean;
19
+ /**
20
+ * Checks if multiple topics are in a bloom.
21
+ * @returns `true` if every topic is in the bloom
22
+ */
23
+ multiCheck(topics: Uint8Array[]): boolean;
24
+ /**
25
+ * Bitwise or blooms together.
26
+ */
27
+ or(bloom: Bloom): void;
28
+ }
29
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/bloom/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAIhD,qBAAa,KAAK;IAChB,SAAS,EAAE,UAAU,CAAA;IACrB,cAAc,EAAE,CAAC,GAAG,EAAE,UAAU,KAAK,UAAU,CAAA;IAE/C;;OAEG;gBACS,SAAS,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,MAAM;IAenD;;;OAGG;IACH,GAAG,CAAC,CAAC,EAAE,UAAU;IAajB;;;OAGG;IACH,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,OAAO;IAgB7B;;;OAGG;IACH,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,OAAO;IAIzC;;OAEG;IACH,EAAE,CAAC,KAAK,EAAE,KAAK;CAKhB"}