utils
Index
References
Namespaces
Classes
Type Aliases
Functions
- asciiToHex
- bytesToHex
- bytesToUint8Array
- checkAddressCheckSum
- compareBlockNumbers
- convert
- convertScalarValue
- encodePacked
- format
- fromAscii
- fromDecimal
- fromTwosComplement
- fromUtf8
- fromWei
- getStorageSlotNumForLongString
- hexToAscii
- hexToBytes
- hexToNumber
- hexToNumberString
- hexToString
- hexToUtf8
- isAddress
- isBloom
- isContractAddressInBloom
- isContractInitOptions
- isDataFormat
- isHex
- isHexStrict
- isInBloom
- isNullish
- isPromise
- isTopic
- isTopicInBloom
- isUint8Array
- isUserEthereumAddressInBloom
- keccak256Wrapper
- leftPad
- mergeDeep
- numberToHex
- padLeft
- padRight
- pollTillDefined
- pollTillDefinedAndReturnIntervalId
- processSolidityEncodePackedArgs
- randomBytes
- randomHex
- rejectIfConditionAtInterval
- rejectIfTimeout
- rightPad
- sha3
- sha3Raw
- soliditySha3
- soliditySha3Raw
- stringToHex
- toAscii
- toBigInt
- toBool
- toChecksumAddress
- toDecimal
- toHex
- toNumber
- toTwosComplement
- toUtf8
- toWei
- uint8ArrayConcat
- uint8ArrayEquals
- utf8ToBytes
- utf8ToHex
- uuidV4
- waitWithTimeout
References
AbiItem
Eip1193Provider
SocketProvider
isBatchRequest
isBatchResponse
isResponseRpcError
isResponseWithError
isResponseWithNotification
isResponseWithResult
isSubscriptionResult
isValidResponse
keccak256
setRequestIdStart
toBatchPayload
toPayload
validateResponse
Namespaces
jsonRpc
isBatchRequest
Parameters
request: JsonRpcBatchRequest | JsonRpcOptionalRequest<unknown> | JsonRpcRequest<unknown>
Returns request is JsonRpcBatchRequest
isBatchResponse
Type parameters
- Result = unknown
- Error_1 = unknown
Parameters
response: JsonRpcResponse<Result, Error_1>
Returns response is JsonRpcBatchResponse<Result, Error_1>
isResponseRpcError
Parameters
rpcError: JsonRpcResponseWithError<JsonRpcResult>
Returns boolean
isResponseWithError
Type parameters
- Error_1 = unknown
- Result = unknown
Parameters
response: JsonRpcResponse<Result, Error_1>
Returns response is JsonRpcResponseWithError<Error_1>
isResponseWithNotification
Type parameters
- Result
Parameters
response: JsonRpcSubscriptionResult | JsonRpcNotification<Result>
Returns response is JsonRpcNotification<Result>
isResponseWithResult
Type parameters
- Result = unknown
- Error_1 = unknown
Parameters
response: JsonRpcResponse<Result, Error_1>
Returns response is JsonRpcResponseWithResult<Result>
isSubscriptionResult
Type parameters
- Result
Parameters
response: JsonRpcSubscriptionResult | JsonRpcNotification<Result>
Returns response is JsonRpcSubscriptionResult
isValidResponse
Type parameters
- Result = unknown
- Error_1 = unknown
Parameters
response: JsonRpcResponse<Result, Error_1>
Returns boolean
setRequestIdStart
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
Parameters
requests: JsonRpcOptionalRequest<unknown>[]
Returns JsonRpcBatchRequest
toPayload
Type parameters
- ParamType = unknown[]
Parameters
request: JsonRpcOptionalRequest<ParamType>
Returns JsonRpcPayload<ParamType>
validateResponse
Type parameters
- Result = unknown
- Error_1 = unknown
Parameters
response: JsonRpcResponse<Result, Error_1>
Returns boolean
Classes
ChunkResponseParser
constructor
Parameters
eventEmitter: EventEmitter<string | symbol, any>
autoReconnect: boolean
Returns ChunkResponseParser
onError
Parameters
optionalclearQueues: () => void
Returns void
parseResponse
Parameters
data: string
Returns JsonRpcResponse<JsonRpcResult, JsonRpcResult>[]
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
Returns number
setMaxListeners
Parameters
maxListeners: number
Returns this
Web3DeferredPromise
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
Type parameters
- T
Parameters
optional__namedParameters: { eagerStart: boolean; timeout: number; timeoutMessage: string }
eagerStart: boolean
timeout: number
timeoutMessage: string
Returns Web3DeferredPromise<T>
[toStringTag]
state
Returns the current state of the promise.
Returns pending | fulfilled | rejected
'pending' | 'fulfilled' | 'rejected'
catch
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
Parameters
optionalonfinally: () => void
(optional) The callback to execute when the promise is settled (fulfilled or rejected).
Returns Promise<T>
reject
Rejects the current promise.
Parameters
optionalreason: unknown
The reason to reject the promise with.
Returns void
resolve
Resolves the current promise.
Parameters
value: T | PromiseLike<T>
The value to resolve the promise with.
Returns void
startTimer
Starts the timeout timer for the promise.
Returns void
then
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
Type parameters
- T
- K = unknown
Type declaration
Parameters
rest...args: K[]
Returns Promise<T>
EtherUnits
ReconnectOptions
Type declaration
autoReconnect: boolean
delay: number
maxAttempts: number
Timeout
Timer
Functions
asciiToHex
Should be called to get hex representation (prefixed by 0x) of ascii string
Parameters
str: string
String to be converted to hex
Returns string
- Hex string
bytesToHex
Convert a byte array to a hex string
Parameters
bytes: Bytes
Byte array to be converted
Returns string
- The hex string representation of the input byte array
bytesToUint8Array
Convert a value from bytes to Uint8Array
Parameters
data: Bytes
Data to be converted
Returns Uint8Array
- The Uint8Array representation of the input data
checkAddressCheckSum
Checks the checksum of a given address. Will also return false on non-checksum addresses.
Parameters
data: string
Returns boolean
compareBlockNumbers
Compares between block A and block B
Parameters
blockA: BlockNumberOrTag
Block number or string
blockB: BlockNumberOrTag
Block number or string
Returns -1 | 0 | 1
- Returns -1 if a < b, returns 1 if a > b and returns 0 if a == b
convert
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
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
rest...values: Sha3Input[]
Returns string
format
Given data that can be interpreted according to the provided schema, returns equivalent data that has been formatted according to the provided return format.
Type parameters
- DataType: unknown
- ReturnType_1: DataFormat
Parameters
schema: ValidationSchemaInput | Schema
how to interpret the data
data: DataType
data to be formatted
optionalreturnFormat: ReturnType_1
how to format the data
Returns FormatType<DataType, ReturnType_1>
- formatted data
fromAscii
Parameters
str: string
Returns string
fromDecimal
Converts value to it's hex representation
Parameters
value: Numbers
optionalhexstrict: boolean
Returns string
fromTwosComplement
Converts the twos complement into a decimal number or big int.
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
Parameters
str: string
Returns string
fromWei
Takes a number of wei and converts it to any other ether unit.
Parameters
number: Numbers
The value in wei
unit: number | 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
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
Should be called to get ascii from it's hex representation
Parameters
str: string
Hex string to be converted to ascii
Returns string
- Ascii string
hexToBytes
Convert a hex string to a byte array
Parameters
bytes: string
Returns Uint8Array
- The byte array representation of the input hex string
hexToNumber
Converts value to it's number representation
Parameters
value: string
Hex string to be converted
Returns number | bigint
- The number representation of the input value
hexToNumberString
Converts value to it's decimal representation in string
Parameters
data: string
Returns string
- The decimal representation of the input value
hexToString
Parameters
str: string
Returns string
hexToUtf8
Should be called to get utf8 from it's hex representation
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.
Parameters
value: ValidInputTypes
optionalcheckChecksum: boolean
Returns boolean
isBloom
Returns true if the bloom is a valid bloom https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7
Parameters
bloom: ValidInputTypes
Returns boolean
isContractAddressInBloom
Returns true if the contract address is part of the given bloom. note: false positives are possible.
Parameters
bloom: string
contractAddress: string
Returns boolean
isContractInitOptions
Parameters
options: unknown
Returns options is ContractInitOptions
isDataFormat
Parameters
dataFormat: unknown
Returns dataFormat is DataFormat
isHex
returns true if input is a hexstring, number or bigint
Parameters
hex: ValidInputTypes
Returns boolean
isHexStrict
Parameters
hex: ValidInputTypes
Returns boolean
isInBloom
Returns true if the value is part of the given bloom note: false positives are possible.
Parameters
bloom: string
value: string | Uint8Array
Returns boolean
isNullish
Parameters
item: unknown
Returns item is undefined | null
isPromise
An alternative to the node function
isPromise
that exists inutil/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 anobject
or afunction
that has athen
function. And returnsfalse
otherwise.
isTopic
Checks if its a valid topic
Parameters
topic: string
Returns boolean
isTopicInBloom
Returns true if the topic is part of the given bloom. note: false positives are possible.
Parameters
bloom: string
topic: string
Returns boolean
isUint8Array
Parameters
data: unknown
Returns data is Uint8Array
isUserEthereumAddressInBloom
Returns true if the ethereum users address is part of the given bloom note: false positives are possible.
Parameters
bloom: string
ethereumAddress: string
Returns boolean
keccak256Wrapper
A wrapper for ethereum-cryptography/keccak256 to allow hashing a
string
and abigint
in addition toUInt8Array
Parameters
data: string | number | bigint | Uint8Array | readonly number[]
the input to hash
Returns string
- the Keccak-256 hash of the input
leftPad
Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.
Parameters
value: Numbers
characterAmount: number
optionalsign: string
Returns string
mergeDeep
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
Converts value to it's hex representation
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
Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.
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
Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.
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
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
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
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
Returns a random byte array by the given bytes size
Parameters
size: number
The size of the random byte array returned
Returns Uint8Array
- random byte array
randomHex
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
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/condition to call.
interval: number
The interval in milliseconds.
Returns [Timer, Promise<never>]
- an array with the interval ID and the Promise.
rejectIfTimeout
Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete
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
Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.
Parameters
value: Numbers
characterAmount: number
optionalsign: string
Returns string
sha3
computes the Keccak-256 hash of the input and returns a hexstring
Parameters
data: Bytes
the input to hash
Returns undefined | string
- the Keccak-256 hash of the input
sha3Raw
Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed.
Parameters
data: Bytes
the input to hash
Returns string
- the Keccak-256 hash of the input
soliditySha3
Will tightly pack values given in the same way solidity would then hash. returns a hash string, or null if input is empty
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
Parameters
rest...values: TypedObject[] | TypedObjectAbbreviated[]
the input to return the tightly packed values
Returns string
- the keccack246 of the tightly packed values
stringToHex
Parameters
str: string
Returns string
toAscii
Parameters
str: string
Returns string
toBigInt
Auto converts any given value into it's bigint representation
Parameters
value: unknown
The value to convert
Returns bigint
- Returns the value in bigint representation
toBool
Parameters
value: unknown
Returns boolean
toChecksumAddress
Will convert an upper or lowercase Ethereum address to a checksum address.
Parameters
address: string
An address string
Returns string
The checksum address
toDecimal
Converts value to it's number representation
Parameters
value: string
Returns number | bigint
toHex
Auto converts any given value into it's hex representation.
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
Converts any given value into it's number representation, if possible, else into it's bigint representation.
Parameters
value: Numbers
The value to convert
Returns number | bigint
- Returns the value in number or bigint representation
toTwosComplement
Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.
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
Parameters
input: string | Uint8Array
Returns string
toWei
Takes a number of a unit and converts it to wei.
Parameters
number: Numbers
The number to convert.
unit: number | 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
Parameters
rest...parts: Uint8Array[]
Returns Uint8Array
uint8ArrayEquals
Returns true if the two passed Uint8Arrays have the same content
Parameters
a: Uint8Array
b: Uint8Array
Returns boolean
utf8ToBytes
Parameters
str: string
Returns Uint8Array
utf8ToHex
Should be called to get hex representation (prefixed by 0x) of utf8 string
Parameters
str: string
Utf8 string to be converted
Returns string
- The hex representation of the input string
uuidV4
Generate a version 4 (random) uuid https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5
Returns string
- A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx
waitWithTimeout
Type parameters
- T
Parameters
awaitable: Promise<T> | AsyncFunction<T, unknown>
timeout: number
error: Error
Returns Promise<T>
Optionally use to make the jsonrpc
id
start from a specific number. Without calling this function, theid
will be filled with a Uuid. But after this being called with a number, theid
will be a number starting from the providedstart
variable. However, ifundefined
was passed to this function, theid
will be a Uuid again.