ethereumjs-util

  • Version 7.1.3
  • Published
  • 300 kB
  • 5 dependencies
  • MPL-2.0 license

Install

npm i ethereumjs-util
yarn add ethereumjs-util
pnpm add ethereumjs-util

Overview

A collection of utility functions for Ethereum

Index

Variables

Functions

Classes

Interfaces

Enums

Type Aliases

Variables

variable KECCAK256_NULL

const KECCAK256_NULL: any;
  • Keccak-256 hash of null

variable KECCAK256_NULL_S

const KECCAK256_NULL_S: string;
  • Keccak-256 hash of null

variable KECCAK256_RLP

const KECCAK256_RLP: any;
  • Keccak-256 hash of the RLP of null

variable KECCAK256_RLP_ARRAY

const KECCAK256_RLP_ARRAY: any;
  • Keccak-256 of an RLP of an empty array

variable KECCAK256_RLP_ARRAY_S

const KECCAK256_RLP_ARRAY_S: string;
  • Keccak-256 of an RLP of an empty array

variable KECCAK256_RLP_S

const KECCAK256_RLP_S: string;
  • Keccak-256 hash of the RLP of null

variable MAX_INTEGER

const MAX_INTEGER: any;
  • The max integer that this VM can handle

variable TWO_POW256

const TWO_POW256: any;
  • 2^256

Functions

function addHexPrefix

addHexPrefix: (str: string) => string;
  • Adds "0x" to a given String if it does not already start with "0x".

function arrayContainsArray

arrayContainsArray: (
superset: unknown[],
subset: unknown[],
some?: boolean
) => boolean;
  • Returns TRUE if the first specified array contains all elements from the second one. FALSE otherwise.

    Parameter superset

    Parameter subset

function baToJSON

baToJSON: (ba: any) => any;
  • Converts a Buffer or Array to JSON.

    Parameter ba

    (Buffer|Array) (Array|String|null)

function bnToHex

bnToHex: (value: any) => PrefixedHexString;
  • Convert BN to 0x-prefixed hex string.

function bnToRlp

bnToRlp: (value: any) => any;

function bnToUnpaddedBuffer

bnToUnpaddedBuffer: (value: any) => any;
  • Convert value from BN to an unpadded Buffer (useful for RLP transport)

    Parameter value

    value to convert

function bufferToHex

bufferToHex: (buf: any) => string;
  • Converts a Buffer into a 0x-prefixed hex String.

    Parameter buf

    Buffer object to convert

function bufferToInt

bufferToInt: (buf: any) => number;
  • Converts a Buffer to a Number.

    Parameter buf

    Buffer object to convert

    Throws

    If the input number exceeds 53 bits.

function defineProperties

defineProperties: (self: any, fields: any, data?: any) => void;
  • Defines properties on a Object. It make the assumption that underlying data is binary.

    Parameter self

    the Object to define properties on

    Parameter fields

    an array fields to define. Fields can contain: * name - the name of the properties * length - the number of bytes the field can have * allowLess - if the field can be less than the length * allowEmpty

    Parameter data

    data to be validated against the definitions

    Deprecated

function ecrecover

ecrecover: (
msgHash: any,
v: BNLike,
r: any,
s: any,
chainId?: BNLike | undefined
) => any;
  • ECDSA public key recovery from signature.

    Returns

    Recovered public key

function ecsign

ecsign: {
(msgHash: any, privateKey: any, chainId?: number): ECDSASignature;
(msgHash: any, privateKey: any, chainId: any): ECDSASignatureBuffer;
};
  • Returns the ECDSA signature of a message hash.

function fromAscii

fromAscii: (stringValue: string) => string;
  • Should be called to get hex representation (prefixed by 0x) of ascii string

    Parameter string

    Parameter optional

    padding

    Returns

    hex representation of input string

function fromRpcSig

fromRpcSig: (sig: string) => ECDSASignature;
  • Convert signature format of the eth_sign RPC method to signature parameters NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053

function fromSigned

fromSigned: (num: any) => any;
  • Interprets a Buffer as a signed integer and returns a BN. Assumes 256-bit numbers.

    Parameter num

    Signed integer value

function fromUtf8

fromUtf8: (stringValue: string) => string;
  • Should be called to get hex representation (prefixed by 0x) of utf8 string

    Parameter string

    Parameter optional

    padding

    Returns

    hex representation of input string

function generateAddress

generateAddress: (from: any, nonce: any) => any;
  • Generates an address of a newly created contract.

    Parameter from

    The address which is creating this new address

    Parameter nonce

    The nonce of the from account

function generateAddress2

generateAddress2: (from: any, salt: any, initCode: any) => any;
  • Generates an address for a contract created using CREATE2.

    Parameter from

    The address which is creating this new address

    Parameter salt

    A salt

    Parameter initCode

    The init code of the contract being created

function getBinarySize

getBinarySize: (str: string) => number;
  • Get the binary size of a string

    Parameter str

    Returns

    the number of bytes contained within the string

function getKeys

getKeys: (
params: Record<string, string>[],
key: string,
allowEmpty?: boolean
) => string[];
  • Returns the keys from an array of objects.

    Parameter params

    Parameter key

    Parameter allowEmpty

    Returns

    output just a simple array of output keys

    Example 1

    getKeys([{a: '1', b: '2'}, {a: '3', b: '4'}], 'a') => ['1', '3']

    `

function hashPersonalMessage

hashPersonalMessage: (message: any) => any;
  • Returns the keccak-256 hash of message, prefixed with the header used by the eth_sign RPC call. The output of this function can be fed into ecsign to produce the same signature as the eth_sign call for a given message, or fed to ecrecover along with a signature to recover the public key used to produce the signature.

function importPublic

importPublic: (publicKey: any) => any;
  • Converts a public key to the Ethereum format.

function intToBuffer

intToBuffer: (i: number) => any;
  • Converts an Number to a Buffer

    Parameter i

    {Buffer}

function intToHex

intToHex: (i: number) => string;
  • Converts a Number into a hex String

    Parameter i

    {String}

function isHexPrefixed

isHexPrefixed: (str: string) => boolean;
  • Returns a Boolean on whether or not the a String starts with '0x'

    Parameter str

    the string input value a boolean if it is or is not hex prefixed

    Throws

    if the str input is not a string

function isHexString

isHexString: (value: string, length?: number) => boolean;
  • Is the string a hex string.

    Parameter value

    Parameter length

    Returns

    output the string is a hex string

function isValidAddress

isValidAddress: (hexAddress: string) => boolean;
  • Checks if the address is a valid. Accepts checksummed addresses too.

function isValidChecksumAddress

isValidChecksumAddress: (
hexAddress: string,
eip1191ChainId?: BNLike | undefined
) => boolean;
  • Checks if the address is a valid checksummed address.

    See toChecksumAddress' documentation for details about the eip1191ChainId parameter.

function isValidPrivate

isValidPrivate: (privateKey: any) => boolean;
  • Checks if the private key satisfies the rules of the curve secp256k1.

function isValidPublic

isValidPublic: (publicKey: any, sanitize?: boolean) => boolean;
  • Checks if the public key satisfies the rules of the curve secp256k1 and the requirements of Ethereum.

    Parameter publicKey

    The two points of an uncompressed key, unless sanitize is enabled

    Parameter sanitize

    Accept public keys in other formats

function isValidSignature

isValidSignature: (
v: BNLike,
r: any,
s: any,
homesteadOrLater?: boolean,
chainId?: BNLike | undefined
) => boolean;
  • Validate a ECDSA signature.

    Parameter homesteadOrLater

    Indicates whether this is being used on either the homestead hardfork or a later one

function isZeroAddress

isZeroAddress: (hexAddress: string) => boolean;
  • Checks if a given address is the zero address.

function keccak

keccak: (a: any, bits?: number) => any;
  • Creates Keccak hash of a Buffer input

    Parameter a

    The input data (Buffer)

    Parameter bits

    (number = 256) The Keccak width

function keccak256

keccak256: (a: any) => any;
  • Creates Keccak-256 hash of the input, alias for keccak(a, 256).

    Parameter a

    The input data (Buffer)

function keccakFromArray

keccakFromArray: (a: number[], bits?: number) => any;
  • Creates Keccak hash of a number array input

    Parameter a

    The input data (number[])

    Parameter bits

    (number = 256) The Keccak width

function keccakFromHexString

keccakFromHexString: (a: string, bits?: number) => any;
  • Creates Keccak hash of an 0x-prefixed string input

    Parameter a

    The input data (String)

    Parameter bits

    (number = 256) The Keccak width

function keccakFromString

keccakFromString: (a: string, bits?: number) => any;
  • Creates Keccak hash of a utf-8 string input

    Parameter a

    The input data (String)

    Parameter bits

    (number = 256) The Keccak width

function padToEven

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

    Parameter value

    output

function privateToAddress

privateToAddress: (privateKey: any) => any;
  • Returns the ethereum address of a given private key.

    Parameter privateKey

    A private key must be 256 bits wide

function privateToPublic

privateToPublic: (privateKey: any) => any;
  • Returns the ethereum public key of a given private key.

    Parameter privateKey

    A private key must be 256 bits wide

function publicToAddress

publicToAddress: (pubKey: any, sanitize?: boolean) => any;

    function pubToAddress

    pubToAddress: (pubKey: any, sanitize?: boolean) => any;
    • Returns the ethereum address of a given public key. Accepts "Ethereum public keys" and SEC1 encoded keys.

      Parameter pubKey

      The two points of an uncompressed key, unless sanitize is enabled

      Parameter sanitize

      Accept public keys in other formats

    function ripemd160

    ripemd160: (a: any, padded: boolean) => any;
    • Creates RIPEMD160 hash of a Buffer input.

      Parameter a

      The input data (Buffer)

      Parameter padded

      Whether it should be padded to 256 bits or not

    function ripemd160FromArray

    ripemd160FromArray: (a: number[], padded: boolean) => any;
    • Creates RIPEMD160 hash of a number[] input.

      Parameter a

      The input data (number[])

      Parameter padded

      Whether it should be padded to 256 bits or not

    function ripemd160FromString

    ripemd160FromString: (a: string, padded: boolean) => any;
    • Creates RIPEMD160 hash of a string input.

      Parameter a

      The input data (String)

      Parameter padded

      Whether it should be padded to 256 bits or not

    function rlphash

    rlphash: (a: any) => any;
    • Creates SHA-3 hash of the RLP encoded version of the input.

      Parameter a

      The input data

    function setLengthLeft

    setLengthLeft: (msg: any, length: number) => any;
    • Left Pads a Buffer with leading zeros till it has length bytes. Or it truncates the beginning if it exceeds.

      Parameter msg

      the value to pad (Buffer)

      Parameter length

      the number of bytes the output should be (Buffer)

    function setLengthRight

    setLengthRight: (msg: any, length: number) => any;
    • Right Pads a Buffer with trailing zeros till it has length bytes. it truncates the end if it exceeds.

      Parameter msg

      the value to pad (Buffer)

      Parameter length

      the number of bytes the output should be (Buffer)

    function sha256

    sha256: (a: any) => any;
    • Creates SHA256 hash of a Buffer input.

      Parameter a

      The input data (Buffer)

    function sha256FromArray

    sha256FromArray: (a: number[]) => any;
    • Creates SHA256 hash of a number[] input.

      Parameter a

      The input data (number[])

    function sha256FromString

    sha256FromString: (a: string) => any;
    • Creates SHA256 hash of a string input.

      Parameter a

      The input data (string)

    function stripHexPrefix

    stripHexPrefix: (str: string) => string;
    • Removes '0x' from a given String if present

      Parameter str

      the string value

      Returns

      the string without 0x prefix

    function toAscii

    toAscii: (hex: string) => string;
    • Should be called to get ascii from its hex representation

      Parameter string

      in hex

      Returns

      ascii string representation of hex value

    function toBuffer

    toBuffer: (v: ToBufferInputTypes) => any;
    • Attempts to turn a value into a Buffer. Inputs supported: Buffer, String (hex-prefixed), Number, null/undefined, BN and other objects with a toArray() or toBuffer() method.

      Parameter v

      the value

    function toChecksumAddress

    toChecksumAddress: (
    hexAddress: string,
    eip1191ChainId?: BNLike | undefined
    ) => string;
    • Returns a checksummed address.

      If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This has the effect of checksummed addresses for one chain having invalid checksums for others. For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191).

      WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not backwards compatible to the original widely adopted checksum format standard introduced in [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications. Usage of this EIP is therefore discouraged unless you have a very targeted use case.

    function toCompactSig

    toCompactSig: (
    v: BNLike,
    r: any,
    s: any,
    chainId?: BNLike | undefined
    ) => string;
    • Convert signature parameters into the format of Compact Signature Representation (EIP-2098).

      Returns

      Signature

    function toRpcSig

    toRpcSig: (v: BNLike, r: any, s: any, chainId?: BNLike | undefined) => string;
    • Convert signature parameters into the format of eth_sign RPC method.

      Returns

      Signature

    function toType

    toType: {
    <T extends TypeOutput>(input: null, outputType: T): null;
    <T extends TypeOutput>(input: undefined, outputType: T): undefined;
    <T extends TypeOutput>(input: any, outputType: T): TypeOutputReturnType[T];
    };
    • Convert an input to a specified type. Input of null/undefined returns null/undefined regardless of the output type.

      Parameter input

      value to convert

      Parameter outputType

      type to output

    function toUnsigned

    toUnsigned: (num: any) => any;
    • Converts a BN to an unsigned integer and returns it as a Buffer. Assumes 256-bit numbers.

      Parameter num

    function toUtf8

    toUtf8: (hex: string) => string;
    • Returns the utf8 string representation from a hex string.

      Examples:

      Input 1: '657468657265756d000000000000000000000000000000000000000000000000' Input 2: '657468657265756d' Input 3: '000000000000000000000000000000000000000000000000657468657265756d'

      Output (all 3 input variants): 'ethereum'

      Note that this method is not intended to be used with hex strings representing quantities in both big endian or little endian notation.

      Parameter string

      Hex string, should be 0x prefixed Utf8 string

    function unpadArray

    unpadArray: (a: number[]) => number[];
    • Trims leading zeros from an Array (of numbers).

      Parameter a

      (number[]) (number[])

    function unpadBuffer

    unpadBuffer: (a: any) => any;
    • Trims leading zeros from a Buffer.

      Parameter a

      (Buffer) (Buffer)

    function unpadHexString

    unpadHexString: (a: string) => string;
    • Trims leading zeros from a hex-prefixed String.

      Parameter a

      (String) (String)

    function zeroAddress

    zeroAddress: () => string;
    • Returns the zero address.

    function zeros

    zeros: (bytes: number) => any;
    • Returns a buffer filled with 0s.

      Parameter bytes

      the number of bytes the buffer should be

    Classes

    class Account

    class Account {}

      constructor

      constructor(nonce?: any, balance?: any, stateRoot?: any, codeHash?: any);
      • This constructor assigns and validates the values. Use the static factory methods to assist in creating an Account from varying data types.

      property balance

      balance: any;

        property codeHash

        codeHash: any;

          property nonce

          nonce: any;

            property stateRoot

            stateRoot: any;

              method fromAccountData

              static fromAccountData: (accountData: AccountData) => Account;

                method fromRlpSerializedAccount

                static fromRlpSerializedAccount: (serialized: any) => Account;

                  method fromValuesArray

                  static fromValuesArray: (values: Buffer[]) => Account;

                    method isContract

                    isContract: () => boolean;
                    • Returns a Boolean determining if the account is a contract.

                    method isEmpty

                    isEmpty: () => boolean;
                    • Returns a Boolean determining if the account is empty complying to the definition of account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): "An account is considered empty when it has no code and zero nonce and zero balance."

                    method raw

                    raw: () => Buffer[];
                    • Returns a Buffer Array of the raw Buffers for the account, in order.

                    method serialize

                    serialize: () => any;
                    • Returns the RLP serialization of the account as a Buffer.

                    class Address

                    class Address {}

                      constructor

                      constructor(buf: any);

                        property buf

                        readonly buf: any;

                          method equals

                          equals: (address: Address) => boolean;
                          • Is address equal to another.

                          method fromPrivateKey

                          static fromPrivateKey: (privateKey: any) => Address;
                          • Returns an address for a given private key.

                            Parameter privateKey

                            A private key must be 256 bits wide

                          method fromPublicKey

                          static fromPublicKey: (pubKey: any) => Address;
                          • Returns an address for a given public key.

                            Parameter pubKey

                            The two points of an uncompressed key

                          method fromString

                          static fromString: (str: string) => Address;
                          • Returns an Address object from a hex-encoded string.

                            Parameter str

                            Hex-encoded address

                          method generate

                          static generate: (from: Address, nonce: any) => Address;
                          • Generates an address for a newly created contract.

                            Parameter from

                            The address which is creating this new address

                            Parameter nonce

                            The nonce of the from account

                          method generate2

                          static generate2: (from: Address, salt: any, initCode: any) => Address;
                          • Generates an address for a contract created using CREATE2.

                            Parameter from

                            The address which is creating this new address

                            Parameter salt

                            A salt

                            Parameter initCode

                            The init code of the contract being created

                          method isPrecompileOrSystemAddress

                          isPrecompileOrSystemAddress: () => boolean;
                          • True if address is in the address range defined by EIP-1352

                          method isZero

                          isZero: () => boolean;
                          • Is address zero.

                          method toBuffer

                          toBuffer: () => any;
                          • Returns Buffer representation of address.

                          method toString

                          toString: () => string;
                          • Returns hex encoding of address.

                          method zero

                          static zero: () => Address;
                          • Returns the zero address.

                          Interfaces

                          interface AccountData

                          interface AccountData {}

                            property balance

                            balance?: BNLike;

                              property codeHash

                              codeHash?: BufferLike;

                                property nonce

                                nonce?: BNLike;

                                  property stateRoot

                                  stateRoot?: BufferLike;

                                    interface ECDSASignature

                                    interface ECDSASignature {}

                                      property r

                                      r: Buffer;

                                        property s

                                        s: Buffer;

                                          property v

                                          v: number;

                                            interface ECDSASignatureBuffer

                                            interface ECDSASignatureBuffer {}

                                              property r

                                              r: Buffer;

                                                property s

                                                s: Buffer;

                                                  property v

                                                  v: Buffer;

                                                    interface TransformableToArray

                                                    interface TransformableToArray {}

                                                      method toArray

                                                      toArray: () => Uint8Array;

                                                        method toBuffer

                                                        toBuffer: () => any;

                                                          interface TransformableToBuffer

                                                          interface TransformableToBuffer {}

                                                            method toArray

                                                            toArray: () => Uint8Array;

                                                              method toBuffer

                                                              toBuffer: () => any;

                                                                Enums

                                                                enum TypeOutput

                                                                enum TypeOutput {
                                                                Number = 0,
                                                                BN = 1,
                                                                Buffer = 2,
                                                                PrefixedHexString = 3,
                                                                }
                                                                • Type output options

                                                                member BN

                                                                BN = 1

                                                                  member Buffer

                                                                  Buffer = 2

                                                                    member Number

                                                                    Number = 0

                                                                      member PrefixedHexString

                                                                      PrefixedHexString = 3

                                                                        Type Aliases

                                                                        type AddressLike

                                                                        type AddressLike = Address | Buffer | PrefixedHexString;
                                                                        • A type that represents an Address-like value. To convert to address, use new Address(toBuffer(value))

                                                                        type BNLike

                                                                        type BNLike = BN | PrefixedHexString | number | Buffer;

                                                                          type BufferLike

                                                                          type BufferLike =
                                                                          | Buffer
                                                                          | Uint8Array
                                                                          | number[]
                                                                          | number
                                                                          | BN
                                                                          | TransformableToBuffer
                                                                          | PrefixedHexString;

                                                                            type PrefixedHexString

                                                                            type PrefixedHexString = string;

                                                                              type ToBufferInputTypes

                                                                              type ToBufferInputTypes =
                                                                              | PrefixedHexString
                                                                              | number
                                                                              | BN
                                                                              | Buffer
                                                                              | Uint8Array
                                                                              | number[]
                                                                              | TransformableToArray
                                                                              | TransformableToBuffer
                                                                              | null
                                                                              | undefined;

                                                                                type TypeOutputReturnType

                                                                                type TypeOutputReturnType = {
                                                                                [TypeOutput.Number]: number;
                                                                                [TypeOutput.BN]: BN;
                                                                                [TypeOutput.Buffer]: Buffer;
                                                                                [TypeOutput.PrefixedHexString]: PrefixedHexString;
                                                                                };

                                                                                  Package Files (10)

                                                                                  Dependencies (5)

                                                                                  Dev Dependencies (15)

                                                                                  Peer Dependencies (0)

                                                                                  No peer dependencies.

                                                                                  Badge

                                                                                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ethereumjs-util.

                                                                                  • Markdown
                                                                                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/ethereumjs-util)
                                                                                  • HTML
                                                                                    <a href="https://www.jsdocs.io/package/ethereumjs-util"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>