UNPKG

@usecannon/ganache

Version:

A library and cli to create a local blockchain for fast Ethereum development.

1,434 lines (1,349 loc) 568 kB
/// <reference types="node" /> import type { AbstractIteratorOptions as AbstractIteratorOptions_2 } from 'abstract-level'; import type { AbstractLevel } from 'abstract-level'; import crypto from 'crypto'; import Emittery from 'emittery'; import { EventEmitter } from 'events'; import * as LRUCache from 'lru-cache'; import { PathLike } from 'fs'; import { Readable } from 'readable-stream'; import { URL } from 'url'; /** * @experimental */ export declare const __experimental_info: () => _ExperimentalInfo; declare class AbortError extends Error { constructor(); } declare type AbstractBatch<K = any, V = any> = PutBatch<K, V> | DelBatch<K, V>; declare interface AbstractChainedBatch<K = any, V = any> extends AbstractOptions { put: (key: K, value: V) => this; del: (key: K) => this; clear: () => this; write(cb: ErrorCallback): any; write(options: any, cb: ErrorCallback): any; } declare const AbstractChainedBatch: AbstractChainedBatchConstructor; declare interface AbstractChainedBatchConstructor { // tslint:disable-next-line no-unnecessary-generics new <K = any, V = any>(db: any): AbstractChainedBatch<K, V>; // tslint:disable-next-line no-unnecessary-generics <K = any, V = any>(db: any): AbstractChainedBatch<K, V>; } declare interface AbstractClearOptions<K = any> extends AbstractOptions { gt?: K | undefined; gte?: K | undefined; lt?: K | undefined; lte?: K | undefined; reverse?: boolean | undefined; limit?: number | undefined; } declare interface AbstractGetOptions extends AbstractOptions { asBuffer?: boolean | undefined; } declare interface AbstractIterator<K, V> extends AbstractOptions { db: AbstractLevelDOWN<K, V>; next(cb: ErrorKeyValueCallback<K, V>): this; end(cb: ErrorCallback): void; } declare const AbstractIterator: AbstractIteratorConstructor; declare interface AbstractIteratorConstructor { // tslint:disable-next-line no-unnecessary-generics new <K = any, V = any>(db: any): AbstractIterator<K, V>; // tslint:disable-next-line no-unnecessary-generics <K = any, V = any>(db: any): AbstractIterator<K, V>; } declare interface AbstractIteratorOptions<K = any> extends AbstractOptions { gt?: K | undefined; gte?: K | undefined; lt?: K | undefined; lte?: K | undefined; reverse?: boolean | undefined; limit?: number | undefined; keys?: boolean | undefined; values?: boolean | undefined; keyAsBuffer?: boolean | undefined; valueAsBuffer?: boolean | undefined; } declare interface AbstractLevelDOWN<K = any, V = any> extends AbstractOptions { open(cb: ErrorCallback): void; open(options: AbstractOpenOptions, cb: ErrorCallback): void; close(cb: ErrorCallback): void; get(key: K, cb: ErrorValueCallback<V>): void; get(key: K, options: AbstractGetOptions, cb: ErrorValueCallback<V>): void; put(key: K, value: V, cb: ErrorCallback): void; put(key: K, value: V, options: AbstractOptions, cb: ErrorCallback): void; del(key: K, cb: ErrorCallback): void; del(key: K, options: AbstractOptions, cb: ErrorCallback): void; getMany(key: K[], cb: ErrorValueCallback<V[]>): void; getMany(key: K[], options: AbstractGetOptions, cb: ErrorValueCallback<V[]>): void; batch(): AbstractChainedBatch<K, V>; batch(array: ReadonlyArray<AbstractBatch<K, V>>, cb: ErrorCallback): AbstractChainedBatch<K, V>; batch( array: ReadonlyArray<AbstractBatch<K, V>>, options: AbstractOptions, cb: ErrorCallback, ): AbstractChainedBatch<K, V>; iterator(options?: AbstractIteratorOptions<K>): AbstractIterator<K, V>; readonly status: "new" | "opening" | "open" | "closing" | "closed"; isOperational(): boolean; } declare const AbstractLevelDOWN: AbstractLevelDOWNConstructor; declare interface AbstractLevelDOWNConstructor { // tslint:disable-next-line no-unnecessary-generics new <K = any, V = any>(location: string): AbstractLevelDOWN<K, V>; // tslint:disable-next-line no-unnecessary-generics <K = any, V = any>(location: string): AbstractLevelDOWN<K, V>; } declare interface AbstractOpenOptions extends AbstractOptions { createIfMissing?: boolean | undefined; errorIfExists?: boolean | undefined; } declare interface AbstractOptions { readonly [k: string]: any; } declare type AccessList = AccessListItem[]; declare type AccessList_2 = AccessListItem_2[]; declare type AccessListBuffer = AccessListBufferItem[]; declare type AccessListBufferItem = [Buffer, Buffer[]]; /** * Typed transaction with optional access lists * * - TransactionType: 1 * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) */ declare class AccessListEIP2930Transaction extends BaseTransaction_2<AccessListEIP2930Transaction> { readonly chainId: bigint; readonly accessList: AccessListBuffer; readonly AccessListJSON: AccessList; readonly gasPrice: bigint; readonly common: Common; /** * The default HF if the tx type is active on that HF * or the first greater HF where the tx is active. * * @hidden */ protected DEFAULT_HARDFORK: string; /** * Instantiate a transaction from a data dictionary. * * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * v, r, s } * * Notes: * - `chainId` will be set automatically if not provided * - All parameters are optional and have some basic default values */ static fromTxData(txData: AccessListEIP2930TxData, opts?: TxOptions): AccessListEIP2930Transaction; /** * Instantiate a transaction from the serialized tx. * * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)])` */ static fromSerializedTx(serialized: Buffer, opts?: TxOptions): AccessListEIP2930Transaction; /** * Create a transaction from a values array. * * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)]` */ static fromValuesArray(values: AccessListEIP2930ValuesArray, opts?: TxOptions): AccessListEIP2930Transaction; /** * 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. */ constructor(txData: AccessListEIP2930TxData, opts?: TxOptions); /** * The amount of gas paid for the data in this tx */ getDataFee(): bigint; /** * The up front amount that an account must have for this transaction to be valid */ getUpfrontCost(): bigint; /** * Returns a Buffer Array of the raw Buffers of the EIP-2930 transaction, in order. * * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)]` * * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block * with {@link Block.fromValuesArray}. * * For an unsigned tx this method uses the empty Buffer values for the * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. */ raw(): AccessListEIP2930ValuesArray; /** * Returns the serialized encoding of the EIP-2930 transaction. * * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)])` * * Note that in contrast to the legacy tx serialization format this is not * valid RLP any more due to the raw tx type preceding and concatenated to * the RLP encoding of the values. */ serialize(): Buffer; /** * Returns the serialized unsigned tx (hashed or raw), which can be used * to sign the transaction (e.g. for sending to a hardware wallet). * * Note: in contrast to the legacy tx the raw message format is already * serialized and doesn't need to be RLP encoded any more. * * ```javascript * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input * ``` * * @param hashMessage - Return hashed message if set to true (default: true) */ getMessageToSign(hashMessage?: boolean): Buffer; /** * Computes a sha3-256 hash of the serialized tx. * * This method can only be used for signed txs (it throws otherwise). * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. */ hash(): Buffer; /** * Computes a sha3-256 hash which can be used to verify the signature */ getMessageToVerifySignature(): Buffer; /** * Returns the public key of the sender */ getSenderPublicKey(): Buffer; _processSignature(v: bigint, r: Buffer, s: Buffer): AccessListEIP2930Transaction; /** * Returns an object with the JSON representation of the transaction */ toJSON(): JsonTx; /** * Return a compact error string representation of the object */ errorStr(): string; /** * Internal helper function to create an annotated error message * * @param msg Base error message * @hidden */ protected _errorMsg(msg: string): string; } /** * {@link AccessListEIP2930Transaction} data. */ declare interface AccessListEIP2930TxData extends TxData { /** * The transaction's chain ID */ chainId?: BigIntLike; /** * The access list which contains the addresses/storage slots which the transaction wishes to access */ accessList?: AccessListBuffer | AccessList | null; } /** * Buffer values array for an {@link AccessListEIP2930Transaction} */ declare type AccessListEIP2930ValuesArray = [ Buffer, Buffer, Buffer, Buffer, Buffer, Buffer, Buffer, AccessListBuffer, Buffer?, Buffer?, Buffer? ]; declare type AccessListItem = { address: PrefixedHexString; storageKeys: PrefixedHexString[]; }; declare type AccessListItem_2 = { address: PrefixedHexString; storageKeys: PrefixedHexString[]; }; declare class Account { address: Address; balance: Quantity; privateKey: Data; nonce: Quantity; storageRoot: Buffer; codeHash: Buffer; constructor(address: Address); static fromBuffer(buffer: Buffer): any; serialize(): Buffer; } declare class Account_2 { nonce: bigint; balance: bigint; storageRoot: Buffer; codeHash: Buffer; static fromAccountData(accountData: AccountData): Account_2; static fromRlpSerializedAccount(serialized: Buffer): Account_2; static fromValuesArray(values: Buffer[]): Account_2; /** * This constructor assigns and validates the values. * Use the static factory methods to assist in creating an Account from varying data types. */ constructor(nonce?: bigint, balance?: bigint, storageRoot?: Buffer, codeHash?: Buffer); private _validate; /** * Returns a Buffer Array of the raw Buffers for the account, in order. */ raw(): Buffer[]; /** * Returns the RLP serialization of the account as a `Buffer`. */ serialize(): Buffer; /** * Returns a `Boolean` determining if the account is a contract. */ isContract(): boolean; /** * Returns a `Boolean` determining if the account is empty complying to the definition of * account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): * "An account is considered empty when it has no code and zero nonce and zero balance." */ isEmpty(): boolean; } declare interface AccountData { nonce?: BigIntLike; balance?: BigIntLike; storageRoot?: BufferLike; codeHash?: BufferLike; } declare type AccountFields = Partial<Pick<Account_2, 'nonce' | 'balance' | 'storageRoot' | 'codeHash'>>; declare type AccountFields_2 = Partial<Pick<Account_2, 'nonce' | 'balance' | 'storageRoot' | 'codeHash'>>; declare class AccountManager { #private; constructor(blockchain: Blockchain); get(address: Address, blockNumber?: Buffer | Tag): Promise<Account | null>; getRaw(address: Address, blockNumber?: string | Buffer | Tag): Promise<Buffer | null>; getNonce(address: Address, blockNumber?: QUANTITY | Buffer | Tag): Promise<Quantity>; getBalance(address: Address, blockNumber?: QUANTITY | Buffer | Tag): Promise<Quantity>; getNonceAndBalance(address: Address, blockNumber?: QUANTITY | Buffer | Tag): Promise<{ nonce: Quantity; balance: Quantity; }>; getCode(address: Address, blockNumber?: QUANTITY | Buffer | Tag): Promise<Data>; } declare type AccountProof = { address: Address; balance: Quantity; codeHash: Data; nonce: Quantity; storageHash: Data; accountProof: Data[]; storageProof: StorageProof_2[]; }; declare type AccountState = [ balance: PrefixedHexString, code: PrefixedHexString, storage: Array<StoragePair> ]; declare type AddOpcode = { opcode: number; opcodeName: string; baseFee: number; gasFunction?: AsyncDynamicGasHandler | SyncDynamicGasHandler; logicFunction: OpHandler; }; declare type AddPrecompile = { address: Address_2; function: PrecompileFunc; }; declare class Address extends Address_2 { static ByteLength: number; constructor(value: Buffer); static from<T extends string | Buffer = string | Buffer>(value: T): Address; static toBuffer(value: JsonRpcDataInputArg): Buffer; static toString(value: JsonRpcDataInputArg): string; toJSON(): string; } /** * Handling and generating Ethereum addresses */ declare class Address_2 { readonly buf: Buffer; constructor(buf: Buffer); /** * Returns the zero address. */ static zero(): Address_2; /** * Returns an Address object from a hex-encoded string. * @param str - Hex-encoded address */ static fromString(str: string): Address_2; /** * Returns an address for a given public key. * @param pubKey The two points of an uncompressed key */ static fromPublicKey(pubKey: Buffer): Address_2; /** * Returns an address for a given private key. * @param privateKey A private key must be 256 bits wide */ static fromPrivateKey(privateKey: Buffer): Address_2; /** * Generates an address for a newly created contract. * @param from The address which is creating this new address * @param nonce The nonce of the from account */ static generate(from: Address_2, nonce: bigint): Address_2; /** * Generates an address for a contract created using CREATE2. * @param from The address which is creating this new address * @param salt A salt * @param initCode The init code of the contract being created */ static generate2(from: Address_2, salt: Buffer, initCode: Buffer): Address_2; /** * Is address equal to another. */ equals(address: Address_2): boolean; /** * Is address zero. */ isZero(): boolean; /** * True if address is in the address range defined * by EIP-1352 */ isPrecompileOrSystemAddress(): boolean; /** * Returns hex encoding of address. */ toString(): string; /** * Returns Buffer representation of address. */ toBuffer(): Buffer; } /** * A type that represents an input that can be converted to an Address. */ declare type AddressLike = Address_2 | Buffer | PrefixedHexString; declare interface AfterBlockEvent extends RunBlockResult { block: Block_3; } declare interface AfterTxEvent extends RunTxResult { /** * The transaction which just got finished */ transaction: TypedTransaction_2; } /** * A type to represent any flavor. Used internally to generalize flavors. * @internal */ declare type AnyFlavor = Flavor<string, Connector<any, any, any>, { provider?: OptionsConfig<any>; server?: OptionsConfig<any>; cli?: OptionsConfig<any>; }>; /** * Defines the interface for a API. * All properties must be `async` callable or return a `Promise` */ declare interface Api extends ApiBase { } /** * Base implementation for an API. * All properties must be `async` callable or return a `Promise` */ declare class ApiBase { readonly [index: string]: (...args: unknown[]) => Promise<unknown>; } declare class ArrayCompositeTreeView<ElementType extends CompositeType<ValueOf<ElementType>, CompositeView<ElementType>, CompositeViewDU<ElementType>>> extends TreeView<ArrayCompositeType<ElementType>> { readonly type: ArrayCompositeType<ElementType>; protected tree: Tree; constructor(type: ArrayCompositeType<ElementType>, tree: Tree); /** * Number of elements in the array. Equal to the Uint32 value of the Tree's length node */ get length(): number; /** * Returns the View's Tree rootNode */ get node(): Node; /** * Get element at `index`. Returns a view of the Composite element type */ get(index: number): CompositeView<ElementType>; /** * Get element at `index`. Returns a view of the Composite element type. * DOES NOT PROPAGATE CHANGES: use only for reads and to skip parent references. */ getReadonly(index: number): CompositeView<ElementType>; /** * Set Composite element type `view` at `index` */ set(index: number, view: CompositeView<ElementType>): void; /** * Returns an array of views of all elements in the array, from index zero to `this.length - 1`. * The returned views don't have a parent hook to this View's Tree, so changes in the returned views won't be * propagated upwards. To get linked element Views use `this.get()` */ getAllReadonly(): CompositeView<ElementType>[]; /** * Returns an array of values of all elements in the array, from index zero to `this.length - 1`. * The returned values are not Views so any changes won't be propagated upwards. * To get linked element Views use `this.get()` */ getAllReadonlyValues(): ValueOf<ElementType>[]; } declare class ArrayCompositeTreeViewDU<ElementType extends CompositeType<ValueOf<ElementType>, CompositeView<ElementType>, CompositeViewDU<ElementType>>> extends TreeViewDU<ArrayCompositeType<ElementType>> { readonly type: ArrayCompositeType<ElementType>; protected _rootNode: Node; protected nodes: Node[]; protected caches: unknown[]; protected readonly viewsChanged: Map<number, CompositeViewDU<ElementType>>; protected _length: number; protected dirtyLength: boolean; private nodesPopulated; constructor(type: ArrayCompositeType<ElementType>, _rootNode: Node, cache?: ArrayCompositeTreeViewDUCache); /** * Number of elements in the array. Equal to un-commited length of the array */ get length(): number; get node(): Node; get cache(): ArrayCompositeTreeViewDUCache; /** * Get element at `index`. Returns a view of the Composite element type. * * NOTE: Assumes that any view created here will change and will call .commit() on it. * .get() should be used only for cases when something may mutate. To get all items without * triggering a .commit() in all them use .getAllReadOnly(). */ get(index: number): CompositeViewDU<ElementType>; /** * Get element at `index`. Returns a view of the Composite element type. * DOES NOT PROPAGATE CHANGES: use only for reads and to skip parent references. */ getReadonly(index: number): CompositeViewDU<ElementType>; /** * Set Composite element type `view` at `index` */ set(index: number, view: CompositeViewDU<ElementType>): void; /** * WARNING: Returns all commited changes, if there are any pending changes commit them beforehand */ getAllReadonly(): CompositeViewDU<ElementType>[]; /** * WARNING: Returns all commited changes, if there are any pending changes commit them beforehand */ getAllReadonlyValues(): ValueOf<ElementType>[]; commit(): void; protected clearCache(): void; private populateAllNodes; } declare type ArrayCompositeTreeViewDUCache = { nodes: Node[]; caches: unknown[]; length: number; nodesPopulated: boolean; }; /** Expected API of this View's type. This interface allows to break a recursive dependency between types and views */ declare type ArrayCompositeType<ElementType extends CompositeType<unknown, CompositeView<ElementType>, CompositeViewDU<ElementType>>> = CompositeType<ValueOf<ElementType>[], unknown, unknown> & { readonly elementType: ElementType; readonly chunkDepth: number; /** INTERNAL METHOD: Return the length of this type from an Array's root node */ tree_getLength(node: Node): number; /** INTERNAL METHOD: Mutate a tree's rootNode with a new length value */ tree_setLength(tree: Tree, length: number): void; /** INTERNAL METHOD: Return the chunks node from a root node */ tree_getChunksNode(rootNode: Node): Node; /** INTERNAL METHOD: Return a new root node with changed chunks node and length */ tree_setChunksNode(rootNode: Node, chunksNode: Node, newLength?: number): Node; }; declare type ArrayToTuple<T extends Readonly<string[]>> = T[number]; /** * Array: ordered homogeneous collection */ declare abstract class ArrayType<ElementType extends Type<unknown>, TV, TVDU> extends CompositeType<ValueOf<ElementType>[], TV, TVDU> { readonly elementType: ElementType; abstract readonly itemsPerChunk: number; protected abstract readonly defaultLen: number; constructor(elementType: ElementType); defaultValue(): ValueOf<ElementType>[]; abstract tree_getLength(node: Node): number; getPropertyType(): Type<unknown>; getPropertyGindex(prop: string | number): bigint; getIndexProperty(index: number): string | number; tree_getLeafGindices(rootGindex: bigint, rootNode?: Node): bigint[]; fromJson(json: unknown): ValueOf<ElementType>[]; toJson(value: ValueOf<ElementType>[]): unknown; clone(value: ValueOf<ElementType>[]): ValueOf<ElementType>[]; equals(a: ValueOf<ElementType>[], b: ValueOf<ElementType>[]): boolean; } declare type AsCall<T> = Flatten<Omit<T, "from"> & { readonly from?: string; }>; declare type AsPooled<T> = Flatten<Omit<T, "blockNumber" | "blockHash" | "transactionIndex"> & { blockNumber: null; blockHash: null; transactionIndex: null; }>; /** * This file returns the dynamic parts of opcodes which have dynamic gas * These are not pure functions: some edit the size of the memory * These functions are therefore not read-only */ declare interface AsyncDynamicGasHandler { (runState: RunState, gas: bigint, common: Common): Promise<bigint>; } declare class AsyncEventEmitter<T extends EventMap> extends EventEmitter { emit<E extends keyof T>(event: E & string, ...args: Parameters<T[E]>): boolean; once<E extends keyof T>(event: E & string, listener: T[E]): this; first<E extends keyof T>(event: E & string, listener: T[E]): this; before<E extends keyof T>(event: E & string, target: T[E], listener: T[E]): this; after<E extends keyof T>(event: E & string, target: T[E], listener: T[E]): this; private beforeOrAfter; on<E extends keyof T>(event: E & string, listener: T[E]): this; addListener<E extends keyof T>(event: E & string, listener: T[E]): this; prependListener<E extends keyof T>(event: E & string, listener: T[E]): this; prependOnceListener<E extends keyof T>(event: E & string, listener: T[E]): this; removeAllListeners(event?: keyof T & string): this; removeListener<E extends keyof T>(event: E & string, listener: T[E]): this; eventNames(): Array<keyof T & string>; listeners<E extends keyof T>(event: E & string): Array<T[E]>; listenerCount(event: keyof T & string): number; getMaxListeners(): number; setMaxListeners(maxListeners: number): this; } declare type AsyncListener<T, R> = ((data: T, callback?: (result?: R) => void) => Promise<R>) | ((data: T, callback?: (result?: R) => void) => void); declare interface AsyncOpHandler { (runState: RunState, common: Common): Promise<void>; } declare namespace Base { type Option = { rawType?: unknown; type: unknown; hasDefault?: true; legacy?: { [name: string]: unknown; }; cliType?: CliTypes; }; type ExclusiveGroupOptionName = string; type ExclusiveGroup = ExclusiveGroupOptionName[]; type Config = { options: { [optionName: string]: Option; }; exclusiveGroups?: ExclusiveGroup[]; }; } declare type BaseFeeHeader = BlockHeader & Required<Pick<BlockHeader, "baseFeePerGas">>; declare type BaseFilterArgs = { address?: string | string[]; topics?: Topic[]; }; declare class BaseJsonRpcType { protected bufferValue: Buffer | null; private [inspect]; constructor(value: JsonRpcInputArg); toString(): string | null; toBuffer(): Buffer; valueOf(): any; toJSON(): string | null; isNull(): boolean; } declare interface BaseOpts { /** * String identifier ('byzantium') for hardfork or {@link Hardfork} enum. * * Default: Hardfork.London */ hardfork?: string | Hardfork_2; /** * Selected EIPs which can be activated, please use an array for instantiation * (e.g. `eips: [ 2537, ]`) * * Currently supported: * * - [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537) - BLS12-381 precompiles */ eips?: number[]; } declare class BaseTransaction { type: Quantity; nonce: Quantity; gas: Quantity; to: Address; value: Quantity; data: Data; v: Quantity | null; r: Quantity | null; s: Quantity | null; effectiveGasPrice: Quantity; from: Address | null; common: Common; index: Quantity; hash: Data; blockNumber: Quantity; blockHash: Data; constructor(common: Common, extra?: GanacheRawExtraTx); setExtra(raw: GanacheRawExtraTx): void; calculateIntrinsicGas(): bigint; } /** * This base class will likely be subject to further * refactoring along the introduction of additional tx types * on the Ethereum network. * * It is therefore not recommended to use directly. */ declare abstract class BaseTransaction_2<TransactionObject> { private readonly _type; readonly nonce: bigint; readonly gasLimit: bigint; readonly to?: Address_2; readonly value: bigint; readonly data: Buffer; readonly v?: bigint; readonly r?: bigint; readonly s?: bigint; readonly common: Common; protected cache: TransactionCache; protected readonly txOptions: TxOptions; /** * List of tx type defining EIPs, * e.g. 1559 (fee market) and 2930 (access lists) * for FeeMarketEIP1559Transaction objects */ protected activeCapabilities: number[]; /** * The default chain the tx falls back to if no Common * is provided and if the chain can't be derived from * a passed in chainId (only EIP-2718 typed txs) or * EIP-155 signature (legacy txs). * * @hidden */ protected DEFAULT_CHAIN: Chain; /** * The default HF if the tx type is active on that HF * or the first greater HF where the tx is active. * * @hidden */ protected DEFAULT_HARDFORK: string | Hardfork_2; constructor(txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData, opts: TxOptions); /** * Returns the transaction type. * * Note: legacy txs will return tx type `0`. */ get type(): number; /** * Checks if a tx type defining capability is active * on a tx, for example the EIP-1559 fee market mechanism * or the EIP-2930 access list feature. * * Note that this is different from the tx type itself, * so EIP-2930 access lists can very well be active * on an EIP-1559 tx for example. * * This method can be useful for feature checks if the * tx type is unknown (e.g. when instantiated with * the tx factory). * * See `Capabilites` in the `types` module for a reference * on all supported capabilities. */ supports(capability: Capability_2): boolean; /** * Checks if the transaction has the minimum amount of gas required * (DataFee + TxFee + Creation Fee). */ validate(): boolean; validate(stringError: false): boolean; validate(stringError: true): string[]; protected _validateYParity(): void; /** * EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2are considered invalid. * Reasoning: https://ethereum.stackexchange.com/a/55728 */ protected _validateHighS(): void; /** * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) */ getBaseFee(): bigint; /** * The amount of gas paid for the data in this tx */ getDataFee(): bigint; /** * The up front amount that an account must have for this transaction to be valid */ abstract getUpfrontCost(): bigint; /** * If the tx's `to` is to the creation address */ toCreationAddress(): boolean; /** * Returns a Buffer Array of the raw Buffers of this transaction, in order. * * Use {@link BaseTransaction.serialize} to add a transaction to a block * with {@link Block.fromValuesArray}. * * For an unsigned tx this method uses the empty Buffer values for the * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant * representation for external signing use {@link BaseTransaction.getMessageToSign}. */ abstract raw(): TxValuesArray | AccessListEIP2930ValuesArray | FeeMarketEIP1559ValuesArray; /** * Returns the encoding of the transaction. */ abstract serialize(): Buffer; abstract getMessageToSign(hashMessage: false): Buffer | Buffer[]; abstract getMessageToSign(hashMessage?: true): Buffer; abstract hash(): Buffer; abstract getMessageToVerifySignature(): Buffer; isSigned(): boolean; /** * Determines if the signature is valid */ verifySignature(): boolean; /** * Returns the sender's address */ getSenderAddress(): Address_2; /** * Returns the public key of the sender */ abstract getSenderPublicKey(): Buffer; /** * Signs a transaction. * * Note that the signed tx is returned as a new object, * use as follows: * ```javascript * const signedTx = tx.sign(privateKey) * ``` */ sign(privateKey: Buffer): TransactionObject; /** * Returns an object with the JSON representation of the transaction */ abstract toJSON(): JsonTx; protected abstract _processSignature(v: bigint, r: Buffer, s: Buffer): TransactionObject; /** * Does chain ID checks on common and returns a common * to be used on instantiation * @hidden * * @param common - {@link Common} instance from tx options * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) */ protected _getCommon(common?: Common, chainId?: BigIntLike): Common; /** * Validates that an object with BigInt values cannot exceed the specified bit limit. * @param values Object containing string keys and BigInt values * @param bits Number of bits to check (64 or 256) * @param cannotEqual Pass true if the number also cannot equal one less the maximum value */ protected _validateCannotExceedMaxInteger(values: { [key: string]: bigint | undefined; }, bits?: number, cannotEqual?: boolean): void; protected static _validateNotArray(values: { [key: string]: any; }): void; /** * Return a compact error string representation of the object */ abstract errorStr(): string; /** * Internal helper function to create an annotated error message * * @param msg Base error message * @hidden */ protected abstract _errorMsg(msg: string): string; /** * Returns the shared error postfix part for _error() method * tx type implementations. */ protected _getSharedErrorPostfix(): string; } /** * Abstract interface with common transaction receipt fields */ declare interface BaseTxReceipt { /** * Cumulative gas used in the block including this tx */ cumulativeBlockGasUsed: bigint; /** * Bloom bitvector */ bitvector: Buffer; /** * Logs emitted */ logs: Log[]; } /** * Represents a basic type as defined in the spec: * https://github.com/ethereum/consensus-specs/blob/dev/ssz/simple-serialize.md#basic-types */ declare abstract class BasicType<V> extends Type<V> { readonly isBasic = true; readonly depth = 0; readonly maxChunkCount = 1; abstract readonly byteLength: number; value_serializedSize(): number; tree_serializedSize(): number; protected assertValidSize(size: number): void; hashTreeRoot(value: V): Uint8Array; clone(value: V): V; equals(a: V, b: V): boolean; /** INTERNAL METHOD: Efficiently get a value from a LeafNode (not packed) */ abstract tree_getFromNode(leafNode: LeafNode): V; /** INTERNAL METHOD: Efficiently set a value to a LeafNode (not packed) */ abstract tree_setToNode(leafNode: LeafNode, value: V): void; /** INTERNAL METHOD: Efficiently get a value from a LeafNode (packed) */ abstract tree_getFromPackedNode(leafNode: LeafNode, index: number): V; /** INTERNAL METHOD: Efficiently set a value to a LeafNode (packed) */ abstract tree_setToPackedNode(leafNode: LeafNode, index: number, value: V): void; } declare type BatchDBOp = PutBatch_2 | DelBatch_2; declare interface BatchedCallback { (err?: Error, response?: (JsonRpcResponse | JsonRpcError)[]): void; } declare type BigIntLike = bigint | PrefixedHexString | number | Buffer; /** * Typed transaction with a new gas fee market mechanism for transactions that include "blobs" of data * * - TransactionType: 5 * - EIP: [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) */ declare class BlobEIP4844Transaction extends BaseTransaction_2<BlobEIP4844Transaction> { readonly chainId: bigint; readonly accessList: AccessListBuffer; readonly AccessListJSON: AccessList; readonly maxPriorityFeePerGas: bigint; readonly maxFeePerGas: bigint; readonly maxFeePerDataGas: bigint; readonly common: Common; versionedHashes: Buffer[]; blobs?: Buffer[]; kzgCommitments?: Buffer[]; aggregateKzgProof?: Buffer; /** * 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 constructors or factory methods to assist in creating a Transaction object from * varying data types. */ constructor(txData: BlobEIP4844TxData, opts?: TxOptions); static fromTxData(txData: BlobEIP4844TxData, opts?: TxOptions): BlobEIP4844Transaction; /** * Creates the minimal representation of a blob transaction from the network wrapper version. * The minimal representation is used when adding transactions to an execution payload/block * @param txData a {@link BlobEIP4844Transaction} containing optional blobs/kzg commitments * @param opts - dictionary of {@link TxOptions} * @returns the "minimal" representation of a BlobEIP4844Transaction (i.e. transaction object minus blobs and kzg commitments) */ static minimalFromNetworkWrapper(txData: BlobEIP4844Transaction, opts?: TxOptions): BlobEIP4844Transaction; /** * Creates a transaction from the network encoding of a blob transaction (with blobs/commitments/proof) * @param serialized a buffer representing a serialized BlobTransactionNetworkWrapper * @param opts any TxOptions defined * @returns a BlobEIP4844Transaction * @throws if no KZG library is loaded -- using the `initKzg` helper method -- or if `opts.common` not provided */ static fromSerializedBlobTxNetworkWrapper(serialized: Buffer, opts?: TxOptions): BlobEIP4844Transaction; /** * Creates a transaction from the "minimal" encoding of a blob transaction (without blobs/commitments/kzg proof) * @param serialized a buffer representing a serialized signed blob transaction * @param opts any TxOptions defined * @returns a BlobEIP4844Transaction */ static fromSerializedTx(serialized: Buffer, opts?: TxOptions): BlobEIP4844Transaction; /** * The up front amount that an account must have for this transaction to be valid * @param baseFee The base fee of the block (will be set to 0 if not provided) */ getUpfrontCost(baseFee?: bigint): bigint; /** * This method is not implemented for blob transactions as the `raw` method is used exclusively with * rlp encoding and these transactions use SSZ for serialization. */ raw(): TxValuesArray; toValue(): ValueOf<typeof SignedBlobTransactionType>; /** * Serialize a blob transaction to the execution payload variant * @returns the minimum (execution payload) serialization of a signed transaction */ serialize(): Buffer; /** * @returns the serialized form of a blob transaction in the network wrapper format (used for gossipping mempool transactions over devp2p) */ serializeNetworkWrapper(): Buffer; getMessageToSign(hashMessage: false): Buffer | Buffer[]; getMessageToSign(hashMessage?: true | undefined): Buffer; /** * Returns the hash of a blob transaction */ unsignedHash(): Buffer; hash(): Buffer; getMessageToVerifySignature(): Buffer; /** * Returns the public key of the sender */ getSenderPublicKey(): Buffer; toJSON(): JsonTx; _processSignature(v: bigint, r: Buffer, s: Buffer): BlobEIP4844Transaction; /** * Return a compact error string representation of the object */ errorStr(): string; /** * Internal helper function to create an annotated error message * * @param msg Base error message * @hidden */ protected _errorMsg(msg: string): string; /** * @returns the number of blobs included with this transaction */ numBlobs(): number; } /** * {@link BlobEIP4844Transaction} data. */ declare interface BlobEIP4844TxData extends FeeMarketEIP1559TxData { /** * The versioned hashes used to validate the blobs attached to a transaction */ versionedHashes?: BufferLike[]; /** * The maximum fee per data gas paid for the transaction */ maxFeePerDataGas?: BigIntLike; /** * The blobs associated with a transaction */ blobs?: BufferLike[]; /** * The KZG commitments corresponding to the versioned hashes for each blob */ kzgCommitments?: BufferLike[]; /** * The aggregate KZG proof associated with the transaction */ kzgProof?: BufferLike; } declare class Block { /** * Base fee per gas for blocks without a parent containing a base fee per gas. */ static readonly INITIAL_BASE_FEE_PER_GAS: 1000000000n; protected _size: number; protected _raw: EthereumRawBlockHeader; protected _common: Common; protected _rawTransactions: BlockRawTransaction[]; protected _rawTransactionMetaData: GanacheRawBlockTransactionMetaData[]; protected _rawWithdrawals: WithdrawalRaw[] | null; header: BlockHeader; constructor(serialized: Buffer, common: Common); /** * Migrates a serialized Block to the latest version. This should only be * called on serialized data from blocks created before v7.8.0. * * This migration updates the `size` value of the block to the correct value * by re-serializing the block for storage in the db. * @param serialized * @returns */ static migrate(serialized: Buffer): Buffer; private _hash; hash(): Data; getTransactions(): (EIP2930AccessListTransaction | LegacyTransaction | EIP1559FeeMarketTransaction)[]; toJSON<IncludeTransactions extends boolean>(includeFullTransactions: IncludeTransactions): { size: Quantity; transactions: IncludeTransactions extends true ? TypedTransactionJSON[] : Data[]; uncles: Data[]; withdrawals: Withdrawal[]; parentHash: Data; sha3Uncles: Data; miner: Data; stateRoot: Data; transactionsRoot: Data; receiptsRoot: Data; logsBloom: Data; difficulty: Quantity; totalDifficulty: Quantity; number: Quantity; gasLimit: Quantity; gasUsed: Quantity; timestamp: Quantity; extraData: Data; mixHash: Data; nonce: Data; baseFeePerGas?: Quantity; withdrawalsRoot?: Data; hash: Data; }; getTxFn<IncludeTransactions extends boolean>(include?: IncludeTransactions): (tx: TypedTransaction) => ReturnType<TypedTransaction["toJSON"]> | Data; static calcNextBaseFeeBigInt(parentHeader: BaseFeeHeader): bigint; static calcNBlocksMaxBaseFee(blocks: number, parentHeader: BaseFeeHeader): bigint; static calcNextBaseFee(parentBlock: Block): bigint; } declare type Block_2 = { header: { number: bigint; cliqueSigner(): Address_2; coinbase: Address_2; timestamp: bigint; difficulty: bigint; prevRandao: Buffer; gasLimit: bigint; baseFeePerGas?: bigint; }; }; /** * An object that represents the block. */ declare class Block_3 { readonly header: BlockHeader_2; readonly transactions: TypedTransaction_2[]; readonly uncleHeaders: BlockHeader_2[]; readonly withdrawals?: Withdrawal_2[]; readonly txTrie: Trie; readonly _common: Common; /** * Returns the withdrawals trie root for array of Withdrawal. * @param wts array of Withdrawal to compute the root of * @param optional emptyTrie to use to generate the root */ static genWithdrawalsTrieRoot(wts: Withdrawal_2[], emptyTrie?: Trie): Promise<Buffer>; /** * Returns the ssz root for array of withdrawal transactions. * @param wts array of Withdrawal to compute the root of */ static generateWithdrawalsSSZRoot(withdrawals: Withdrawal_2[]): Promise<void>; /** * Returns the txs trie root for array of TypedTransaction * @param txs array of TypedTransaction to compute the root of * @param optional emptyTrie to use to generate the root */ static genTransactionsTrieRoot(txs: TypedTransaction_2[], emptyTrie?: Trie): Promise<Buffer>; /** * Static constructor to create a block from a block data dictionary * * @param blockData * @param opts */ static fromBlockData(blockData?: BlockData, opts?: BlockOptions): Block_3; /** * Static constructor to create a block from a RLP-serialized block * * @param serialized * @param opts */ static fromRLPSerializedBlock(serialized: Buffer, opts?: BlockOptions): Block_3; /** * Static constructor to create a block from an array of Buffer values * * @param values * @param opts */ static fromValuesArray(values: BlockBuffer, opts?: BlockOptions): Block_3; /** * Creates a new block object from Ethereum JSON RPC. * * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) * @param uncles - Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) * @param options - An object describing the blockchain */ static fromRPC(blockData: JsonRpcBlock, uncles?: any[], opts?: BlockOptions): Block_3; /** * This constructor takes the values, validates them, assigns them and freezes the object. * Use the static factory methods to assist in creating a Block object from varying data types and options. */ constructor(header?: BlockHeader_2, transactions?: TypedTransaction_2[], uncleHeaders?: BlockHeader_2[], opts?: BlockOptions, withdrawals?: Withdrawal_2[]); /** * Returns a Buffer Array of the raw Buffers of this block, in order. */ raw(): BlockBuffer; /** * Returns the hash of the block. */ hash(): Buffer; /** * Determines if this block is the genesis block. */ isGenesis(): boolean; /** * Returns the rlp encoding of the block. */ serialize(): Buffer; /** * Generates transaction trie for validation. */ genTxTrie(): Promise<void>; /** * Validates the transaction trie by generating a trie * and do a check on the root hash. */ validateTransactionsTrie(): Promise<boolean>; /** * Validates transaction signatures and minimum gas requirements. * * @param stringError - If `true`, a string with the indices of the invalid txs is returned. */ validateTransactions(): boolean; validateTransactions(stringError: false): boolean; validateTransactions(stringError: true): string[]; /** * Validates the block data, throwing if invalid. * This can be checked on the Block itself without needing access to any parent block * It checks: * - All transactions are valid * - The transactions trie is valid * - The uncle hash is valid * @param onlyHeader if only passed the header, skip validating txTrie and unclesHash (default: false) */ validateData(onlyHeader?: boolean): Promise<void>; /** * Validates that data gas fee for each transaction is greater than or equal to the * dataGasPrice for the block and that total data gas in block is less than maximum * data gas per block * @param parentHeader header of parent block */ validateBlobTransactions(parentHeader: BlockHeader_2): void; /** * Validates the uncle's hash. */ validateUnclesHash(): boolean; /** * Validates the withdrawal root */ validateWithdrawalsTrie(): Promise<boolean>; /** * Consistency checks for uncles included in the block, if any. * * Throws if invalid. * * The rules for uncles checked are the following: * Header has at most 2 uncles. * Header does not count an uncle twice. */ validateUncles(): void; /** * Returns the canonical difficulty for this block. * * @param parentBlock - the parent of this `Block` */ ethashCanonicalDifficulty(parentBlock: Block_3): bigint; /** * Validates if the block gasLimit remains in the boundaries set by the protocol. * Throws if invalid * * @param parentBlock - the parent of this `Block` */ validateGasLimit(parentBlock: Block_3): void; /** * Returns the block in JSON format. */ toJSON(): JsonBlock; /** * Return a compact error string representation of the object */ errorStr(): string; /** * Internal helper function to create an annotated error message * * @param msg Base error message * @hidden */ protected _errorMsg(msg: string): string; } declare type BlockBodyBuffer = [TransactionsBuffer, UncleHeadersBuffer, WithdrawalsBuffer?]; declare type BlockBuffer = [BlockHeaderBuffer, TransactionsBuffer, UncleHeadersBuffer] | [BlockHeaderBuffer, TransactionsBuffer, UncleHeadersBuffer, WithdrawalsBuffer]; declare class BlockBuilder { /** * The cumulative gas used by the transactions added to the block. */ gasUsed: bigint; /** * The cumulative data gas used by the blobs in a block */ dataGasUsed: bigint; /** * Value of the block, represented by the final transaction fees * acruing to the miner. */ private _minerValue; private readonly vm; private blockOpts; private headerData; private transactions; private transactionResults; private withdrawals?; private checkpointed; private blockStatus; get transactionReceipts(): TxReceipt[]; get minerValue(): bigint; constructor(vm: VM, opts: BuildBlockOpts); /** * Throws if the block has already been built or reverted. */ private checkStatus; getStatus(): BlockStatus; /** * Calculates and returns the transactionsTrie for the block. */ transactionsTrie(): Promise<Buffer>; /** * Calculates and returns the logs bloom for the block. */ logsBloom(): Buffer; /** * Calculates and returns the receiptTrie for the block. */ receiptTrie(): Promise<Buffer>; /** * Adds the block miner reward to the coinbase account. */ private rewardMiner; /** * Adds the withdrawal amount to the withdrawal address */ private processWithdrawals; /** * Run and add a transaction to the block being built. * Please note that this modifies the state of the VM. * Throws if the transaction's gasLimit is greater than * the remaining gas in the block. */ addTransaction(tx: TypedTransaction_2, { skipHardForkValidation }?: { skipHardForkValidation?: boolean; }): Promise<RunTxResult>; /** * Reverts the checkpoint on the StateManager to reset the state from any transactions that have been run. */ revert(): Promise<void>; /** * This method returns the finalized block. * It also: * - Assigns the reward for miner (PoW) * - Commits the checkpoin