Skip to main content

eth

Index

References

Namespaces

Classes

Interfaces

Type Aliases

Variables

Functions

References

Web3Eth

Re-exports Web3Eth

decodeEventABI

Re-exports decodeEventABI

Namespaces

abi

abi:

decodeContractErrorData

decodeLog

  • decodeLog<ReturnType_1>(inputs: AbiParameter[], data: string, topics: string | string[]): ReturnType_1
  • Decodes ABI-encoded log data and indexed topic data.

    @example
    let res = web3.eth.abi.decodeLog(
    [
    {
    type: "string",
    name: "myString",
    },
    {
    type: "uint256",
    name: "myNumber",
    indexed: true,
    },
    {
    type: "uint8",
    name: "mySmallNumber",
    indexed: true,
    },
    ],
    "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000",
    [
    "0x000000000000000000000000000000000000000000000000000000000000f310",
    "0x0000000000000000000000000000000000000000000000000000000000000010",
    ]
    );
    > {
    '0': 'Hello%!',
    '1': 62224n,
    '2': 16n,
    __length__: 3,
    myString: 'Hello%!',
    myNumber: 62224n,
    mySmallNumber: 16n
    }

    Type parameters

    Parameters

    • inputs: AbiParameter[]

      A AbiParameter input array. See the Solidity documentation for a list of types.

    • data: string

      The ABI byte code in the data field of a log.

    • topics: string | string[]

      An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0]

    Returns ReturnType_1

    • The result object containing the decoded parameters.

decodeParameter

  • decodeParameter(abi: AbiInput, bytes: string): unknown
  • Decodes an ABI encoded parameter to its JavaScript type.

    @example
      const res = web3.eth.abi.decodeParameter(
    "uint256",
    "0x0000000000000000000000000000000000000000000000000000000000000010"
    );
    console.log(res);
    > 16n

    const res = web3.eth.abi.decodeParameter(
    "string",
    "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000"
    );

    console.log(res);
    > Hello!%!

    const res = web3.eth.abi.decodeParameter(
    {
    ParentStruct: {
    propertyOne: "uint256",
    propertyTwo: "uint256",
    childStruct: {
    propertyOne: "uint256",
    propertyTwo: "uint256",
    },
    },
    },
    "0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e"
    );

    console.log(res);
    {
    '0': 42n,
    '1': 56n,
    '2': {
    '0': 45n,
    '1': 78n,
    __length__: 2,
    propertyOne: 45n,
    propertyTwo: 78n
    },
    __length__: 3,
    propertyOne: 42n,
    propertyTwo: 56n,
    childStruct: {
    '0': 45n,
    '1': 78n,
    __length__: 2,
    propertyOne: 45n,
    propertyTwo: 78n
    }
    }

    Parameters

    Returns unknown

    • The decoded parameter

decodeParameters

  • decodeParameters(abi: AbiInput[], bytes: string): { __length__: number }
  • Decodes ABI encoded parameters to its JavaScript types.

    @example
    let res = web3.eth.abi.decodeParameters(
    ["string", "uint256"],
    "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000"
    );
    console.log(res);
    > { '0': 'Hello!%!', '1': 234n, __length__: 2 }

    let res = web3.eth.abi.decodeParameters(
    [
    {
    type: "string",
    name: "myString",
    },
    {
    type: "uint256",
    name: "myNumber",
    },
    ],
    "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000"
    );
    console.log(res);
    > {
    '0': 'Hello!%!',
    '1': 234n,
    __length__: 2,
    myString: 'Hello!%!',
    myNumber: 234n
    }

    const res = web3.eth.abi.decodeParameters(
    [
    "uint8[]",
    {
    ParentStruct: {
    propertyOne: "uint256",
    propertyTwo: "uint256",
    childStruct: {
    propertyOne: "uint256",
    propertyTwo: "uint256",
    },
    },
    },
    ],
    "0x00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000018"
    );
    console.log(res);
    >
    '0': [ 42n, 24n ],
    '1': {
    '0': 42n,
    '1': 56n,
    '2': {
    '0': 45n,
    '1': 78n,
    __length__: 2,
    propertyOne: 45n,
    propertyTwo: 78n
    },
    __length__: 3,
    propertyOne: 42n,
    propertyTwo: 56n,
    childStruct: {
    '0': 45n,
    '1': 78n,
    __length__: 2,
    propertyOne: 45n,
    propertyTwo: 78n
    }
    },
    __length__: 2,
    ParentStruct: {
    '0': 42n,
    '1': 56n,
    '2': {
    '0': 45n,
    '1': 78n,
    __length__: 2,
    propertyOne: 45n,
    propertyTwo: 78n
    },
    __length__: 3,
    propertyOne: 42n,
    propertyTwo: 56n,
    childStruct: {
    '0': 45n,
    '1': 78n,
    __length__: 2,
    propertyOne: 45n,
    propertyTwo: 78n
    }
    }
    }

    Parameters

    Returns { __length__: number }

    • The result object containing the decoded parameters.
    • [key string]: unknown
    • __length__: number

decodeParametersWith

  • decodeParametersWith(abis: AbiInput[], bytes: string, loose: boolean): { __length__: number }
  • Should be used to decode list of params


    Parameters

    • abis: AbiInput[]
    • bytes: string
    • loose: boolean

    Returns { __length__: number }

    • [key string]: unknown
    • __length__: number

encodeErrorSignature

  • Encodes the error name to its ABI signature, which are the sha3 hash of the error name including input types.


    Parameters

    Returns string

encodeEventSignature

  • Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types.

    @example
    const event = web3.eth.abi.encodeEventSignature({
    name: "myEvent",
    type: "event",
    inputs: [
    {
    type: "uint256",
    name: "myNumber",
    },
    {
    type: "bytes32",
    name: "myBytes",
    },
    ],
    });
    console.log(event);
    > 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97

    const event = web3.eth.abi.encodeEventSignature({
    inputs: [
    {
    indexed: true,
    name: "from",
    type: "address",
    },
    {
    indexed: true,
    name: "to",
    type: "address",
    },
    {
    indexed: false,
    name: "value",
    type: "uint256",
    },
    ],
    name: "Transfer",
    type: "event",
    });
    console.log(event);
    > 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef

    Parameters

    • functionName: string | AbiEventFragment

      The event name to encode, or the AbiEventFragment object of the event. If string, it has to be in the form of eventName(param1Type,param2Type,...). eg: myEvent(uint256,bytes32).

    Returns string

    • The ABI signature of the event.

encodeFunctionCall

  • Encodes a function call using its JSON interface object and given parameters. The JSON interface spec documentation https://docs.soliditylang.org/en/latest/abi-spec.html#json

    @example
    const sig = web3.eth.abi.encodeFunctionCall(
    {
    name: "myMethod",
    type: "function",
    inputs: [
    {
    type: "uint256",
    name: "myNumber",
    },
    {
    type: "string",
    name: "myString",
    },
    ],
    },
    ["2345675643", "Hello!%"]
    );
    console.log(sig);
    > 0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000



    const sig = web3.eth.abi.encodeFunctionCall(
    {
    inputs: [
    {
    name: "account",
    type: "address",
    },
    ],
    name: "balanceOf",
    outputs: [
    {
    name: "",
    type: "uint256",
    },
    ],
    stateMutability: "view",
    type: "function",
    },
    ["0x1234567890123456789012345678901234567890"]
    );

    console.log(sig);
    > 0x70a082310000000000000000000000001234567890123456789012345678901234567890

    Parameters

    • jsonInterface: AbiFunctionFragment

      The JSON interface object of the function.

    • params: unknown[]

      The parameters to encode

    Returns string

    • The ABI encoded function call, which, means the function signature and the parameters passed.

encodeFunctionSignature

  • Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. The JSON interface spec documentation https://docs.soliditylang.org/en/latest/abi-spec.html#json

    @example
    const signature = web3.eth.abi.encodeFunctionSignature({
    name: "myMethod",
    type: "function",
    inputs: [
    {
    type: "uint256",
    name: "myNumber",
    },
    {
    type: "string",
    name: "myString",
    },
    ],
    });
    console.log(signature);
    > 0x24ee0097

    const signature = web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)')
    console.log(signature);
    > 0x24ee0097

    const signature = web3.eth.abi.encodeFunctionSignature('safeTransferFrom(address,address,uint256,bytes)');
    console.log(signature);
    > 0xb88d4fde

    Parameters

    • functionName: string | AbiFunctionFragment

      The function name to encode or the JSON interface object of the function. If the passed parameter is a string, it has to be in the form of functionName(param1Type,param2Type,...). eg: myFunction(uint256,uint32[],bytes10,bytes)

    Returns string

    • The ABI signature of the function.

encodeParameter

  • encodeParameter(abi: AbiInput, param: unknown): string
  • Encodes a parameter based on its type to its ABI representation.

    @example
     const res = web3.eth.abi.encodeParameter("uint256", "2345675643");
    console.log(res);
    0x000000000000000000000000000000000000000000000000000000008bd02b7b

    const res = web3.eth.abi.encodeParameter("uint", "2345675643");

    console.log(res);
    >0x000000000000000000000000000000000000000000000000000000008bd02b7b

    const res = web3.eth.abi.encodeParameter("bytes32", "0xdf3234");

    console.log(res);
    >0xdf32340000000000000000000000000000000000000000000000000000000000

    const res = web3.eth.abi.encodeParameter("bytes", "0xdf3234");

    console.log(res);
    > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000

    const res = web3.eth.abi.encodeParameter("bytes32[]", ["0xdf3234", "0xfdfd"]);

    console.log(res);
    > 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000

    const res = web3.eth.abi.encodeParameter(
    {
    ParentStruct: {
    propertyOne: "uint256",
    propertyTwo: "uint256",
    childStruct: {
    propertyOne: "uint256",
    propertyTwo: "uint256",
    },
    },
    },
    {
    propertyOne: 42,
    propertyTwo: 56,
    childStruct: {
    propertyOne: 45,
    propertyTwo: 78,
    },
    }
    );

    console.log(res);
    > 0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000004e

    Parameters

    Returns string

    • The ABI encoded parameter

encodeParameters

  • encodeParameters(abi: readonly AbiInput[], params: unknown[]): string
  • Encodes a parameter based on its type to its ABI representation.

    @example
    const res = web3.eth.abi.encodeParameters(
    ["uint256", "string"],
    ["2345675643", "Hello!%"]
    );

    console.log(res);
    > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000

    Parameters

    Returns string

    • The ABI encoded parameters

flattenTypes

  • flattenTypes(includeTuple: boolean, puts: readonly AbiParameter[]): string[]
  • used to flatten json abi inputs/outputs into an array of type-representing-strings


    Parameters

    Returns string[]

formatOddHexstrings

  • formatOddHexstrings(param: string): string
  • format odd-length bytes to even-length


    Parameters

    • param: string

    Returns string

formatParam

  • formatParam(type: string, _param: unknown): unknown
  • Handle some formatting of params for backwards compatibility with Ethers V4


    Parameters

    • type: string
    • _param: unknown

    Returns unknown

getEncodedEip712Data

  • Get the EIP-191 encoded message to sign, from the typedData object. If hash is enabled, the message will be hashed with Keccak256.


    Parameters

    Returns string

inferTypesAndEncodeParameters

  • inferTypesAndEncodeParameters(params: unknown[]): string
  • Infer a smart contract method parameter type and then encode this parameter.

    @remarks

    This method is useful when you don't know the type of the parameters you want to encode. It will infer the type of the parameters and then encode them. However, it is not recommended to use this method when you know the type of the parameters you want to encode. In this case, use the encodeParameters method instead. The type inference is not perfect and can lead to unexpected results. Especially when you want to encode an array, uint that is not uint256 or bytes....

    @example
    const res = web3.eth.abi.encodeParameters(
    ["2345675643", "Hello!%"]
    );

    console.log(res);
    > 0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000

    Parameters

    • params: unknown[]

      The parameters to encode.

    Returns string

    • The ABI encoded parameters

isAbiConstructorFragment

isAbiErrorFragment

isAbiEventFragment

isAbiFragment

isAbiFunctionFragment

isOddHexstring

  • isOddHexstring(param: unknown): boolean
  • returns true if input is a hexstring and is odd-lengthed


    Parameters

    • param: unknown

    Returns boolean

isSimplifiedStructFormat

  • isSimplifiedStructFormat(type: string | Partial<AbiParameter> | Partial<AbiParameter> | Partial<{ components?: Components; index?: boolean; internalType?: string; name: string; type: string }> | Partial<{}>): type is Omit<AbiParameter, name | components>
  • Check if type is simplified struct format


    Parameters

    • type: string | Partial<AbiParameter> | Partial<AbiParameter> | Partial<{ components?: Components; index?: boolean; internalType?: string; name: string; type: string }> | Partial<{}>

    Returns type is Omit<AbiParameter, name | components>

jsonInterfaceMethodToString

  • Should be used to create full function/event name from json abi returns a string


    Parameters

    Returns string

mapStructNameAndType

  • mapStructNameAndType(structName: string): AbiStruct
  • Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used


    Parameters

    • structName: string

    Returns AbiStruct

mapStructToCoderFormat

  • Maps the simplified format in to the expected format of the ABICoder


    Parameters

    Returns AbiCoderStruct[]

mapTypes

  • Map types if simplified format is used


    Parameters

    Returns (string | Record<string, unknown> | AbiParameter)[]

accounts

accounts:

txUtils

txUtils:

checkMaxInitCodeSize

  • checkMaxInitCodeSize(common: Common, length: number): void
  • Parameters

    • common: Common
    • length: number

    Returns void

getAccessListData

  • getAccessListData(accessList: AccessListUint8Array | AccessList): { AccessListJSON: AccessList; accessList: AccessListUint8Array }
  • Parameters

    • accessList: AccessListUint8Array | AccessList

    Returns { AccessListJSON: AccessList; accessList: AccessListUint8Array }

    • AccessListJSON: AccessList
    • accessList: AccessListUint8Array

getAccessListJSON

  • getAccessListJSON(accessList: AccessListUint8Array): { address: string; storageKeys: string[] }[]
  • Parameters

    • accessList: AccessListUint8Array

    Returns { address: string; storageKeys: string[] }[]

getDataFeeEIP2930

  • getDataFeeEIP2930(accessList: AccessListUint8Array, common: Common): number
  • Parameters

    • accessList: AccessListUint8Array
    • common: Common

    Returns number

verifyAccessList

  • verifyAccessList(accessList: AccessListUint8Array): void
  • Parameters

    • accessList: AccessListUint8Array

    Returns void

Capability

Capability:

Can be used in conjunction with Transaction.supports to query on tx capabilities

EIP1559FeeMarket

EIP1559FeeMarket: 1559

Tx supports EIP-1559 gas fee market mechanism See: 1559 Fee Market EIP

EIP155ReplayProtection

EIP155ReplayProtection: 155

Tx supports EIP-155 replay protection See: 155 Replay Attack Protection EIP

EIP2718TypedTransaction

EIP2718TypedTransaction: 2718

Tx is a typed transaction as defined in EIP-2718 See: 2718 Transaction Type EIP

EIP2930AccessLists

EIP2930AccessLists: 2930

Tx supports access list generation as defined in EIP-2930 See: 2930 Access Lists EIP

Chain

Chain:

Goerli

Goerli: 5

Mainnet

Mainnet: 1

Sepolia

Sepolia: 11155111

ConsensusAlgorithm

ConsensusAlgorithm:

Casper

Casper: casper

Clique

Clique: clique

Ethash

Ethash: ethash

ConsensusType

ConsensusType:

ProofOfAuthority

ProofOfAuthority: poa

ProofOfStake

ProofOfStake: pos

ProofOfWork

ProofOfWork: pow

CustomChain

CustomChain:

ArbitrumOne

ArbitrumOne: arbitrum-one

Arbitrum One - mainnet for Arbitrum roll-up

ArbitrumRinkebyTestnet

ArbitrumRinkebyTestnet: arbitrum-rinkeby-testnet

Arbitrum Rinkeby Testnet

OptimisticEthereum

OptimisticEthereum: optimistic-ethereum

Optimistic Ethereum - mainnet for Optimism roll-up

OptimisticKovan

OptimisticKovan: optimistic-kovan

Optimistic Kovan - testnet for Optimism roll-up

PolygonMainnet

PolygonMainnet: polygon-mainnet

Polygon (Matic) Mainnet

PolygonMumbai

PolygonMumbai: polygon-mumbai

Polygon (Matic) Mumbai Testnet

xDaiChain

xDaiChain: x-dai-chain

xDai EVM sidechain with a native stable token

Hardfork

Hardfork:

ArrowGlacier

ArrowGlacier: arrowGlacier

Berlin

Berlin: berlin

Byzantium

Byzantium: byzantium

Chainstart

Chainstart: chainstart

Constantinople

Constantinople: constantinople

Dao

Dao: dao

GrayGlacier

GrayGlacier: grayGlacier

Homestead

Homestead: homestead

Istanbul

Istanbul: istanbul

London

London: london

Merge

Merge: merge

MergeForkIdTransition

MergeForkIdTransition: mergeForkIdTransition

MuirGlacier

MuirGlacier: muirGlacier

Petersburg

Petersburg: petersburg

Shanghai

Shanghai: shanghai

ShardingForkDev

ShardingForkDev: shardingFork

SpuriousDragon

SpuriousDragon: spuriousDragon

TangerineWhistle

TangerineWhistle: tangerineWhistle

TypeOutput

TypeOutput:

Type output options

BigInt

BigInt: 1

Number

Number: 0

PrefixedHexString

PrefixedHexString: 3

Uint8Array

Uint8Array: 2

AccessListEIP2930Transaction

AccessListEIP2930Transaction:

Typed transaction with optional access lists

constructor

  • new AccessListEIP2930Transaction(txData: AccessListEIP2930TxData, 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.


    Parameters

    • txData: AccessListEIP2930TxData
    • optionalopts: TxOptions

    Returns AccessListEIP2930Transaction

readonlyAccessListJSON

AccessListJSON: AccessList

readonlyaccessList

accessList: AccessListUint8Array

readonlychainId

chainId: bigint

readonlycommon

common: Common

readonlydata

data: Uint8Array

readonlygasLimit

gasLimit: bigint

readonlygasPrice

gasPrice: bigint

readonlynonce

nonce: bigint

optionalreadonlyr

r?: bigint

optionalreadonlys

s?: bigint

optionalreadonlyto

to?: Address

optionalreadonlyv

v?: bigint

readonlyvalue

value: bigint

type

  • get type(): number
  • Returns the transaction type.

    Note: legacy txs will return tx type 0.


    Returns number

_processSignature

  • _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): AccessListEIP2930Transaction
  • Parameters

    • v: bigint
    • r: Uint8Array
    • s: Uint8Array

    Returns AccessListEIP2930Transaction

errorStr

  • errorStr(): string
  • Return a compact error string representation of the object


    Returns string

getBaseFee

  • getBaseFee(): bigint
  • The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)


    Returns bigint

getDataFee

  • getDataFee(): bigint
  • The amount of gas paid for the data in this tx


    Returns bigint

getMessageToSign

  • getMessageToSign(hashMessage?: boolean): Uint8Array
  • 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.

    const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input

    Parameters

    • optionalhashMessage: boolean

      Return hashed message if set to true (default: true)

    Returns Uint8Array

getMessageToVerifySignature

  • getMessageToVerifySignature(): Uint8Array
  • Computes a sha3-256 hash which can be used to verify the signature


    Returns Uint8Array

getSenderAddress

  • getSenderAddress(): Address
  • Returns the sender's address


    Returns Address

getSenderPublicKey

  • getSenderPublicKey(): Uint8Array
  • Returns the public key of the sender


    Returns Uint8Array

getUpfrontCost

  • getUpfrontCost(): bigint
  • The up front amount that an account must have for this transaction to be valid


    Returns bigint

hash

  • hash(): Uint8Array
  • Computes a sha3-256 hash of the serialized tx.

    This method can only be used for signed txs (it throws otherwise). Use AccessListEIP2930Transaction.getMessageToSign to get a tx hash for the purpose of signing.


    Returns Uint8Array

isSigned

  • isSigned(): boolean
  • Returns boolean

raw

  • raw(): AccessListEIP2930ValuesArray
  • Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-2930 transaction, in order.

    Format:

    [chainId, nonce, gasPrice, gasLimit, to, value, data, accessList,
    signatureYParity (v), signatureR (r), signatureS (s)]

    Use AccessListEIP2930Transaction.serialize to add a transaction to a block with Block.fromValuesArray.

    For an unsigned tx this method uses the empty UINT8ARRAY values for the signature parameters v, r and s for encoding. For an EIP-155 compliant representation for external signing use AccessListEIP2930Transaction.getMessageToSign.


    Returns AccessListEIP2930ValuesArray

serialize

  • serialize(): Uint8Array
  • 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.


    Returns Uint8Array

sign

  • sign(privateKey: Uint8Array): AccessListEIP2930Transaction
  • Signs a transaction.

    Note that the signed tx is returned as a new object, use as follows:

    const signedTx = tx.sign(privateKey)

    Parameters

    • privateKey: Uint8Array

    Returns AccessListEIP2930Transaction

supports

  • supports(capability: Capability): boolean
  • 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.


    Parameters

    • capability: Capability

    Returns boolean

toCreationAddress

  • toCreationAddress(): boolean
  • If the tx's to is to the creation address


    Returns boolean

toJSON

  • toJSON(): JsonTx
  • Returns an object with the JSON representation of the transaction


    Returns JsonTx

validate

  • validate(): boolean
  • validate(stringError: false): boolean
  • validate(stringError: true): string[]
  • Checks if the transaction has the minimum amount of gas required (DataFee + TxFee + Creation Fee).


    Returns boolean

verifySignature

  • verifySignature(): boolean
  • Determines if the signature is valid


    Returns boolean

staticfromSerializedTx

  • fromSerializedTx(serialized: Uint8Array, 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)])


    Parameters

    • serialized: Uint8Array
    • optionalopts: TxOptions

    Returns AccessListEIP2930Transaction

staticfromTxData

  • fromTxData(txData: AccessListEIP2930TxData, opts?: TxOptions): AccessListEIP2930Transaction
  • 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

    Parameters

    • txData: AccessListEIP2930TxData
    • optionalopts: TxOptions

    Returns AccessListEIP2930Transaction

staticfromValuesArray

  • fromValuesArray(values: AccessListEIP2930ValuesArray, 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)]


    Parameters

    • values: AccessListEIP2930ValuesArray
    • optionalopts: TxOptions

    Returns AccessListEIP2930Transaction

abstractBaseTransaction

BaseTransaction<TransactionObject>:

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.


Type parameters

  • TransactionObject

constructor

  • new BaseTransaction<TransactionObject>(txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData, opts: TxOptions): BaseTransaction<TransactionObject>
  • Type parameters

    • TransactionObject

    Parameters

    • txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData
    • opts: TxOptions

    Returns BaseTransaction<TransactionObject>

readonlycommon

common: Common

readonlydata

data: Uint8Array

readonlygasLimit

gasLimit: bigint

readonlynonce

nonce: bigint

optionalreadonlyr

r?: bigint

optionalreadonlys

s?: bigint

optionalreadonlyto

to?: Address

optionalreadonlyv

v?: bigint

readonlyvalue

value: bigint

type

  • get type(): number
  • Returns the transaction type.

    Note: legacy txs will return tx type 0.


    Returns number

abstracterrorStr

  • errorStr(): string
  • Return a compact error string representation of the object


    Returns string

getBaseFee

  • getBaseFee(): bigint
  • The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)


    Returns bigint

getDataFee

  • getDataFee(): bigint
  • The amount of gas paid for the data in this tx


    Returns bigint

abstractgetMessageToSign

  • getMessageToSign(hashMessage: false): Uint8Array | Uint8Array[]
  • getMessageToSign(hashMessage?: true): Uint8Array
  • Parameters

    • hashMessage: false

    Returns Uint8Array | Uint8Array[]

abstractgetMessageToVerifySignature

  • getMessageToVerifySignature(): Uint8Array
  • Returns Uint8Array

getSenderAddress

  • getSenderAddress(): Address
  • Returns the sender's address


    Returns Address

abstractgetSenderPublicKey

  • getSenderPublicKey(): Uint8Array
  • Returns the public key of the sender


    Returns Uint8Array

abstractgetUpfrontCost

  • getUpfrontCost(): bigint
  • The up front amount that an account must have for this transaction to be valid


    Returns bigint

abstracthash

  • hash(): Uint8Array
  • Returns Uint8Array

isSigned

  • isSigned(): boolean
  • Returns boolean

abstractraw

  • raw(): FeeMarketEIP1559ValuesArray | AccessListEIP2930ValuesArray | TxValuesArray
  • Returns a Uint8Array Array of the raw Uint8Arrays of this transaction, in order.

    Use BaseTransaction.serialize to add a transaction to a block with Block.fromValuesArray.

    For an unsigned tx this method uses the empty Uint8Array values for the signature parameters v, r and s for encoding. For an EIP-155 compliant representation for external signing use BaseTransaction.getMessageToSign.


    Returns FeeMarketEIP1559ValuesArray | AccessListEIP2930ValuesArray | TxValuesArray

abstractserialize

  • serialize(): Uint8Array
  • Returns the encoding of the transaction.


    Returns Uint8Array

sign

  • sign(privateKey: Uint8Array): TransactionObject
  • Signs a transaction.

    Note that the signed tx is returned as a new object, use as follows:

    const signedTx = tx.sign(privateKey)

    Parameters

    • privateKey: Uint8Array

    Returns TransactionObject

supports

  • supports(capability: Capability): boolean
  • 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.


    Parameters

    • capability: Capability

    Returns boolean

toCreationAddress

  • toCreationAddress(): boolean
  • If the tx's to is to the creation address


    Returns boolean

abstracttoJSON

  • toJSON(): JsonTx
  • Returns an object with the JSON representation of the transaction


    Returns JsonTx

validate

  • validate(): boolean
  • validate(stringError: false): boolean
  • validate(stringError: true): string[]
  • Checks if the transaction has the minimum amount of gas required (DataFee + TxFee + Creation Fee).


    Returns boolean

verifySignature

  • verifySignature(): boolean
  • Determines if the signature is valid


    Returns boolean

staticfromSerializedTx

  • fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): any
  • Parameters

    • serialized: Uint8Array
    • optionalopts: TxOptions

    Returns any

staticfromTxData

  • fromTxData(txData: any, opts?: TxOptions): any
  • Parameters

    • txData: any
    • optionalopts: TxOptions

    Returns any

Common

Common:

Common class to access chain and hardfork parameters and to provide a unified and shared view on the network and hardfork state.

Use the Common.custom static constructor for creating simple custom chain Common objects (more complete custom chain setups can be created via the main constructor and the CommonOpts.customChains parameter).

constructor

  • new Common(opts: CommonOpts): Common
  • Parameters

    • opts: CommonOpts

    Returns Common

readonlyDEFAULT_HARDFORK

DEFAULT_HARDFORK: string

_calcForkHash

  • _calcForkHash(hardfork: string, genesisHash: Uint8Array): string
  • Internal helper function to calculate a fork hash


    Parameters

    • hardfork: string

      Hardfork name

    • genesisHash: Uint8Array

      Genesis block hash of the chain

    Returns string

    Fork hash as hex string

_getHardfork

  • _getHardfork(hardfork: string): null | HardforkConfig
  • Internal helper function, returns the params for the given hardfork for the chain set


    Parameters

    • hardfork: string

      Hardfork name

    Returns null | HardforkConfig

    Dictionary with hardfork params or null if hardfork not on chain

activeOnBlock

  • activeOnBlock(blockNumber: Numbers): boolean
  • Alias to hardforkIsActiveOnBlock when hardfork is set


    Parameters

    Returns boolean

    True if HF is active on block number

bootstrapNodes

  • bootstrapNodes(): undefined | BootstrapNodeConfig[]
  • Returns bootstrap nodes for the current chain


    Returns undefined | BootstrapNodeConfig[]

    Dict with bootstrap nodes

chainId

  • chainId(): bigint
  • Returns the Id of current chain


    Returns bigint

    chain Id

chainName

  • chainName(): string
  • Returns the name of current chain


    Returns string

    chain name (lower case)

consensusAlgorithm

  • consensusAlgorithm(): string
  • Returns the concrete consensus implementation algorithm or protocol for the network e.g. "ethash" for "pow" consensus type, "clique" for "poa" consensus type or "casper" for "pos" consensus type.

    Note: This value can update along a Hardfork.


    Returns string

consensusConfig

  • consensusConfig(): {}
  • Returns a dictionary with consensus configuration parameters based on the consensus algorithm

    Expected returns (parameters must be present in the respective chain json files):

    ethash: empty object clique: period, epoch casper: empty object

    Note: This value can update along a Hardfork.


    Returns {}

    • [key string]: CliqueConfig | EthashConfig | CasperConfig

consensusType

  • consensusType(): string
  • Returns the consensus type of the network Possible values: "pow"|"poa"|"pos"

    Note: This value can update along a Hardfork.


    Returns string

copy

  • copy(): Common
  • Returns a deep copy of this Common instance.


    Returns Common

dnsNetworks

  • dnsNetworks(): string[]
  • Returns DNS networks for the current chain


    Returns string[]

    Array of DNS ENR urls

eipBlock

  • eipBlock(eip: number): null | bigint
  • Returns the hardfork change block for eip


    Parameters

    • eip: number

      EIP number

    Returns null | bigint

    Block number or null if unscheduled

eips

  • eips(): number[]
  • Returns the active EIPs


    Returns number[]

    List of EIPs

forkHash

  • forkHash(_hardfork?: string, genesisHash?: Uint8Array): string
  • Returns an eth/64 compliant fork hash (EIP-2124)


    Parameters

    • optional_hardfork: string
    • optionalgenesisHash: Uint8Array

      Genesis block hash of the chain, optional if already defined and not needed to be calculated

    Returns string

genesis

  • genesis(): GenesisBlockConfig
  • Returns the Genesis parameters of the current chain


    Returns GenesisBlockConfig

    Genesis dictionary

getHardforkByBlockNumber

  • getHardforkByBlockNumber(_blockNumber: Numbers, _td?: string | number | bigint, _timestamp?: string | number | bigint): string
  • Returns the hardfork based on the block number or an optional total difficulty (Merge HF) provided.

    An optional TD takes precedence in case the corresponding HF block is set to null or otherwise needs to match (if not an error will be thrown).


    Parameters

    • _blockNumber: Numbers
    • optional_td: string | number | bigint
    • optional_timestamp: string | number | bigint

    Returns string

    The name of the HF

getMaxListeners

  • getMaxListeners(): number
  • Returns number

gteHardfork

  • gteHardfork(hardfork: string): boolean
  • Alias to hardforkGteHardfork when hardfork is set


    Parameters

    • hardfork: string

      Hardfork name

    Returns boolean

    True if hardfork set is greater than hardfork provided

hardfork

  • hardfork(): string
  • Returns the hardfork set


    Returns string

    Hardfork name

hardforkBlock

  • hardforkBlock(_hardfork?: string): null | bigint
  • Returns the hardfork change block for hardfork provided or set


    Parameters

    • optional_hardfork: string

    Returns null | bigint

    Block number or null if unscheduled

hardforkForForkHash

  • hardforkForForkHash(forkHash: string): null | HardforkConfig

  • Parameters

    • forkHash: string

      Fork hash as a hex string

    Returns null | HardforkConfig

    Array with hardfork data (name, block, forkHash)

hardforkGteHardfork

  • hardforkGteHardfork(_hardfork1: null | string, hardfork2: string): boolean
  • Sequence based check if given or set HF1 is greater than or equal HF2


    Parameters

    • _hardfork1: null | string
    • hardfork2: string

      Hardfork name

    Returns boolean

    True if HF1 gte HF2

hardforkIsActiveOnBlock

  • hardforkIsActiveOnBlock(_hardfork: null | string, _blockNumber: Numbers): boolean
  • Checks if set or provided hardfork is active on block number


    Parameters

    • _hardfork: null | string
    • _blockNumber: Numbers

    Returns boolean

    True if HF is active on block number

hardforkTTD

  • hardforkTTD(_hardfork?: string): null | bigint
  • Returns the hardfork change total difficulty (Merge HF) for hardfork provided or set


    Parameters

    • optional_hardfork: string

    Returns null | bigint

    Total difficulty or null if no set

hardforkTimestamp

  • hardforkTimestamp(_hardfork?: string): null | bigint
  • Parameters

    • optional_hardfork: string

    Returns null | bigint

hardforks

  • hardforks(): HardforkConfig[]
  • Returns the hardforks for current chain


    Returns HardforkConfig[]

    Array with arrays of hardforks

isActivatedEIP

  • isActivatedEIP(eip: number): boolean
  • Checks if an EIP is activated by either being included in the EIPs manually passed in with the CommonOpts.eips or in a hardfork currently being active

    Note: this method only works for EIPs being supported by the CommonOpts.eips constructor option


    Parameters

    • eip: number

    Returns boolean

isHardforkBlock

  • isHardforkBlock(_blockNumber: Numbers, _hardfork?: string): boolean
  • True if block number provided is the hardfork (given or set) change block

    @deprecated

    Parameters

    • _blockNumber: Numbers
    • optional_hardfork: string

    Returns boolean

    True if blockNumber is HF block

isNextHardforkBlock

  • isNextHardforkBlock(_blockNumber: Numbers, _hardfork?: string): boolean
  • True if block number provided is the hardfork change block following the hardfork given or set

    @deprecated

    Parameters

    • _blockNumber: Numbers
    • optional_hardfork: string

    Returns boolean

    True if blockNumber is HF block

networkId

  • networkId(): bigint
  • Returns the Id of current network


    Returns bigint

    network Id

nextHardforkBlock

  • nextHardforkBlock(_hardfork?: string): null | bigint
  • Returns the change block for the next hardfork after the hardfork provided or set

    @deprecated

    Parameters

    • optional_hardfork: string

    Returns null | bigint

    Block number or null if not available

nextHardforkBlockOrTimestamp

  • nextHardforkBlockOrTimestamp(_hardfork?: string): null | bigint
  • Returns the change block for the next hardfork after the hardfork provided or set


    Parameters

    • optional_hardfork: string

    Returns null | bigint

    Block timestamp, number or null if not available

param

  • param(topic: string, name: string): bigint
  • Returns a parameter for the current chain setup

    If the parameter is present in an EIP, the EIP always takes precedence. Otherwise the parameter if taken from the latest applied HF with a change on the respective parameter.


    Parameters

    • topic: string

      Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow')

    • name: string

      Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic)

    Returns bigint

    The value requested or BigInt(0) if not found

paramByBlock

  • paramByBlock(topic: string, name: string, blockNumber: Numbers, td?: string | number | bigint, timestamp?: string | number | bigint): bigint
  • Returns a parameter for the hardfork active on block number or optional provided total difficulty (Merge HF)


    Parameters

    • topic: string

      Parameter topic

    • name: string

      Parameter name

    • blockNumber: Numbers

      Block number

    • optionaltd: string | number | bigint

      Total difficulty *

    • optionaltimestamp: string | number | bigint

    Returns bigint

    The value requested or BigInt(0) if not found

paramByEIP

  • paramByEIP(topic: string, name: string, eip: number): undefined | bigint
  • Returns a parameter corresponding to an EIP


    Parameters

    • topic: string

      Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow')

    • name: string

      Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic)

    • eip: number

      Number of the EIP

    Returns undefined | bigint

    The value requested or undefined if not found

paramByHardfork

  • paramByHardfork(topic: string, name: string, hardfork: string): bigint
  • Returns the parameter corresponding to a hardfork


    Parameters

    • topic: string

      Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow')

    • name: string

      Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic)

    • hardfork: string

      Hardfork name

    Returns bigint

    The value requested or BigInt(0) if not found

setChain

  • setChain(chain: string | number | bigint | object): ChainConfig
  • Sets the chain


    Parameters

    • chain: string | number | bigint | object

      String ('mainnet') or Number (1) chain representation. Or, a Dictionary of chain parameters for a private network.

    Returns ChainConfig

    The dictionary with parameters set as chain

setEIPs

  • setEIPs(eips?: number[]): void
  • Sets the active EIPs


    Parameters

    • optionaleips: number[]

    Returns void

setForkHashes

  • setForkHashes(genesisHash: Uint8Array): void
  • Sets any missing forkHashes on the passed-in Common instance


    Parameters

    • genesisHash: Uint8Array

      The genesis block hash

    Returns void

setHardfork

  • setHardfork(hardfork: string): void
  • Sets the hardfork to get params for


    Parameters

    • hardfork: string

      String identifier (e.g. 'byzantium') or Hardfork enum

    Returns void

setHardforkByBlockNumber

  • setHardforkByBlockNumber(blockNumber: Numbers, td?: string | number | bigint, timestamp?: string | number | bigint): string
  • Sets a new hardfork based on the block number or an optional total difficulty (Merge HF) provided.

    An optional TD takes precedence in case the corresponding HF block is set to null or otherwise needs to match (if not an error will be thrown).


    Parameters

    • blockNumber: Numbers
    • optionaltd: string | number | bigint
    • optionaltimestamp: string | number | bigint

    Returns string

    The name of the HF set

setMaxListeners

  • setMaxListeners(maxListeners: number): this
  • Parameters

    • maxListeners: number

    Returns this

static_getInitializedChains

  • _getInitializedChains(customChains?: ChainConfig[]): ChainsConfig
  • Parameters

    • optionalcustomChains: ChainConfig[]

    Returns ChainsConfig

staticcustom

  • custom(chainParamsOrName: Partial<ChainConfig> | PolygonMainnet | PolygonMumbai | ArbitrumRinkebyTestnet | ArbitrumOne | xDaiChain | OptimisticKovan | OptimisticEthereum, opts?: CustomCommonOpts): Common
  • Creates a Common object for a custom chain, based on a standard one.

    It uses all the Chain parameters from the baseChain option except the ones overridden in a provided chainParamsOrName dictionary. Some usage example:

    Common.custom({chainId: 123})

    There are also selected supported custom chains which can be initialized by using one of the CustomChains for chainParamsOrName, e.g.:

    Common.custom(CustomChains.MaticMumbai)

    Note that these supported custom chains only provide some base parameters (usually the chain and network ID and a name) and can only be used for selected use cases (e.g. sending a tx with the web3-utils/tx library to a Layer-2 chain).


    Parameters

    • chainParamsOrName: Partial<ChainConfig> | PolygonMainnet | PolygonMumbai | ArbitrumRinkebyTestnet | ArbitrumOne | xDaiChain | OptimisticKovan | OptimisticEthereum

      Custom parameter dict (name will default to custom-chain) or string with name of a supported custom chain

    • optionalopts: CustomCommonOpts

      Custom chain options to set the CustomCommonOpts.baseChain, selected CustomCommonOpts.hardfork and others

    Returns Common

staticfromGethGenesis

  • fromGethGenesis(genesisJson: any, to: GethConfigOpts): Common
  • Static method to load and set common from a geth genesis json


    Parameters

    • genesisJson: any

      json of geth configuration

    • to: GethConfigOpts

      further configure the common instance

    Returns Common

    Common

staticisSupportedChainId

  • isSupportedChainId(chainId: bigint): boolean
  • Static method to determine if a chainId is supported as a standard chain


    Parameters

    • chainId: bigint

      bigint id (1) of a standard chain

    Returns boolean

    boolean

FeeMarketEIP1559Transaction

FeeMarketEIP1559Transaction:

Typed transaction with a new gas fee market mechanism

constructor

  • new FeeMarketEIP1559Transaction(txData: FeeMarketEIP1559TxData, opts?: TxOptions): FeeMarketEIP1559Transaction
  • 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: FeeMarketEIP1559TxData
    • optionalopts: TxOptions

    Returns FeeMarketEIP1559Transaction

readonlyAccessListJSON

AccessListJSON: AccessList

readonlyaccessList

accessList: AccessListUint8Array

readonlychainId

chainId: bigint

readonlycommon

common: Common

readonlydata

data: Uint8Array

readonlygasLimit

gasLimit: bigint

readonlymaxFeePerGas

maxFeePerGas: bigint

readonlymaxPriorityFeePerGas

maxPriorityFeePerGas: bigint

readonlynonce

nonce: bigint

optionalreadonlyr

r?: bigint

optionalreadonlys

s?: bigint

optionalreadonlyto

to?: Address

optionalreadonlyv

v?: bigint

readonlyvalue

value: bigint

type

  • get type(): number
  • Returns the transaction type.

    Note: legacy txs will return tx type 0.


    Returns number

_processSignature

  • _processSignature(v: bigint, r: Uint8Array, s: Uint8Array): FeeMarketEIP1559Transaction
  • Parameters

    • v: bigint
    • r: Uint8Array
    • s: Uint8Array

    Returns FeeMarketEIP1559Transaction

errorStr

  • errorStr(): string
  • Return a compact error string representation of the object


    Returns string

getBaseFee

  • getBaseFee(): bigint
  • The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)


    Returns bigint

getDataFee

  • getDataFee(): bigint
  • The amount of gas paid for the data in this tx


    Returns bigint

getMessageToSign

  • getMessageToSign(hashMessage?: boolean): Uint8Array
  • 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.

    const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input

    Parameters

    • optionalhashMessage: boolean

      Return hashed message if set to true (default: true)

    Returns Uint8Array

getMessageToVerifySignature

  • getMessageToVerifySignature(): Uint8Array
  • Computes a sha3-256 hash which can be used to verify the signature


    Returns Uint8Array

getSenderAddress

  • getSenderAddress(): Address
  • Returns the sender's address


    Returns Address

getSenderPublicKey

  • getSenderPublicKey(): Uint8Array
  • Returns the public key of the sender


    Returns Uint8Array

getUpfrontCost

  • getUpfrontCost(baseFee?: bigint): bigint
  • The up front amount that an account must have for this transaction to be valid


    Parameters

    • optionalbaseFee: bigint

      The base fee of the block (will be set to 0 if not provided)

    Returns bigint

hash

  • hash(): Uint8Array
  • Computes a sha3-256 hash of the serialized tx.

    This method can only be used for signed txs (it throws otherwise). Use FeeMarketEIP1559Transaction.getMessageToSign to get a tx hash for the purpose of signing.


    Returns Uint8Array

isSigned

  • isSigned(): boolean
  • Returns boolean

raw

  • raw(): FeeMarketEIP1559ValuesArray
  • Returns a Uint8Array Array of the raw Uint8Arrays of the EIP-1559 transaction, in order.

    Format:

    [chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data,
    accessList, signatureYParity, signatureR, signatureS]

    Use FeeMarketEIP1559Transaction.serialize to add a transaction to a block with Block.fromValuesArray.

    For an unsigned tx this method uses the empty Uint8Array values for the signature parameters v, r and s for encoding. For an EIP-155 compliant representation for external signing use FeeMarketEIP1559Transaction.getMessageToSign.


    Returns FeeMarketEIP1559ValuesArray

serialize

  • serialize(): Uint8Array
  • Returns the serialized encoding of the EIP-1559 transaction.

    Format:

    0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data,
    accessList, signatureYParity, signatureR, signatureS])

    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.


    Returns Uint8Array

sign

  • sign(privateKey: Uint8Array): FeeMarketEIP1559Transaction
  • Signs a transaction.

    Note that the signed tx is returned as a new object, use as follows:

    const signedTx = tx.sign(privateKey)

    Parameters

    • privateKey: Uint8Array

    Returns FeeMarketEIP1559Transaction

supports

  • supports(capability: Capability): boolean
  • 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.


    Parameters

    • capability: Capability

    Returns boolean

toCreationAddress

  • toCreationAddress(): boolean
  • If the tx's to is to the creation address


    Returns boolean

toJSON

  • toJSON(): JsonTx
  • Returns an object with the JSON representation of the transaction


    Returns JsonTx

validate

  • validate(): boolean
  • validate(stringError: false): boolean
  • validate(stringError: true): string[]
  • Checks if the transaction has the minimum amount of gas required (DataFee + TxFee + Creation Fee).


    Returns boolean

verifySignature

  • verifySignature(): boolean
  • Determines if the signature is valid


    Returns boolean

staticfromSerializedTx

  • fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): FeeMarketEIP1559Transaction
  • Instantiate a transaction from the serialized tx.

    Format:

    0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data,
    accessList, signatureYParity, signatureR, signatureS])


    Parameters

    • serialized: Uint8Array
    • optionalopts: TxOptions

    Returns FeeMarketEIP1559Transaction

staticfromTxData

  • fromTxData(txData: FeeMarketEIP1559TxData, opts?: TxOptions): FeeMarketEIP1559Transaction
  • Instantiate a transaction from a data dictionary.

    Format: { chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, 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

    Parameters

    • txData: FeeMarketEIP1559TxData
    • optionalopts: TxOptions

    Returns FeeMarketEIP1559Transaction

staticfromValuesArray

  • fromValuesArray(values: FeeMarketEIP1559ValuesArray, opts?: TxOptions): FeeMarketEIP1559Transaction
  • Create a transaction from a values array.

    Format:

    [chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data,
    accessList, signatureYParity, signatureR, signatureS]


    Parameters

    • values: FeeMarketEIP1559ValuesArray
    • optionalopts: TxOptions

    Returns FeeMarketEIP1559Transaction

Transaction

Transaction:

An Ethereum non-typed (legacy) transaction

constructor

  • new Transaction(txData: TxData, opts?: TxOptions): Transaction
  • 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
    • optionalopts: TxOptions

    Returns Transaction

readonlycommon

common: Common

readonlydata

data: Uint8Array

readonlygasLimit

gasLimit: bigint

readonlygasPrice

gasPrice: bigint

readonlynonce

nonce: bigint

optionalreadonlyr

r?: bigint

optionalreadonlys

s?: bigint

optionalreadonlyto

to?: Address

optionalreadonlyv

v?: bigint

readonlyvalue

value: bigint

type

  • get type(): number
  • Returns the transaction type.

    Note: legacy txs will return tx type 0.


    Returns number

errorStr

  • errorStr(): string
  • Return a compact error string representation of the object


    Returns string

getBaseFee

  • getBaseFee(): bigint
  • The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)


    Returns bigint

getDataFee

  • getDataFee(): bigint
  • The amount of gas paid for the data in this tx


    Returns bigint

getMessageToSign

  • getMessageToSign(hashMessage: false): Uint8Array[]
  • getMessageToSign(hashMessage?: true): Uint8Array
  • Returns the unsigned tx (hashed or raw), which can be used to sign the transaction (e.g. for sending to a hardware wallet).

    Note: the raw message message format for the legacy tx is not RLP encoded and you might need to do yourself with:

    import { bufArrToArr } from '../util'
    import { RLP } from '../rlp'
    const message = tx.getMessageToSign(false)
    const serializedMessage = RLP.encode(message) // use this for the HW wallet input

    Parameters

    • hashMessage: false

      Return hashed message if set to true (default: true)

    Returns Uint8Array[]

getMessageToVerifySignature

  • getMessageToVerifySignature(): Uint8Array
  • Computes a sha3-256 hash which can be used to verify the signature


    Returns Uint8Array

getSenderAddress

  • getSenderAddress(): Address
  • Returns the sender's address


    Returns Address

getSenderPublicKey

  • getSenderPublicKey(): Uint8Array
  • Returns the public key of the sender


    Returns Uint8Array

getUpfrontCost

  • getUpfrontCost(): bigint
  • The up front amount that an account must have for this transaction to be valid


    Returns bigint

hash

  • hash(): Uint8Array
  • Computes a sha3-256 hash of the serialized tx.

    This method can only be used for signed txs (it throws otherwise). Use Transaction.getMessageToSign to get a tx hash for the purpose of signing.


    Returns Uint8Array

isSigned

  • isSigned(): boolean
  • Returns boolean

raw

  • raw(): TxValuesArray
  • Returns a Uint8Array Array of the raw Uint8Arrays of the legacy transaction, in order.

    Format: [nonce, gasPrice, gasLimit, to, value, data, v, r, s]

    For legacy txs this is also the correct format to add transactions to a block with Block.fromValuesArray (use the serialize() method for typed txs).

    For an unsigned tx this method returns the empty Uint8Array values for the signature parameters v, r and s. For an EIP-155 compliant representation have a look at Transaction.getMessageToSign.


    Returns TxValuesArray

serialize

  • serialize(): Uint8Array
  • Returns the serialized encoding of the legacy transaction.

    Format: rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])

    For an unsigned tx this method uses the empty Uint8Array values for the signature parameters v, r and s for encoding. For an EIP-155 compliant representation for external signing use Transaction.getMessageToSign.


    Returns Uint8Array

sign

  • sign(privateKey: Uint8Array): Transaction
  • Signs a transaction.

    Note that the signed tx is returned as a new object, use as follows:

    const signedTx = tx.sign(privateKey)

    Parameters

    • privateKey: Uint8Array

    Returns Transaction

supports

  • supports(capability: Capability): boolean
  • 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.


    Parameters

    • capability: Capability

    Returns boolean

toCreationAddress

  • toCreationAddress(): boolean
  • If the tx's to is to the creation address


    Returns boolean

toJSON

  • toJSON(): JsonTx
  • Returns an object with the JSON representation of the transaction.


    Returns JsonTx

validate

  • validate(): boolean
  • validate(stringError: false): boolean
  • validate(stringError: true): string[]
  • Checks if the transaction has the minimum amount of gas required (DataFee + TxFee + Creation Fee).


    Returns boolean

verifySignature

  • verifySignature(): boolean
  • Determines if the signature is valid


    Returns boolean

staticfromSerializedTx

  • fromSerializedTx(serialized: Uint8Array, opts?: TxOptions): Transaction
  • Instantiate a transaction from the serialized tx.

    Format: rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])


    Parameters

    • serialized: Uint8Array
    • optionalopts: TxOptions

    Returns Transaction

staticfromTxData

  • fromTxData(txData: TxData, opts?: TxOptions): Transaction
  • Instantiate a transaction from a data dictionary.

    Format: { nonce, gasPrice, gasLimit, to, value, data, v, r, s }

    Notes:

    • All parameters are optional and have some basic default values

    Parameters

    • txData: TxData
    • optionalopts: TxOptions

    Returns Transaction

staticfromValuesArray

  • fromValuesArray(values: TxValuesArray, opts?: TxOptions): Transaction
  • Create a transaction from a values array.

    Format: [nonce, gasPrice, gasLimit, to, value, data, v, r, s]


    Parameters

    • values: TxValuesArray
    • optionalopts: TxOptions

    Returns Transaction

TransactionFactory

TransactionFactory:

staticfromBlockBodyData

  • fromBlockBodyData(data: Uint8Array | Uint8Array[], txOptions?: TxOptions): TypedTransaction
  • When decoding a BlockBody, in the transactions field, a field is either: A Uint8Array (a TypedTransaction - encoded as TransactionType || rlp(TransactionPayload)) A Uint8Array[] (Legacy Transaction) This method returns the right transaction.


    Parameters

    • data: Uint8Array | Uint8Array[]

      A Uint8Array or Uint8Array[]

    • optionaltxOptions: TxOptions

      The transaction options

    Returns TypedTransaction

staticfromSerializedData

  • fromSerializedData(data: Uint8Array, txOptions?: TxOptions): TypedTransaction
  • This method tries to decode serialized data.


    Parameters

    • data: Uint8Array

      The data Uint8Array

    • optionaltxOptions: TxOptions

      The transaction options

    Returns TypedTransaction

staticfromTxData

  • fromTxData(txData: TxData | Transaction | AccessListEIP2930Transaction | FeeMarketEIP1559Transaction, txOptions?: TxOptions): TypedTransaction
  • Create a transaction from a txData object


    Parameters

    • txData: TxData | Transaction | AccessListEIP2930Transaction | FeeMarketEIP1559Transaction

      The transaction data. The type field will determine which transaction type is returned (if undefined, creates a legacy transaction)

    • optionaltxOptions: TxOptions

      Options to pass on to the constructor of the transaction

    Returns TypedTransaction

staticregisterTransactionType

  • registerTransactionType<NewTxTypeClass>(type: Numbers, txClass: NewTxTypeClass): void
  • Type parameters

    • NewTxTypeClass: { prototype: BaseTransaction<any>; fromSerializedTx: any; fromTxData: any }

    Parameters

    • type: Numbers
    • txClass: NewTxTypeClass

    Returns void

statictypeToInt

  • Parameters

    Returns number

Wallet

Wallet<T>:

Wallet is an in memory wallet that can hold multiple accounts. These accounts can be used when using web3.eth.sendTransaction() or web3.eth.contract.methods.contractfunction().send();

For using Wallet functionality, install Web3 package using npm i web3 or yarn add web3. After that, Wallet functionality will be available as mentioned below.

import { Web3 } from 'web3';
const web3 = new Web3('http://127.0.0.1:7545');

const wallet = await web3.eth.accounts.wallet.create(2);

const signature = wallet.at(0).sign("Test Data"); // use wallet

// fund account before sending following transaction ...

const receipt = await web3.eth.sendTransaction({ // internally sign transaction using wallet
from: wallet.at(0).address,
to: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
value: 1
//....
});

constructor

add

  • add(account: string | T): this
  • Adds an account using a private key or account object to the wallet.


    Parameters

    • account: string | T

      A private key or account object

    Returns this

    The wallet

    web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387');
    > Wallet(1) [
    {
    address: '0x85D70633b90e03e0276B98880286D0D055685ed7',
    privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [Function: encrypt]
    },
    _accountProvider: {
    create: [Function: create],
    privateKeyToAccount: [Function: privateKeyToAccount],
    decrypt: [Function: decrypt]
    },
    _addressMap: Map(1) { '0x85d70633b90e03e0276b98880286d0d055685ed7' => 0 },
    _defaultKeyName: 'web3js_wallet'
    ]

clear

  • clear(): this
  • Securely empties the wallet and removes all its accounts. Use this with *caution as it will remove all accounts stored in local wallet.


    Returns this

    The wallet object


    web3.eth.accounts.wallet.clear();
    > Wallet(0) [
    _accountProvider: {
    create: [Function: create],
    privateKeyToAccount: [Function: privateKeyToAccount],
    decrypt: [Function: decrypt]
    },
    _addressMap: Map(0) {},
    _defaultKeyName: 'web3js_wallet'
    ]

create

  • create(numberOfAccounts: number): this
  • Generates one or more accounts in the wallet. If wallets already exist they will not be overridden.


    Parameters

    • numberOfAccounts: number

      Number of accounts to create. Leave empty to create an empty wallet.

    Returns this

    The wallet

    web3.eth.accounts.wallet.create(2)
    > Wallet(2) [
    {
    address: '0xde38310a42B751AE57d30cFFF4a0A3c52A442fCE',
    privateKey: '0x6422c9d28efdcbee93c1d32a5fc6fd6fa081b985487885296cf8c9bbb5872600',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [Function: encrypt]
    },
    {
    address: '0x766BF755246d924B1d017Fdb5390f38a60166691',
    privateKey: '0x756530f13c0eb636ebdda655335f5dea9921e3362e2e588b0ad59e556f7751f0',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [Function: encrypt]
    },
    _accountProvider: {
    create: [Function: create],
    privateKeyToAccount: [Function: privateKeyToAccount],
    decrypt: [Function: decrypt]
    },
    _addressMap: Map(2) {
    '0xde38310a42b751ae57d30cfff4a0a3c52a442fce' => 0,
    '0x766bf755246d924b1d017fdb5390f38a60166691' => 1
    },
    _defaultKeyName: 'web3js_wallet'
    ]

decrypt

  • decrypt(encryptedWallets: KeyStore[], password: string, options?: Record<string, unknown>): Promise<Wallet<T>>
  • Decrypts keystore v3 objects.


    Parameters

    • encryptedWallets: KeyStore[]

      An array of encrypted keystore v3 objects to decrypt

    • password: string

      The password to encrypt with

    • optionaloptions: Record<string, unknown>

      decrypt options for the wallets

    Returns Promise<Wallet<T>>

    The decrypted wallet object

    web3.eth.accounts.wallet.decrypt([
    { version: 3,
    id: '83191a81-aaca-451f-b63d-0c5f3b849289',
    address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
    crypto:
    { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d',
    cipherparams: { iv: '497f4d26997a84d570778eae874b2333' },
    cipher: 'aes-128-ctr',
    kdf: 'scrypt',
    kdfparams:
    { dklen: 32,
    salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d',
    n: 262144,
    r: 8,
    p: 1 },
    mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } },
    { version: 3,
    id: '7d6b91fa-3611-407b-b16b-396efb28f97e',
    address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
    crypto:
    { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43',
    cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' },
    cipher: 'aes-128-ctr',
    kdf: 'scrypt',
    kdfparams:
    { dklen: 32,
    salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8',
    n: 262144,
    r: 8,
    p: 1 },
    mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } }
    ], 'test').then(console.log)
    > Wallet {
    _accountProvider: {
    create: [Function: create],
    privateKeyToAccount: [Function: privateKeyToAccount],
    decrypt: [Function: decrypt]
    },
    _defaultKeyName: 'web3js_wallet',
    _accounts: {
    '0x85d70633b90e03e0276b98880286d0d055685ed7': {
    address: '0x85D70633b90e03e0276B98880286D0D055685ed7',
    privateKey: '0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [Function: encrypt]
    },
    '0x06f702337909c06c82b09b7a22f0a2f0855d1f68': {
    address: '0x06F702337909C06C82B09B7A22F0a2f0855d1F68',
    privateKey: '87a51da18900da7398b3bab03996833138f269f8f66dd1237b98df6b9ce14573',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [Function: encrypt]
    },
    '0xb5d89661b59a9af0b34f58d19138baa2de48baaf': {
    address: '0xB5d89661B59a9aF0b34f58D19138bAa2de48BAaf',
    privateKey: '7ee61c5282979aae9dd795bb6a54e8bdc2bfe009acb64eb9a67322eec3b3da6e',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [Function: encrypt]
    }
    }
    }

encrypt

  • encrypt(password: string, options?: Record<string, unknown>): Promise<KeyStore[]>
  • Encrypts all wallet accounts to an array of encrypted keystore v3 objects.


    Parameters

    • password: string

      The password which will be used for encryption

    • optionaloptions: Record<string, unknown>

      encryption options

    Returns Promise<KeyStore[]>

    An array of the encrypted keystore v3.

    web3.eth.accounts.wallet.create(1)
    web3.eth.accounts.wallet.encrypt("abc").then(console.log);
    > [
    '{"version":3,"id":"fa46e213-a7c3-4844-b903-dd14d39cc7db",
    "address":"fa3e41a401609103c241431cbdee8623ae2a321a","crypto":
    {"ciphertext":"8d179a911d6146ad2924e86bf493ed89b8ff3596ffec0816e761c542016ab13c",
    "cipherparams":{"iv":"acc888c6cf4a19b86846cef0185a7164"},"cipher":"aes-128-ctr",
    "kdf":"scrypt","kdfparams":{"n":8192,"r":8,"p":1,"dklen":32,"salt":"6a743c9b367d15f4758e4f3f3378ff0fd443708d1c64854e07588ea5331823ae"},
    "mac":"410544c8307e3691fda305eb3722d82c3431f212a87daa119a21587d96698b57"}}'
    ]

get

  • get(addressOrIndex: string | number): undefined | T
  • Get the account of the wallet with either the index or public address.


    Parameters

    • addressOrIndex: string | number

      A string of the address or number index within the wallet.

    Returns undefined | T

    The account object or undefined if the account doesn't exist

load

  • load(password: string, keyName?: string): Promise<Wallet<T>>
  • Loads a wallet from local storage and decrypts it. NOTE: Browser only


    Parameters

    • password: string

      The password to decrypt the wallet.

    • optionalkeyName: string

      (optional)The key used for local storage position, defaults to web3js_wallet"

    Returns Promise<Wallet<T>>

    Returns the wallet object

    web3.eth.accounts.wallet.save('test#!$');
    > true
    web3.eth.accounts.wallet.load('test#!$');
    { defaultKeyName: "web3js_wallet",
    length: 0,
    _accounts: Accounts {_requestManager: RequestManager, givenProvider: Proxy, providers: {}, _provider: WebsocketProvider,},
    [[Prototype]]: Object
    }

remove

  • remove(addressOrIndex: string | number): boolean
  • Removes an account from the wallet.


    Parameters

    • addressOrIndex: string | number

      The account address, or index in the wallet.

    Returns boolean

    true if the wallet was removed. false if it couldn't be found.

    web3.eth.accounts.wallet.add('0xbce9b59981303e76c4878b1a6d7b088ec6b9dd5c966b7d5f54d7a749ff683387');

    web3.eth.accounts.wallet.remove('0x85D70633b90e03e0276B98880286D0D055685ed7');
    > true
    web3.eth.accounts.wallet
    > Wallet(0) [
    _accountProvider: {
    create: [Function: create],
    privateKeyToAccount: [Function: privateKeyToAccount],
    decrypt: [Function: decrypt]
    },
    _addressMap: Map(0) {},
    _defaultKeyName: 'web3js_wallet'
    ]

save

  • save(password: string, keyName?: string): Promise<boolean>
  • Stores the wallet encrypted and as string in local storage. NOTE: Browser only


    Parameters

    • password: string

      The password to encrypt the wallet

    • optionalkeyName: string

      (optional) The key used for the local storage position, defaults to "web3js_wallet".

    Returns Promise<boolean>

    Will return boolean value true if saved properly

    web3.eth.accounts.wallet.save('test#!$');
    >true

staticgetStorage

  • getStorage(): undefined | WebStorage
  • Get the storage object of the browser


    Returns undefined | WebStorage

    the storage

AccessListEIP2930TxData

AccessListEIP2930TxData:

AccessListEIP2930Transaction data.

optionalaccessList

accessList?: null | AccessListUint8Array | AccessList

The access list which contains the addresses/storage slots which the transaction wishes to access

optionalchainId

chainId?: string | number | bigint

The transaction's chain ID

optionaldata

data?: string | number | bigint | Uint8Array | number[]

This will contain the data of the message or the init of a contract.

optionalgasLimit

gasLimit?: string | number | bigint | Uint8Array

The transaction's gas limit.

optionalgasPrice

gasPrice?: null | string | number | bigint | Uint8Array

The transaction's gas price.

optionalnonce

nonce?: string | number | bigint | Uint8Array

The transaction's nonce.

optionalr

r?: string | number | bigint | Uint8Array

EC signature parameter.

optionals

s?: string | number | bigint | Uint8Array

EC signature parameter.

optionalto

to?: string | Uint8Array | Address

The transaction's the address is sent to.

optionaltype

type?: string | number | bigint

The transaction type

optionalv

v?: string | number | bigint | Uint8Array

EC recovery ID.

optionalvalue

value?: string | number | bigint | Uint8Array

The amount of Ether sent.

BootstrapNodeConfig

BootstrapNodeConfig:

optionalchainId

chainId?: number

comment

comment: string

id

id: string

ip

ip: string

location

location: string

optionalnetwork

network?: string

port

port: string | number

ChainConfig

ChainConfig:

optionalbootstrapNodes

bootstrapNodes?: BootstrapNodeConfig[]

chainId

chainId: number | bigint

optionalcomment

comment?: string

consensus

consensus: { algorithm: string; casper?: CasperConfig; clique?: CliqueConfig; ethash?: EthashConfig; type: string }

Type declaration

  • algorithm: string
  • optionalcasper?: CasperConfig
  • optionalclique?: CliqueConfig
  • optionalethash?: EthashConfig
  • type: string

optionaldefaultHardfork

defaultHardfork?: string

optionaldnsNetworks

dnsNetworks?: string[]

genesis

genesis: GenesisBlockConfig

hardforks

hardforks: HardforkConfig[]

name

name: string

networkId

networkId: number | bigint

optionalurl

url?: string

ChainName

ChainName:

ChainsConfig

ChainsConfig:

CommonOpts

CommonOpts:

Options for instantiating a Common instance.

chain

chain: string | number | bigint | object

Chain name ('mainnet'), id (1), or Chain enum, either from a chain directly supported or a custom chain passed in via CommonOpts.customChains.

optionalcustomChains

customChains?: ChainConfig[]

Initialize (in addition to the supported chains) with the selected custom chains. Custom genesis state should be passed to the Blockchain class if used.

Usage (directly with the respective chain initialization via the CommonOpts.chain option):

import myCustomChain1 from '[PATH_TO_MY_CHAINS]/myCustomChain1.json'
const common = new Common({ chain: 'myCustomChain1', customChains: [ myCustomChain1 ]})

optionaleips

eips?: number[]

Selected EIPs which can be activated, please use an array for instantiation (e.g. eips: [ 2537, ])

Currently supported:

optionalhardfork

hardfork?: string

String identifier ('byzantium') for hardfork or Hardfork enum.

Default: Hardfork.London

CustomCommonOpts

CustomCommonOpts:

Options to be used with the Common.custom static constructor.

optionalbaseChain

baseChain?: string | number | bigint

The name (mainnet), id (1), or Chain enum of a standard chain used to base the custom chain params on.

optionaleips

eips?: number[]

Selected EIPs which can be activated, please use an array for instantiation (e.g. eips: [ 2537, ])

Currently supported:

optionalhardfork

hardfork?: string

String identifier ('byzantium') for hardfork or Hardfork enum.

Default: Hardfork.London

ECDSASignature

ECDSASignature:

r

r: Uint8Array

s

s: Uint8Array

v

v: bigint

FeeMarketEIP1559TxData

FeeMarketEIP1559TxData:

FeeMarketEIP1559Transaction data.

optionalaccessList

accessList?: null | AccessListUint8Array | AccessList

The access list which contains the addresses/storage slots which the transaction wishes to access

optionalchainId

chainId?: string | number | bigint

The transaction's chain ID

optionaldata

data?: string | number | bigint | Uint8Array | number[]

This will contain the data of the message or the init of a contract.

optionalgasLimit

gasLimit?: string | number | bigint | Uint8Array

The transaction's gas limit.

optionalgasPrice

gasPrice?: null

The transaction's gas price, inherited from Transaction. This property is not used for EIP1559 transactions and should always be undefined for this specific transaction type.

optionalmaxFeePerGas

maxFeePerGas?: string | number | bigint | Uint8Array

The maximum total fee

optionalmaxPriorityFeePerGas

maxPriorityFeePerGas?: string | number | bigint | Uint8Array

The maximum inclusion fee per gas (this fee is given to the miner)

optionalnonce

nonce?: string | number | bigint | Uint8Array

The transaction's nonce.

optionalr

r?: string | number | bigint | Uint8Array

EC signature parameter.

optionals

s?: string | number | bigint | Uint8Array

EC signature parameter.

optionalto

to?: string | Uint8Array | Address

The transaction's the address is sent to.

optionaltype

type?: string | number | bigint

The transaction type

optionalv

v?: string | number | bigint | Uint8Array

EC recovery ID.

optionalvalue

value?: string | number | bigint | Uint8Array

The amount of Ether sent.

GenesisBlockConfig

GenesisBlockConfig:

optionalbaseFeePerGas

baseFeePerGas?: string

difficulty

difficulty: number

extraData

extraData: string

gasLimit

gasLimit: number

nonce

nonce: string

optionaltimestamp

timestamp?: string

GethConfigOpts

GethConfigOpts:

optionalchain

chain?: string

optionaleips

eips?: number[]

Selected EIPs which can be activated, please use an array for instantiation (e.g. eips: [ 2537, ])

Currently supported:

optionalgenesisHash

genesisHash?: Uint8Array

optionalhardfork

hardfork?: string

String identifier ('byzantium') for hardfork or Hardfork enum.

Default: Hardfork.London

optionalmergeForkIdPostMerge

mergeForkIdPostMerge?: boolean

HardforkConfig

HardforkConfig:

block

block: null | number

optionalforkHash

forkHash?: null | string

name

name: string

optionaltimestamp

timestamp?: string | number

optionalttd

ttd?: string | bigint

JsonTx

JsonTx:

Generic interface for all tx types with a JSON representation of a transaction.

Note that all values are marked as optional and not all the values are present on all tx types (an EIP1559 tx e.g. lacks a gasPrice).

optionalaccessList

accessList?: JsonAccessListItem[]

optionalchainId

chainId?: string

optionaldata

data?: string

optionalgasLimit

gasLimit?: string

optionalgasPrice

gasPrice?: string

optionalmaxFeePerDataGas

maxFeePerDataGas?: string

optionalmaxFeePerGas

maxFeePerGas?: string

optionalmaxPriorityFeePerGas

maxPriorityFeePerGas?: string

optionalnonce

nonce?: string

optionalr

r?: string

optionals

s?: string

optionalto

to?: string

optionaltype

type?: string

optionalv

v?: string

optionalvalue

value?: string

optionalversionedHashes

versionedHashes?: string[]

TransformableToArray

TransformableToArray:

toArray

  • toArray(): Uint8Array
  • Returns Uint8Array

TxOptions

TxOptions:

The options for initializing a Transaction.

optionalallowUnlimitedInitCodeSize

allowUnlimitedInitCodeSize?: boolean

Allows unlimited contract code-size init while debugging. This (partially) disables EIP-3860. Gas cost for initcode size analysis will still be charged. Use with caution.

optionalcommon

common?: Common

A Common object defining the chain and hardfork for the transaction.

Object will be internally copied so that tx behavior don't incidentally change on future HF changes.

Default: Common object set to mainnet and the default hardfork as defined in the Common class.

Current default hardfork: istanbul

optionalfreeze

freeze?: boolean

A transaction object by default gets frozen along initialization. This gives you strong additional security guarantees on the consistency of the tx parameters. It also enables tx hash caching when the hash() method is called multiple times.

If you need to deactivate the tx freeze - e.g. because you want to subclass tx and add additional properties - it is strongly encouraged that you do the freeze yourself within your code instead.

Default: true

Web3Account

Web3Account:

address

address: string

readonlyencrypt

encrypt: (password: string, options?: Record<string, unknown>) => Promise<KeyStore>

Type declaration

    • (password: string, options?: Record<string, unknown>): Promise<KeyStore>
    • Parameters

      • password: string
      • optionaloptions: Record<string, unknown>

      Returns Promise<KeyStore>

privateKey

privateKey: string

readonlysign

sign: (data: string | Record<string, unknown>) => { message?: string; messageHash: string; r: string; s: string; signature: string; v: string }

Type declaration

    • (data: string | Record<string, unknown>): { message?: string; messageHash: string; r: string; s: string; signature: string; v: string }
    • Parameters

      • data: string | Record<string, unknown>

      Returns { message?: string; messageHash: string; r: string; s: string; signature: string; v: string }

      • optionalreadonlymessage?: string
      • readonlymessageHash: string
      • readonlyr: string
      • readonlys: string
      • readonlysignature: string
      • readonlyv: string

readonlysignTransaction

signTransaction: (tx: Transaction) => Promise<{ messageHash: string; r: string; rawTransaction: string; s: string; transactionHash: string; v: string }>

Type declaration

    • (tx: Transaction): Promise<{ messageHash: string; r: string; rawTransaction: string; s: string; transactionHash: string; v: string }>
    • Parameters

      Returns Promise<{ messageHash: string; r: string; rawTransaction: string; s: string; transactionHash: string; v: string }>

WebStorage

WebStorage:

This Web Storage API interface provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

readonlylength

length: number

Returns the number of key/value pairs.

clear

  • clear(): void
  • Removes all key/value pairs, if there are any.

    Dispatches a storage event on Window objects holding an equivalent Storage object.


    Returns void

getItem

  • getItem(key: string): null | string
  • Returns the current value associated with the given key, or null if the given key does not exist.


    Parameters

    • key: string

    Returns null | string

key

  • key(index: number): null | string
  • Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs.


    Parameters

    • index: number

    Returns null | string

removeItem

  • removeItem(key: string): void
  • Removes the key/value pair with the given key, if a key/value pair with the given key exists.

    Dispatches a storage event on Window objects holding an equivalent Storage object.


    Parameters

    • key: string

    Returns void

setItem

  • setItem(key: string, value: string): void
  • Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.

    Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)

    Dispatches a storage event on Window objects holding an equivalent Storage object.


    Parameters

    • key: string
    • value: string

    Returns void

AccessList

AccessList: AccessListItem[]

AccessListEIP2930ValuesArray

AccessListEIP2930ValuesArray: [Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, AccessListUint8Array, Uint8Array?, Uint8Array?, Uint8Array?]

Uint8Array values array for an AccessListEIP2930Transaction

AccessListItem

AccessListItem: { address: PrefixedHexString; storageKeys: PrefixedHexString[] }

Type declaration

  • address: PrefixedHexString
  • storageKeys: PrefixedHexString[]

AccessListUint8Array

AccessListUint8Array: AccessListUint8ArrayItem[]

AccessListUint8ArrayItem

AccessListUint8ArrayItem: [Uint8Array, Uint8Array[]]

BigIntLike

BigIntLike: bigint | PrefixedHexString | number | Uint8Array

CasperConfig

CasperConfig: Record<string, unknown>

CliqueConfig

CliqueConfig: { epoch: number; period: number }

Type declaration

  • epoch: number
  • period: number

EthashConfig

EthashConfig: Record<string, unknown>

FeeMarketEIP1559ValuesArray

FeeMarketEIP1559ValuesArray: [Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, Uint8Array, AccessListUint8Array, Uint8Array?, Uint8Array?, Uint8Array?]

Uint8Array values array for a FeeMarketEIP1559Transaction

NestedUint8Array

NestedUint8Array: (Uint8Array | NestedUint8Array)[]

PrefixedHexString

PrefixedHexString: string

SignFunction

SignFunction: (data: string, privateKey: string) => SignResult

Type declaration

    • (data: string, privateKey: string): SignResult
    • Parameters

      • data: string
      • privateKey: string

      Returns SignResult

SignResult

SignResult: SignatureObject & { message?: string; signature: string }

SignTransactionFunction

SignTransactionFunction: (transaction: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData | Record<string, unknown>) => SignTransactionResult

Type declaration

    • (transaction: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData | Record<string, unknown>): SignTransactionResult
    • Parameters

      • transaction: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData | Record<string, unknown>

      Returns SignTransactionResult

SignTransactionResult

SignTransactionResult: SignatureObject & { rawTransaction: string; transactionHash: string }

SignatureObject

SignatureObject: { messageHash: string; r: string; s: string; v: string }

Type declaration

  • messageHash: string
  • r: string
  • s: string
  • v: string

ToBytesInputTypes

ToBytesInputTypes: PrefixedHexString | number | bigint | Uint8Array | number[] | TransformableToArray | null | undefined

TxData

TxData: { data?: Uint8ArrayLike; gasLimit?: Numbers | Uint8Array; gasPrice?: Numbers | Uint8Array | null; nonce?: Numbers | Uint8Array; r?: Numbers | Uint8Array; s?: Numbers | Uint8Array; to?: Address | Uint8Array | HexString; type?: Numbers; v?: Numbers | Uint8Array; value?: Numbers | Uint8Array }

Legacy Transaction Data


Type declaration

  • optionaldata?: Uint8ArrayLike

    This will contain the data of the message or the init of a contract.

  • optionalgasLimit?: Numbers | Uint8Array

    The transaction's gas limit.

  • optionalgasPrice?: Numbers | Uint8Array | null

    The transaction's gas price.

  • optionalnonce?: Numbers | Uint8Array

    The transaction's nonce.

  • optionalr?: Numbers | Uint8Array

    EC signature parameter.

  • optionals?: Numbers | Uint8Array

    EC signature parameter.

  • optionalto?: Address | Uint8Array | HexString

    The transaction's the address is sent to.

  • optionaltype?: Numbers

    The transaction type

  • optionalv?: Numbers | Uint8Array

    EC recovery ID.

  • optionalvalue?: Numbers | Uint8Array

    The amount of Ether sent.

TxValuesArray

TxValuesArray: Uint8Array[]

Uint8Array values array for a legacy Transaction

TypeOutputReturnType

TypeOutputReturnType: { 0: number; 1: bigint; 2: Uint8Array; 3: PrefixedHexString }

Type declaration

  • 0: number
  • 1: bigint
  • 2: Uint8Array
  • 3: PrefixedHexString

TypedTransaction

TypedTransaction: Transaction | AccessListEIP2930Transaction | FeeMarketEIP1559Transaction

Uint8ArrayLike

Uint8ArrayLike: Uint8Array | number[] | number | bigint | PrefixedHexString

constkeyStoreSchema

keyStoreSchema: { properties: { address: { type: string }; crypto: { properties: { cipher: { type: string }; cipherparams: { type: string }; ciphertext: { type: string }; kdf: { type: string }; kdfparams: { type: string }; mac: { type: string }; salt: { type: string } }; required: string[]; type: string }; id: { type: string }; version: { type: string } }; required: string[]; type: string }

Type declaration

  • properties: { address: { type: string }; crypto: { properties: { cipher: { type: string }; cipherparams: { type: string }; ciphertext: { type: string }; kdf: { type: string }; kdfparams: { type: string }; mac: { type: string }; salt: { type: string } }; required: string[]; type: string }; id: { type: string }; version: { type: string } }
    • address: { type: string }
      • type: string
    • crypto: { properties: { cipher: { type: string }; cipherparams: { type: string }; ciphertext: { type: string }; kdf: { type: string }; kdfparams: { type: string }; mac: { type: string }; salt: { type: string } }; required: string[]; type: string }
      • properties: { cipher: { type: string }; cipherparams: { type: string }; ciphertext: { type: string }; kdf: { type: string }; kdfparams: { type: string }; mac: { type: string }; salt: { type: string } }
        • cipher: { type: string }
          • type: string
        • cipherparams: { type: string }
          • type: string
        • ciphertext: { type: string }
          • type: string
        • kdf: { type: string }
          • type: string
        • kdfparams: { type: string }
          • type: string
        • mac: { type: string }
          • type: string
        • salt: { type: string }
          • type: string
      • required: string[]
      • type: string
    • id: { type: string }
      • type: string
    • version: { type: string }
      • type: string
  • required: string[]
  • type: string

assertIsUint8Array

  • assertIsUint8Array(input: unknown): asserts input is Uint8Array
  • Throws if input is not a Uint8Array


    Parameters

    • input: unknown

      value to check

    Returns asserts input is Uint8Array

bigIntToHex

  • bigIntToHex(num: bigint): string
  • Converts a bigint to a 0x prefixed hex string


    Parameters

    • num: bigint

    Returns string

bigIntToUint8Array

  • bigIntToUint8Array(num: bigint): Uint8Array
  • Converts a bigint to a Uint8Array


    Parameters

    • num: bigint

    Returns Uint8Array

bigIntToUnpaddedUint8Array

  • bigIntToUnpaddedUint8Array(value: bigint): Uint8Array
  • Convert value from bigint to an unpadded Uint8Array (useful for RLP transport)


    Parameters

    • value: bigint

      value to convert

    Returns Uint8Array

create

  • create(): Web3Account
  • Generates and returns a Web3Account object that includes the private and public key For creation of private key, it uses an audited package ethereum-cryptography/secp256k1 that is cryptographically secure random number with certain characteristics. Read more: https://www.npmjs.com/package/ethereum-cryptography#secp256k1-curve


    Returns Web3Account

    A Web3Account object

    web3.eth.accounts.create();
    {
    address: '0xbD504f977021b5E5DdccD8741A368b147B3B38bB',
    privateKey: '0x964ced1c69ad27a311c432fdc0d8211e987595f7eb34ab405a5f16bdc9563ec5',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [AsyncFunction: encrypt]
    }

decrypt

  • decrypt(keystore: string | KeyStore, password: string | Uint8Array, nonStrict?: boolean): Promise<Web3Account>
  • Decrypts a v3 keystore JSON, and creates the account.


    Parameters

    • keystore: string | KeyStore

      the encrypted Keystore object or string to decrypt

    • password: string | Uint8Array

      The password that was used for encryption

    • optionalnonStrict: boolean

      if true and given a json string, the keystore will be parsed as lowercase.

    Returns Promise<Web3Account>

    Returns the decrypted Web3Account object Decrypting scrypt

    web3.eth.accounts.decrypt({
    version: 3,
    id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a',
    address: 'cda9a91875fc35c8ac1320e098e584495d66e47c',
    crypto: {
    ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f',
    cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' },
    cipher: 'aes-128-ctr',
    kdf: 'scrypt',
    kdfparams: {
    n: 8192,
    r: 8,
    p: 1,
    dklen: 32,
    salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'
    },
    mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd'
    }
    }, '123').then(console.log);


    > {
    address: '0xcdA9A91875fc35c8Ac1320E098e584495d66e47c',
    privateKey: '67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6',
    signTransaction: [Function: signTransaction],
    sign: [Function: sign],
    encrypt: [AsyncFunction: encrypt]
    }

ecrecover

  • ecrecover(msgHash: Uint8Array, v: bigint, r: Uint8Array, s: Uint8Array, chainId?: bigint): Uint8Array
  • ECDSA public key recovery from signature. NOTE: Accepts v === 0 | v === 1 for EIP1559 transactions


    Parameters

    • msgHash: Uint8Array
    • v: bigint
    • r: Uint8Array
    • s: Uint8Array
    • optionalchainId: bigint

    Returns Uint8Array

    Recovered public key

encrypt

  • encrypt a private key with a password, returns a V3 JSON Keystore

    Read more: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition


    Parameters

    • privateKey: Bytes

      The private key to encrypt, 32 bytes.

    • password: string | Uint8Array

      The password used for encryption.

    • optionaloptions: CipherOptions

      Options to configure to encrypt the keystore either scrypt or pbkdf2

    Returns Promise<KeyStore>

    Returns a V3 JSON Keystore

    Encrypt using scrypt options:


    web3.eth.accounts.encrypt(
    '0x67f476289210e3bef3c1c75e4de993ff0a00663df00def84e73aa7411eac18a6',
    '123',
    {
    n: 8192,
    iv: web3.utils.hexToBytes('0xbfb43120ae00e9de110f8325143a2709'),
    salt: web3.utils.hexToBytes('0x210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'),
    }).then(console.log)

    > {
    version: 3,
    id: 'c0cb0a94-4702-4492-b6e6-eb2ac404344a',
    address: 'cda9a91875fc35c8ac1320e098e584495d66e47c',
    crypto: {
    ciphertext: 'cb3e13e3281ff3861a3f0257fad4c9a51b0eb046f9c7821825c46b210f040b8f',
    cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' },
    cipher: 'aes-128-ctr',
    kdf: 'scrypt',
    kdfparams: {
    n: 8192,
    r: 8,
    p: 1,
    dklen: 32,
    salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd'
    },
    mac: 'efbf6d3409f37c0084a79d5fdf9a6f5d97d11447517ef1ea8374f51e581b7efd'
    }
    }

    Encrypting using pbkdf2 options:

    web3.eth.accounts.encrypt('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
    '123',
    {
    iv: 'bfb43120ae00e9de110f8325143a2709',
    salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd',
    c: 262144,
    kdf: 'pbkdf2',
    }).then(console.log)

    >
    {
    version: 3,
    id: '77381417-0973-4e4b-b590-8eb3ace0fe2d',
    address: 'b8ce9ab6943e0eced004cde8e3bbed6568b2fa01',
    crypto: {
    ciphertext: '76512156a34105fa6473ad040c666ae7b917d14c06543accc0d2dc28e6073b12',
    cipherparams: { iv: 'bfb43120ae00e9de110f8325143a2709' },
    cipher: 'aes-128-ctr',
    kdf: 'pbkdf2',
    kdfparams: {
    dklen: 32,
    salt: '210d0ec956787d865358ac45716e6dd42e68d48e346d795746509523aeb477dd',
    c: 262144,
    prf: 'hmac-sha256'
    },
    mac: '46eb4884e82dc43b5aa415faba53cc653b7038e9d61cc32fd643cf8c396189b7'
    }
    }

hashMessage

  • hashMessage(message: string): string
  • Hashes the given message. The data will be UTF-8 HEX decoded and enveloped as follows: "\x19Ethereum Signed Message:\n" + message.length + message and hashed using keccak256.


    Parameters

    • message: string

      A message to hash, if its HEX it will be UTF8 decoded.

    Returns string

    The hashed message

    web3.eth.accounts.hashMessage("Hello world")

    > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede"

    web3.eth.accounts.hashMessage(web3.utils.utf8ToHex("Hello world")) // Will be hex decoded in hashMessage

    > "0x8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede"

intToUint8Array

  • intToUint8Array(i: number): Uint8Array
  • Converts an Number to a Uint8Array


    Parameters

    • i: number

    Returns Uint8Array

isAccessList

  • isAccessList(input: AccessListUint8Array | AccessList): input is AccessList
  • Parameters

    • input: AccessListUint8Array | AccessList

    Returns input is AccessList

isAccessListUint8Array

  • isAccessListUint8Array(input: AccessListUint8Array | AccessList): input is AccessListUint8Array
  • Parameters

    • input: AccessListUint8Array | AccessList

    Returns input is AccessListUint8Array

padToEven

  • padToEven(value: string): string
  • Pads a String to have an even length


    Parameters

    • value: string

    Returns string

    output

parseAndValidatePrivateKey

  • parseAndValidatePrivateKey(data: Bytes, ignoreLength?: boolean): Uint8Array
  • Get the private key Uint8Array after the validation. Note: This function is not exported through main web3 package, so for using it directly import from accounts package.


    Parameters

    • data: Bytes

      Private key

    • optionalignoreLength: boolean

      Optional, ignore length check during validation

    Returns Uint8Array

    The Uint8Array private key

    parseAndValidatePrivateKey("0x08c673022000ece7964ea4db2d9369c50442b2869cbd8fc21baaca59e18f642c")

    > Uint8Array(32) [
    186, 26, 143, 168, 235, 179, 90, 75,
    101, 63, 84, 221, 152, 150, 30, 203,
    8, 113, 94, 226, 53, 213, 216, 5,
    194, 159, 17, 53, 219, 97, 121, 248
    ]

parseGethGenesis

  • parseGethGenesis(json: any, name?: string, mergeForkIdPostMerge?: boolean): { bootstrapNodes: never[]; chainId: number; consensus: { algorithm: string; clique: { epoch: any; period: any }; ethash?: undefined; type: string } | { algorithm: string; clique?: undefined; ethash: {}; type: string }; genesis: { baseFeePerGas: string; coinbase: string; difficulty: number; extraData: string; gasLimit: number; mixHash: string; nonce: string; timestamp: string }; hardfork: string | undefined; hardforks: ConfigHardfork[]; name: string; networkId: number }
  • Parses a genesis.json exported from Geth into parameters for Common instance


    Parameters

    • json: any

      representing the Geth genesis file

    • optionalname: string

      optional chain name

    • optionalmergeForkIdPostMerge: boolean

    Returns { bootstrapNodes: never[]; chainId: number; consensus: { algorithm: string; clique: { epoch: any; period: any }; ethash?: undefined; type: string } | { algorithm: string; clique?: undefined; ethash: {}; type: string }; genesis: { baseFeePerGas: string; coinbase: string; difficulty: number; extraData: string; gasLimit: number; mixHash: string; nonce: string; timestamp: string }; hardfork: string | undefined; hardforks: ConfigHardfork[]; name: string; networkId: number }

    parsed params

    • bootstrapNodes: never[]
    • chainId: number
    • consensus: { algorithm: string; clique: { epoch: any; period: any }; ethash?: undefined; type: string } | { algorithm: string; clique?: undefined; ethash: {}; type: string }
    • genesis: { baseFeePerGas: string; coinbase: string; difficulty: number; extraData: string; gasLimit: number; mixHash: string; nonce: string; timestamp: string }
      • baseFeePerGas: string
      • coinbase: string
      • difficulty: number
      • extraData: string
      • gasLimit: number
      • mixHash: string
      • nonce: string
      • timestamp: string
    • hardfork: string | undefined
    • hardforks: ConfigHardfork[]
    • name: string
    • networkId: number

privateKeyToAccount

  • privateKeyToAccount(privateKey: Bytes, ignoreLength?: boolean): Web3Account
  • Get an Account object from the privateKey


    Parameters

    • privateKey: Bytes

      String or Uint8Array of 32 bytes

    • optionalignoreLength: boolean

      if true, will not error check length

    Returns Web3Account

    A Web3Account object

    The Web3Account.signTransaction is not stateful if directly imported from accounts package and used. Network access is required to get the account nonce and chainId to sign the transaction, so use Web3.eth.accounts.signTransaction for signing transactions.

    :

    web3.eth.accounts.privateKeyToAccount("0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709");

    > {
    address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
    privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
    sign,
    signTransaction,
    encrypt,
    }

privateKeyToAddress

  • privateKeyToAddress(privateKey: Bytes): string
  • Get the ethereum Address from a private key

    @example
    web3.eth.accounts.privateKeyToAddress("0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728")

    > "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0"

    Parameters

    • privateKey: Bytes

      String or Uint8Array of 32 bytes

    Returns string

    The Ethereum address

privateKeyToPublicKey

  • privateKeyToPublicKey(privateKey: Bytes, isCompressed: boolean): string
  • Get the public key from a private key

    @example
    web3.eth.accounts.privateKeyToPublicKey("0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", true)

    > "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a" // uncompressed public key

    Parameters

    • privateKey: Bytes

      String or Uint8Array of 32 bytes

    • isCompressed: boolean

      if true, will generate a 33 byte compressed public key instead of a 65 byte public key

    Returns string

    The public key

recover

  • recover(data: string | SignatureObject, signatureOrV?: string, prefixedOrR?: string | boolean, s?: string, prefixed?: boolean): string
  • Recovers the Ethereum address which was used to sign the given data


    Parameters

    • data: string | SignatureObject

      Either a signed message, hash, or the signatureObject

    • optionalsignatureOrV: string

      signature or V

    • optionalprefixedOrR: string | boolean

      prefixed or R

    • optionals: string

      S value in signature

    • optionalprefixed: boolean

      (default: false) If the last parameter is true, the given message will NOT automatically be prefixed with "\\x19Ethereum Signed Message:\\n" + message.length + message, and assumed to be already prefixed.

    Returns string

    The Ethereum address used to sign this data

    const data = 'Some data';
    const sigObj = web3.eth.accounts.sign(data, '0xbe6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728')

    > {
    message: 'Some data',
    messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
    v: '0x1b',
    r: '0xa8037a6116c176a25e6fc224947fde9e79a2deaa0dd8b67b366fbdfdbffc01f9',
    s: '0x53e41351267b20d4a89ebfe9c8f03c04de9b345add4a52f15bd026b63c8fb150',
    signature: &#