@ethereumjs/evm
Version:
JavaScript Ethereum Virtual Machine (EVM) implementation
246 lines • 11.5 kB
TypeScript
import type { BlockLevelAccessList, PrefixedHexString } from '@ethereumjs/util';
import { Account, Address } from '@ethereumjs/util';
import { EventEmitter } from 'eventemitter3';
import { EVMError } from './errors.ts';
import { Journal } from './journal.ts';
import { EVMPerformanceLogger } from './logger.ts';
import { Message } from './message.ts';
import { TransientStorage } from './transientStorage.ts';
import { type Block, type CustomOpcode, type EVMBLSInterface, type EVMEvent, type EVMInterface, type EVMMockBlockchainInterface, type EVMOpts, type EVMResult, type EVMRunCallOpts, type EVMRunCodeOpts, type ExecResult } from './types.ts';
import type { Common, StateManagerInterface } from '@ethereumjs/common';
import type { BinaryTreeAccessWitness } from './binaryTreeAccessWitness.ts';
import type { InterpreterOpts } from './interpreter.ts';
import type { MessageWithTo } from './message.ts';
import type { AsyncDynamicGasHandler, SyncDynamicGasHandler } from './opcodes/gas.ts';
import type { OpHandler, OpcodeList, OpcodeMap } from './opcodes/index.ts';
import type { CustomPrecompile, PrecompileFunc } from './precompiles/index.ts';
/**
* Creates a standardized ExecResult for out-of-gas errors.
* @param gasLimit - Gas limit consumed by the failing frame
* @returns Execution result describing the OOG failure
*/
export declare function OOGResult(gasLimit: bigint): ExecResult;
/**
* Creates an ExecResult for code-deposit out-of-gas errors (EIP-3541).
* @param gasUsedCreateCode - Gas consumed while attempting to store code
*/
export declare function COOGResult(gasUsedCreateCode: bigint): ExecResult;
/**
* Returns an ExecResult signalling invalid bytecode input.
* @param gasLimit - Gas consumed up to the point of failure
*/
export declare function INVALID_BYTECODE_RESULT(gasLimit: bigint): ExecResult;
/**
* Returns an ExecResult signalling invalid EOF formatting.
* @param gasLimit - Gas consumed up to the point of failure
*/
export declare function INVALID_EOF_RESULT(gasLimit: bigint): ExecResult;
/**
* Returns an ExecResult for code size violations.
* @param gasUsed - Gas consumed before the violation was detected
*/
export declare function CodesizeExceedsMaximumError(gasUsed: bigint): ExecResult;
/**
* Wraps an {@link EVMError} in an ExecResult.
* @param error - Error encountered during execution
* @param gasUsed - Gas consumed up to the error
*/
export declare function EVMErrorResult(error: EVMError, gasUsed: bigint): ExecResult;
/**
* Creates a default block header used by stand-alone executions.
* @returns Block-like object with zeroed header fields
*/
export declare function defaultBlock(): Block;
/**
* The EVM (Ethereum Virtual Machine) is responsible for executing EVM bytecode, processing transactions, and managing state changes. It handles both contract calls and contract creation operations.
*
* An EVM instance can be created with the constructor method:
*
* - {@link createEVM}
*/
export declare class EVM implements EVMInterface {
protected static supportedHardforks: ("chainstart" | "byzantium" | "istanbul" | "homestead" | "dao" | "tangerineWhistle" | "spuriousDragon" | "constantinople" | "petersburg" | "muirGlacier" | "berlin" | "london" | "arrowGlacier" | "grayGlacier" | "mergeNetsplitBlock" | "paris" | "shanghai" | "cancun" | "prague" | "osaka" | "bpo1" | "bpo2" | "bpo3" | "bpo4" | "bpo5" | "amsterdam")[];
protected _tx?: {
gasPrice: bigint;
origin: Address;
};
protected _block?: Block;
readonly common: Common;
readonly events: EventEmitter<EVMEvent>;
stateManager: StateManagerInterface;
blockchain: EVMMockBlockchainInterface;
journal: Journal;
binaryAccessWitness?: BinaryTreeAccessWitness;
systemBinaryAccessWitness?: BinaryTreeAccessWitness;
readonly transientStorage: TransientStorage;
protected _opcodes: OpcodeList;
readonly allowUnlimitedContractSize: boolean;
readonly allowUnlimitedInitCodeSize: boolean;
/**
* Accumulated block access list when EIP-7928 is active.
*
* @remarks Experimental (Amsterdam): may change on patch releases.
*/
readonly blockLevelAccessList?: BlockLevelAccessList;
/**
* EIP-8037 transaction-level state-gas reservoir.
* Holds gas paid by the user that exceeds the EIP-7825 regular-gas budget
* and is reserved exclusively for state-creation charges. State-gas charges
* draw from `stateGasReservoir` first; once exhausted, they fall through to
* the regular `gasLeft`. Refunds (revert / exceptional halt / SELFDESTRUCT
* of same-tx-created accounts) refill it.
* Initialized by `runTx` at the start of each transaction; `0` when EIP-8037 is inactive.
*
* @remarks Experimental (Amsterdam): may change on patch releases.
*/
stateGasReservoir: bigint;
/**
* EIP-8037 cumulative state-gas used by the current transaction.
*
* @remarks Experimental (Amsterdam): may change on patch releases.
*/
executionStateGasUsed: bigint;
/**
* EIP-7928 CALL post-state OOG: set while handling post-target access failure so
* `runTx` drains the state-gas reservoir and the sender pays the full tx gas limit.
*
* @remarks Experimental (Amsterdam): may change on patch releases.
*/
eip7928CallPostTargetOog: boolean;
/**
* EIP-8037 per-frame state-gas snapshots. Pushed on each message-level
* journal.checkpoint() and popped on commit (drop) or revert / exceptional
* halt (restore). Restoring on revert refunds all state-gas charges and
* undoes all reservoir refills made within the reverted frame, per spec:
* "all state-gas charged on the child frame is refunded to the parent
* frame's state_gas_reservoir [...] execution_state_gas_used is
* decreased consistently".
*/
protected _stateGasSnapshots: Array<{
reservoir: bigint;
used: bigint;
createdAccountStateGas: Map<PrefixedHexString, bigint>;
createdAccountIntrinsicStateGas: Map<PrefixedHexString, bigint>;
}>;
/**
* EIP-8037 SELFDESTRUCT deferred refund support.
* Per-address record of the state-gas charged for account creation
* (stateBytesPerNewAccount × costPerStateByte) plus code deposit
* (L × costPerStateByte) at successful CREATE/CREATE2 frame exit.
* Reset at the start of each tx and consulted by runTx to refund
* state-gas for accounts that were both created and SELFDESTRUCTed
* in the same tx (per EIP-6780 + EIP-8037).
* Storage-slot state-gas is not tracked here yet; that is a separate
* follow-up.
*/
createdAccountStateGas: Map<PrefixedHexString, bigint>;
/**
* EIP-8037 (v7): intrinsic state-gas tracking for depth=0 creation
* transactions. The intrinsic stateBytesPerNewAccount * costPerStateByte
* is paid up-front in runTx and isn't part of stateGasCreate. On a same-tx
* SELFDESTRUCT of the freshly-created contract, runTx refunds the STATE
* dimension only (decrement execution_state_gas_used) — the reservoir is
* NOT credited, so the user still pays the gross intrinsic. This realizes
* the v7 spec note "tx doesn't over charge for an account that never
* persists" at the block_state_gas_used level.
*/
createdAccountIntrinsicStateGas: Map<PrefixedHexString, bigint>;
protected readonly _customOpcodes?: CustomOpcode[];
protected readonly _customPrecompiles?: CustomPrecompile[];
protected _handlers: Map<number, OpHandler>;
protected _dynamicGasHandlers: Map<number, AsyncDynamicGasHandler | SyncDynamicGasHandler>;
protected _opcodeMap: OpcodeMap;
protected _precompiles: Map<string, PrecompileFunc>;
protected readonly _optsCached: EVMOpts;
protected performanceLogger: EVMPerformanceLogger;
get precompiles(): Map<string, PrecompileFunc>;
get opcodes(): OpcodeList;
protected readonly _bls?: EVMBLSInterface;
/**
* EVM is run in DEBUG mode (default: false)
* Taken from DEBUG environment variable
*
* Safeguards on debug() calls are added for
* performance reasons to avoid string literal evaluation
* @hidden
*/
readonly DEBUG: boolean;
protected readonly _emit: (topic: string, data: any) => Promise<void>;
private _bn254;
/**
*
* Creates new EVM object
*
* @deprecated The direct usage of this constructor is replaced since
* non-finalized async initialization lead to side effects. Please
* use the async {@link createEVM} constructor instead (same API).
*
* @param opts The EVM options
* @param bn128 Initialized bn128 WASM object for precompile usage (internal)
*/
constructor(opts: EVMOpts);
/**
* Returns a list with the currently activated opcodes
* available for EVM execution
*/
getActiveOpcodes(): OpcodeList;
protected _executeCall(message: MessageWithTo): Promise<EVMResult>;
protected _executeCreate(message: Message): Promise<EVMResult>;
/**
* Starts the actual bytecode processing for a CALL or CREATE
*/
protected runInterpreter(message: Message, opts?: InterpreterOpts): Promise<ExecResult>;
/**
* Executes an EVM message, determining whether it's a call or create
* based on the `to` address. It checkpoints the state and reverts changes
* if an exception happens during the message execution.
*/
runCall(opts: EVMRunCallOpts): Promise<EVMResult>;
/**
* Bound to the global VM and therefore
* shouldn't be used directly from the evm class
*/
runCode(opts: EVMRunCodeOpts): Promise<ExecResult>;
/**
* Returns the precompile function registered at the given address,
* or `undefined` if no precompile is active there.
*
* Accepts either an `Address` instance or a `0x`-prefixed hex string.
*
* ```ts
* const evm = await createEVM({
* customPrecompiles: [{ address: '0x000000000000000000000000000000000000ff01', function: myFn }],
* })
* const fn = evm.getPrecompile('0x000000000000000000000000000000000000ff01')
* ```
*/
getPrecompile(address: Address | PrefixedHexString): PrecompileFunc | undefined;
/**
* Executes a precompiled contract with given data and gas limit.
*/
protected runPrecompile(code: PrecompileFunc, data: Uint8Array, gasLimit: bigint): Promise<ExecResult> | ExecResult;
protected _loadCode(message: Message): Promise<void>;
protected _generateAddress(message: Message): Promise<Address>;
protected _reduceSenderBalance(account: Account, message: Message): Promise<void>;
protected _addToBalance(toAccount: Account, message: MessageWithTo): Promise<void>;
/**
* Once the interpreter has finished depth 0, a post-message cleanup should be done
*/
private postMessageCleanup;
/**
* This method copies the EVM, current HF and EIP settings
* and returns a new EVM instance.
*
* Note: this is only a shallow copy and both EVM instances
* will point to the same underlying state DB.
*
* @returns EVM
*/
shallowCopy(): EVM;
getPerformanceLogs(): {
opcodes: import("./logger.ts").EVMPerformanceLogOutput[];
precompiles: import("./logger.ts").EVMPerformanceLogOutput[];
};
clearPerformanceLogs(): void;
}
//# sourceMappingURL=evm.d.ts.map