Skip to main content

utils

Index

References

AbiItem

Re-exports AbiItem

Eip1193Provider

Re-exports Eip1193Provider

SocketProvider

Re-exports SocketProvider

isBatchRequest

Re-exports isBatchRequest

isBatchResponse

Re-exports isBatchResponse

isResponseRpcError

isResponseWithError

isResponseWithNotification

isResponseWithResult

isSubscriptionResult

isValidResponse

Re-exports isValidResponse

keccak256

Renames and re-exports keccak256Wrapper

setRequestIdStart

toBatchPayload

Re-exports toBatchPayload

toPayload

Re-exports toPayload

validateResponse

Re-exports validateResponse

Namespaces

jsonRpc

jsonRpc:

isBatchRequest

isBatchResponse

isResponseRpcError

isResponseWithError

isResponseWithNotification

isResponseWithResult

isSubscriptionResult

isValidResponse

  • isValidResponse<Result, Error_1>(response: JsonRpcResponse<Result, Error_1>): boolean
  • Type parameters

    • Result = unknown
    • Error_1 = unknown

    Parameters

    Returns boolean

setRequestIdStart

  • setRequestIdStart(start: undefined | number): void
  • Optionally use to make the jsonrpc id start from a specific number. Without calling this function, the id will be filled with a Uuid. But after this being called with a number, the id will be a number staring from the provided start variable. However, if undefined was passed to this function, the id will be a Uuid again.


    Parameters

    • start: undefined | number

      a number to start incrementing from. Or undefined to use a new Uuid (this is the default behavior)

    Returns void

toBatchPayload

toPayload

validateResponse

  • validateResponse<Result, Error_1>(response: JsonRpcResponse<Result, Error_1>): boolean
  • Type parameters

    • Result = unknown
    • Error_1 = unknown

    Parameters

    Returns boolean

Classes

ChunkResponseParser

ChunkResponseParser:

constructor

  • new ChunkResponseParser(eventEmitter: EventEmitter<string | symbol, any>, autoReconnect: boolean): ChunkResponseParser
  • Parameters

    • eventEmitter: EventEmitter<string | symbol, any>
    • autoReconnect: boolean

    Returns ChunkResponseParser

onError

  • onError(clearQueues?: () => void): void
  • Parameters

    • optionalclearQueues: () => void

    Returns void

parseResponse

EventEmitter

EventEmitter:

This class copy the behavior of Node.js EventEmitter class. It is used to provide the same interface for the browser environment.

constructor

  • Returns EventEmitter

getMaxListeners

  • getMaxListeners(): number
  • Returns number

setMaxListeners

  • setMaxListeners(maxListeners: number): this
  • Parameters

    • maxListeners: number

    Returns this

Web3DeferredPromise

Web3DeferredPromise<T>:

The class is a simple implementation of a deferred promise with optional timeout functionality, which can be useful when dealing with asynchronous tasks.


Type parameters

  • T

constructor

  • new Web3DeferredPromise<T>(__namedParameters?: { eagerStart: boolean; timeout: number; timeoutMessage: string }): Web3DeferredPromise<T>
  • Type parameters

    • T

    Parameters

    • optional__namedParameters: { eagerStart: boolean; timeout: number; timeoutMessage: string }

    Returns Web3DeferredPromise<T>

[toStringTag]

[toStringTag]: Promise

state

  • get state(): pending | fulfilled | rejected
  • Returns the current state of the promise.


    Returns pending | fulfilled | rejected

    'pending' | 'fulfilled' | 'rejected'

catch

  • catch<TResult>(onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<T | TResult>

  • Type parameters

    • TResult

    Parameters

    • optionalonrejected: (reason: any) => TResult | PromiseLike<TResult>

      (optional) The callback to execute when the promise is rejected.

    Returns Promise<T | TResult>

finally

  • finally(onfinally?: () => void): Promise<T>

  • Parameters

    • optionalonfinally: () => void

      (optional) The callback to execute when the promise is settled (fulfilled or rejected).

    Returns Promise<T>

reject

  • reject(reason?: unknown): void
  • Rejects the current promise.


    Parameters

    • optionalreason: unknown

      The reason to reject the promise with.

    Returns void

resolve

  • resolve(value: T | PromiseLike<T>): void
  • Resolves the current promise.


    Parameters

    • value: T | PromiseLike<T>

      The value to resolve the promise with.

    Returns void

startTimer

  • startTimer(): void
  • Starts the timeout timer for the promise.


    Returns void

then

  • then<TResult1, TResult2>(onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: unknown) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>

  • Type parameters

    • TResult1
    • TResult2

    Parameters

    • optionalonfulfilled: (value: T) => TResult1 | PromiseLike<TResult1>

      (optional) The callback to execute when the promise is fulfilled.

    • optionalonrejected: (reason: unknown) => TResult2 | PromiseLike<TResult2>

      (optional) The callback to execute when the promise is rejected.

    Returns Promise<TResult1 | TResult2>

Type Aliases

AsyncFunction

AsyncFunction<T, K>: (...args: K[]) => Promise<T>

Type parameters

  • T
  • K = unknown

Type declaration

    • (...args: K[]): Promise<T>
    • Parameters

      • rest...args: K[]

      Returns Promise<T>

EtherUnits

EtherUnits: keyof typeof ethUnitMap

ReconnectOptions

ReconnectOptions: { autoReconnect: boolean; delay: number; maxAttempts: number }

Type declaration

  • autoReconnect: boolean
  • delay: number
  • maxAttempts: number

Timeout

Timeout: ReturnType<typeof setTimeout>

Timer

Timer: ReturnType<typeof setInterval>

Functions

asciiToHex

  • asciiToHex(str: string): string
  • Should be called to get hex representation (prefixed by 0x) of ascii string

    @example
    console.log(web3.utils.asciiToHex('Hello World'));
    > 0x48656c6c6f20576f726c64

    Parameters

    • str: string

      String to be converted to hex

    Returns string

    • Hex string

bytesToHex

  • bytesToHex(bytes: Bytes): string
  • Convert a byte array to a hex string

    @example
    console.log(web3.utils.bytesToHex(new Uint8Array([72, 12])));
    > "0x480c"

    Parameters

    • bytes: Bytes

      Byte array to be converted

    Returns string

    • The hex string representation of the input byte array

bytesToUint8Array

  • bytesToUint8Array(data: Bytes): Uint8Array
  • Convert a value from bytes to Uint8Array

    @example
    console.log(web3.utils.bytesToUint8Array("0xab")));
    > Uint8Array(1) [ 171 ]

    Parameters

    • data: Bytes

      Data to be converted

    Returns Uint8Array

    • The Uint8Array representation of the input data

checkAddressCheckSum

  • checkAddressCheckSum(data: string): boolean
  • Checks the checksum of a given address. Will also return false on non-checksum addresses.

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    • data: string

    Returns boolean

compareBlockNumbers

  • Compares between block A and block B

    @example
    console.log(web3.utils.compareBlockNumbers('latest', 'pending'));
    > -1

    console.log(web3.utils.compareBlockNumbers(12, 11));
    > 1

    Parameters

    Returns 0 | 1 | -1

    • Returns -1 if a &lt; b, returns 1 if a &gt; b and returns 0 if a == b

convert

  • convert(data: unknown, schema: Schema, dataPath: string[], format: DataFormat, oneOfPath?: [string, number][]): unknown
  • Converts the data to the specified format


    Parameters

    • data: unknown

      data to convert

    • schema: Schema

      The JSON schema that describes the structure of the data

    • dataPath: string[]

      A string array that specifies the path to the data within the JSON schema

    • format: DataFormat

      The format to be converted to

    • optionaloneOfPath: [string, number][]

      An optional array of two-element tuples that specifies the "oneOf" option to choose, if the schema has oneOf and the data path can match multiple subschemas

    Returns unknown

    • The data converted to the specified format

convertScalarValue

  • convertScalarValue(value: unknown, ethType: string, format: DataFormat): unknown
  • Converts a value depending on the format


    Parameters

    • value: unknown

      value to convert

    • ethType: string

      The type of the value to be parsed

    • format: DataFormat

      The format to be converted to

    Returns unknown

    • The value converted to the specified format

encodePacked

  • Encode packed arguments to a hexstring


    Parameters

    Returns string

format

fromAscii

  • fromAscii(str: string): string
  • @alias

    asciiToHex


    Parameters

    • str: string

    Returns string

fromDecimal

  • fromDecimal(value: Numbers, hexstrict?: boolean): string
  • Converts value to it's hex representation

    @alias

    numberToHex


    Parameters

    • value: Numbers
    • optionalhexstrict: boolean

    Returns string

fromTwosComplement

  • fromTwosComplement(value: Numbers, nibbleWidth?: number): number | bigint
  • Converts the twos complement into a decimal number or big int.

    @example
    console.log(web3.utils.fromTwosComplement('0x0000000000000000000000000000000d', 32'));
    > 13

    console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32));
    > 9007199254740992n

    Parameters

    • value: Numbers

      The value to be converted.

    • optionalnibbleWidth: number

      The nibble width of the hex string (default is 64).

    Returns number | bigint

    The decimal number or big int.

fromUtf8

  • fromUtf8(str: string): string
  • @alias

    utf8ToHex


    Parameters

    • str: string

    Returns string

fromWei

  • fromWei(number: Numbers, unit: noether | wei | kwei | Kwei | babbage | femtoether | mwei | Mwei | lovelace | picoether | gwei | Gwei | shannon | nanoether | nano | szabo | microether | micro | finney | milliether | milli | ether | kether | grand | mether | gether | tether): string
  • Takes a number of wei and converts it to any other ether unit.

    @example
    console.log(web3.utils.fromWei("1", "ether"));
    > 0.000000000000000001

    console.log(web3.utils.fromWei("1", "shannon"));
    > 0.000000001

    Parameters

    • number: Numbers

      The value in wei

    • unit: noether | wei | kwei | Kwei | babbage | femtoether | mwei | Mwei | lovelace | picoether | gwei | Gwei | shannon | nanoether | nano | szabo | microether | micro | finney | milliether | milli | ether | kether | grand | mether | gether | tether

      The unit to convert to

    Returns string

    • Returns the converted value in the given unit

getStorageSlotNumForLongString

  • getStorageSlotNumForLongString(mainSlotNumber: string | number): undefined | string
  • Get slot number for storage long string in contract. Basically for getStorage method returns slotNumber where will data placed


    Parameters

    • mainSlotNumber: string | number

      the slot number where will be stored hash of long string

    Returns undefined | string

    • the slot number where will be stored long string

hexToAscii

  • hexToAscii(str: string): string
  • Should be called to get ascii from it's hex representation

    @example
    console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64'));
    > Hello World

    Parameters

    • str: string

      Hex string to be converted to ascii

    Returns string

    • Ascii string

hexToBytes

  • hexToBytes(bytes: string): Uint8Array
  • Convert a hex string to a byte array

    @example
    console.log(web3.utils.hexToBytes('0x74657374'));
    > Uint8Array(4) [ 116, 101, 115, 116 ]

    Parameters

    • bytes: string

    Returns Uint8Array

    • The byte array representation of the input hex string

hexToNumber

  • hexToNumber(value: string): number | bigint
  • Converts value to it's number representation

    @example
    conoslle.log(web3.utils.hexToNumber('0xa'));
    > 10

    Parameters

    • value: string

      Hex string to be converted

    Returns number | bigint

    • The number representation of the input value

hexToNumberString

  • hexToNumberString(data: string): string
  • Converts value to it's decimal representation in string

    @example
    console.log(web3.utils.hexToNumberString('0xa'));
    > "10"

    Parameters

    • data: string

    Returns string

    • The decimal representation of the input value

hexToString

  • hexToString(str: string): string
  • @alias

    hexToUtf8


    Parameters

    • str: string

    Returns string

hexToUtf8

  • hexToUtf8(str: string): string
  • Should be called to get utf8 from it's hex representation

    @example
    console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64'));
    > Hello World

    Parameters

    • str: string

      Hex string to be converted

    Returns string

    • Utf8 string

isAddress

  • Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters.

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    Returns boolean

isBloom

isContractAddressInBloom

  • isContractAddressInBloom(bloom: string, contractAddress: string): boolean
  • Returns true if the contract address is part of the given bloom. note: false positives are possible.

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    • bloom: string
    • contractAddress: string

    Returns boolean

isContractInitOptions

isDataFormat

  • isDataFormat(dataFormat: unknown): dataFormat is DataFormat
  • Parameters

    • dataFormat: unknown

    Returns dataFormat is DataFormat

isHex

  • returns true if input is a hexstring, number or bigint

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    Returns boolean

isHexStrict

  • @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    Returns boolean

isInBloom

  • isInBloom(bloom: string, value: string | Uint8Array): boolean
  • Returns true if the value is part of the given bloom note: false positives are possible.

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    • bloom: string
    • value: string | Uint8Array

    Returns boolean

isNullish

  • isNullish(item: unknown): item is undefined | null
  • Parameters

    • item: unknown

    Returns item is undefined | null

isPromise

  • isPromise(object: unknown): boolean
  • An alternative to the node function isPromise that exists in util/types because it is not available on the browser.


    Parameters

    • object: unknown

      to check if it is a Promise

    Returns boolean

    true if it is an object or a function that has a then function. And returns false otherwise.

isTopic

  • isTopic(topic: string): boolean
  • Checks if its a valid topic

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    • topic: string

    Returns boolean

isTopicInBloom

  • isTopicInBloom(bloom: string, topic: string): boolean
  • Returns true if the topic is part of the given bloom. note: false positives are possible.

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    • bloom: string
    • topic: string

    Returns boolean

isUint8Array

  • isUint8Array(data: unknown): data is Uint8Array
  • Parameters

    • data: unknown

    Returns data is Uint8Array

isUserEthereumAddressInBloom

  • isUserEthereumAddressInBloom(bloom: string, ethereumAddress: string): boolean
  • Returns true if the ethereum users address is part of the given bloom note: false positives are possible.

    @deprecated

    Will be removed in next release. Please use web3-validator package instead.


    Parameters

    • bloom: string
    • ethereumAddress: string

    Returns boolean

keccak256Wrapper

  • keccak256Wrapper(data: string | number | bigint | Uint8Array | readonly number[]): string
  • A wrapper for ethereum-cryptography/keccak256 to allow hashing a string and a bigint in addition to UInt8Array

    @example
    console.log(web3.utils.keccak256Wrapper('web3.js'));
    > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a

    console.log(web3.utils.keccak256Wrapper(1));
    > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6

    console.log(web3.utils.keccak256Wrapper(0xaf12fd));
    > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c

    Parameters

    • data: string | number | bigint | Uint8Array | readonly number[]

      the input to hash

    Returns string

    • the Keccak-256 hash of the input

leftPad

  • leftPad(value: Numbers, characterAmount: number, sign?: string): string
  • Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.

    @alias

    padLeft


    Parameters

    • value: Numbers
    • characterAmount: number
    • optionalsign: string

    Returns string

mergeDeep

  • mergeDeep(destination: Record<string, unknown>, ...sources: Record<string, unknown>[]): Record<string, unknown>
  • Deep merge two objects.


    Parameters

    • destination: Record<string, unknown>

      The destination object.

    • rest...sources: Record<string, unknown>[]

      An array of source objects.

    Returns Record<string, unknown>

    • The merged object.

numberToHex

  • numberToHex(value: Numbers, hexstrict?: boolean): string
  • Converts value to it's hex representation

    @example
    console.log(web3.utils.numberToHex(10));
    > "0xa"

    Parameters

    • value: Numbers

      Value to be converted

    • optionalhexstrict: boolean

      Add padding to converted value if odd, to make it hexstrict

    Returns string

    • The hex representation of the input value

padLeft

  • padLeft(value: Numbers, characterAmount: number, sign?: string): string
  • Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.

    @example

    console.log(web3.utils.padLeft('0x123', 10));
    >0x0000000123

    Parameters

    • value: Numbers

      The value to be padded.

    • characterAmount: number

      The amount of characters the string should have.

    • optionalsign: string

      The sign to be added (default is 0).

    Returns string

    The padded string.

padRight

  • padRight(value: Numbers, characterAmount: number, sign?: string): string
  • Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.

    @example
    console.log(web3.utils.padRight('0x123', 10));
    > 0x1230000000

    console.log(web3.utils.padRight('0x123', 10, '1'));
    > 0x1231111111

    Parameters

    • value: Numbers

      The value to be padded.

    • characterAmount: number

      The amount of characters the string should have.

    • optionalsign: string

      The sign to be added (default is 0).

    Returns string

    The padded string.

pollTillDefined

  • pollTillDefined<T>(func: AsyncFunction<T, unknown>, interval: number): Promise<Exclude<T, undefined>>
  • Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), or until a timeout is reached. pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result. This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId().


    Type parameters

    • T

    Parameters

    • func: AsyncFunction<T, unknown>

      The function to call.

    • interval: number

      The interval in milliseconds.

    Returns Promise<Exclude<T, undefined>>

pollTillDefinedAndReturnIntervalId

  • pollTillDefinedAndReturnIntervalId<T>(func: AsyncFunction<T, unknown>, interval: number): [Promise<Exclude<T, undefined>>, Timer]
  • Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null), or until a timeout is reached. It returns promise and intervalId.


    Type parameters

    • T

    Parameters

    • func: AsyncFunction<T, unknown>

      The function to call.

    • interval: number

      The interval in milliseconds.

    Returns [Promise<Exclude<T, undefined>>, Timer]

processSolidityEncodePackedArgs

  • processSolidityEncodePackedArgs(arg: Sha3Input): string
  • returns a string of the tightly packed value given based on the type


    Parameters

    • arg: Sha3Input

      the input to return the tightly packed value

    Returns string

    • the tightly packed value

randomBytes

  • randomBytes(size: number): Uint8Array
  • Returns a random byte array by the given bytes size

    @example
    console.log(web3.utils.randomBytes(32));
    > Uint8Array(32) [
    93, 172, 226, 32, 33, 176, 156, 156,
    182, 30, 240, 2, 69, 96, 174, 197,
    33, 136, 194, 241, 197, 156, 110, 111,
    66, 87, 17, 88, 67, 48, 245, 183
    ]

    Parameters

    • size: number

      The size of the random byte array returned

    Returns Uint8Array

    • random byte array

randomHex

  • randomHex(byteSize: number): string
  • Returns a random hex string by the given bytes size


    Parameters

    • byteSize: number

      The size of the random hex string returned

    Returns string

    • random hex string
    console.log(web3.utils.randomHex(32));
    > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e

rejectIfConditionAtInterval

  • rejectIfConditionAtInterval<T>(cond: AsyncFunction<undefined | T, unknown>, interval: number): [Timer, Promise<never>]
  • Sets an interval that repeatedly executes the given cond function with the specified interval between each call. If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned.


    Type parameters

    • T

    Parameters

    • cond: AsyncFunction<undefined | T, unknown>

      The function/confition to call.

    • interval: number

      The interval in milliseconds.

    Returns [Timer, Promise<never>]

    • an array with the interval ID and the Promise.

rejectIfTimeout

  • rejectIfTimeout(timeout: number, error: Error): [Timer, Promise<never>]
  • Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete

    @example
    const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out'));

    Parameters

    • timeout: number

      The timeout to enforced in milliseconds.

    • error: Error

      The error to throw if the timeout is reached.

    Returns [Timer, Promise<never>]

    A tuple of the timeout id and the promise that will be rejected if the timeout is reached.

rightPad

  • rightPad(value: Numbers, characterAmount: number, sign?: string): string
  • Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.

    @alias

    padRight


    Parameters

    • value: Numbers
    • characterAmount: number
    • optionalsign: string

    Returns string

sha3

  • sha3(data: Bytes): undefined | string
  • computes the Keccak-256 hash of the input and returns a hexstring

    @example
    console.log(web3.utils.sha3('web3.js'));
    > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a

    console.log(web3.utils.sha3(''));
    > undefined

    Parameters

    • data: Bytes

      the input to hash

    Returns undefined | string

    • the Keccak-256 hash of the input

sha3Raw

  • sha3Raw(data: Bytes): string
  • Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed.

    @example
    conosle.log(web3.utils.sha3Raw('web3.js'));
    > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a

    console.log(web3.utils.sha3Raw(''));
    > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470

    Parameters

    • data: Bytes

      the input to hash

    Returns string

    • the Keccak-256 hash of the input

soliditySha3

  • soliditySha3(...values: Sha3Input[]): undefined | string
  • Will tightly pack values given in the same way solidity would then hash. returns a hash string, or null if input is empty

    @example
    console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" }));
    > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b

    Parameters

    • rest...values: Sha3Input[]

      the input to return the tightly packed values

    Returns undefined | string

    • the keccack246 of the tightly packed values

soliditySha3Raw

  • Will tightly pack values given in the same way solidity would then hash. returns a hash string, if input is empty will return 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470

    @example
    console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" }))
    > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0

    Parameters

    Returns string

    • the keccack246 of the tightly packed values

stringToHex

  • stringToHex(str: string): string
  • @alias

    utf8ToHex


    Parameters

    • str: string

    Returns string

toAscii

  • toAscii(str: string): string
  • @alias

    hexToAscii


    Parameters

    • str: string

    Returns string

toBigInt

  • toBigInt(value: unknown): bigint
  • Auto converts any given value into it's bigint representation

    @example
    console.log(web3.utils.toBigInt(1));
    > 1n

    Parameters

    • value: unknown

      The value to convert

    Returns bigint

    • Returns the value in bigint representation

toBool

  • toBool(value: unknown): boolean
  • Parameters

    • value: unknown

    Returns boolean

toChecksumAddress

  • toChecksumAddress(address: string): string
  • Will convert an upper or lowercase Ethereum address to a checksum address.

    @example
    web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
    > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"

    Parameters

    • address: string

      An address string

    Returns string

    The checksum address

toDecimal

  • toDecimal(value: string): number | bigint
  • Converts value to it's number representation

    @alias

    hexToNumber


    Parameters

    • value: string

    Returns number | bigint

toHex

  • toHex(value: string | number | bigint | boolean | object | Uint8Array, returnType?: boolean): string
  • Auto converts any given value into it's hex representation.

    @example
    console.log(web3.utils.toHex(10));
    > 0xa

    console.log(web3.utils.toHex('0x123', true));
    > bytes

    Parameters

    • value: string | number | bigint | boolean | object | Uint8Array

      Value to be converted to hex

    • optionalreturnType: boolean

      If true, it will return the type of the value

    Returns string

toNumber

  • toNumber(value: Numbers): number | bigint
  • Converts any given value into it's number representation, if possible, else into it's bigint representation.

    @example
    console.log(web3.utils.toNumber(1));
    > 1
    console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER));
    > 9007199254740991

    console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER)));
    > 9007199254740991

    console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)));
    > 9007199254740992n

    Parameters

    Returns number | bigint

    • Returns the value in number or bigint representation

toTwosComplement

  • toTwosComplement(value: Numbers, nibbleWidth?: number): string
  • Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.

    @example
    console.log(web3.utils.toTwosComplement(13, 32));
    > 0x0000000000000000000000000000000d

    console.log(web3.utils.toTwosComplement('-0x1', 32));
    > 0xffffffffffffffffffffffffffffffff

    console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32));
    > 0x00000000000000000020000000000000

    Parameters

    • value: Numbers

      The value to be converted.

    • optionalnibbleWidth: number

      The nibble width of the hex string (default is 64).

    Returns string

    The hex string of the two’s complement.

toUtf8

  • toUtf8(input: string | Uint8Array): string
  • @alias

    hexToUtf8


    Parameters

    • input: string | Uint8Array

    Returns string

toWei

  • toWei(number: Numbers, unit: noether | wei | kwei | Kwei | babbage | femtoether | mwei | Mwei | lovelace | picoether | gwei | Gwei | shannon | nanoether | nano | szabo | microether | micro | finney | milliether | milli | ether | kether | grand | mether | gether | tether): string
  • Takes a number of a unit and converts it to wei.

    @example
    console.log(web3.utils.toWei("0.001", "ether"));
    > 1000000000000000 //(wei)

    Parameters

    • number: Numbers

      The number to convert.

    • unit: noether | wei | kwei | Kwei | babbage | femtoether | mwei | Mwei | lovelace | picoether | gwei | Gwei | shannon | nanoether | nano | szabo | microether | micro | finney | milliether | milli | ether | kether | grand | mether | gether | tether

      EtherUnits The unit of the number passed.

    Returns string

    The number converted to wei.

uint8ArrayConcat

  • uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array
  • Parameters

    • rest...parts: Uint8Array[]

    Returns Uint8Array

uint8ArrayEquals

  • uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean
  • Returns true if the two passed Uint8Arrays have the same content


    Parameters

    • a: Uint8Array
    • b: Uint8Array

    Returns boolean

utf8ToBytes

  • utf8ToBytes(str: string): Uint8Array
  • Parameters

    • str: string

    Returns Uint8Array

utf8ToHex

  • utf8ToHex(str: string): string
  • Should be called to get hex representation (prefixed by 0x) of utf8 string

    @example
    console.log(utf8ToHex('web3.js'));
    > "0x776562332e6a73"

    Parameters

    • str: string

      Utf8 string to be converted

    Returns string

    • The hex representation of the input string

uuidV4

  • uuidV4(): string

waitWithTimeout

  • waitWithTimeout<T>(awaitable: Promise<T> | AsyncFunction<T, unknown>, timeout: number, error: Error): Promise<T>
  • waitWithTimeout<T>(awaitable: Promise<T> | AsyncFunction<T, unknown>, timeout: number): Promise<T | undefined>
  • Type parameters

    • T

    Parameters

    • awaitable: Promise<T> | AsyncFunction<T, unknown>
    • timeout: number
    • error: Error

    Returns Promise<T>