Skip to main content

Utils

This package provides utility functions for Ethereum dapps and other web3.js packages.

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

import { Web3 } from 'web3';
const web3 = new Web3();

const value = web3.utils.fromWei("1", "ether")

For using individual package install web3-utils package using npm i web3-utils or yarn add web3-utils and only import required functions. This is more efficient approach for building lightweight applications.

import { fromWei, soliditySha3Raw } from 'web3-utils';

console.log(fromWei("1", "ether"));
console.log(soliditySha3Raw({ type: "string", value: "helloworld" }))

Functions

asciiToHex

asciiToHex(str): string

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

Parameters

NameTypeDescription
strstringString to be converted to hex

Returns

string

  • Hex string

Example

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

Defined in

packages/web3-utils/src/converters.ts:290


bytesToHex

bytesToHex(bytes): string

Convert a byte array to a hex string

Parameters

NameTypeDescription
bytesBytesByte array to be converted

Returns

string

  • The hex string representation of the input byte array

Example

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

#### Defined in

[packages/web3-utils/src/converters.ts:124](https://github.com/web3/web3.js/blob/b89462d/packages/web3-utils/src/converters.ts#L124)

___

### bytesToUint8Array

**bytesToUint8Array**(`data`): `Uint8Array`

Convert a value from bytes to Uint8Array

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `Bytes` | Data to be converted |

#### Returns

`Uint8Array`

- The Uint8Array representation of the input data

**`Example`**

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

Defined in

packages/web3-utils/src/converters.ts:90


checkAddressCheckSum

checkAddressCheckSum(data): boolean

Checks the checksum of a given address. Will also return false on non-checksum addresses.

Parameters

NameType
datastring

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/address.d.ts:5


compareBlockNumbers

compareBlockNumbers(blockA, blockB): 0 | 1 | -1

Compares between block A and block B

Parameters

NameTypeDescription
blockABlockNumberOrTagBlock number or string
blockBBlockNumberOrTagBlock number or string

Returns

0 | 1 | -1

  • Returns -1 if a < b, returns 1 if a > b and returns 0 if a == b

Example

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

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

Defined in

packages/web3-utils/src/validation.ts:127


encodePacked

encodePacked(...values): string

Encode packed arguments to a hexstring

Parameters

NameType
...valuesSha3Input[]

Returns

string

Defined in

packages/web3-utils/src/hash.ts:353


fromAscii

fromAscii(str): string

Parameters

NameType
strstring

Returns

string

Alias

asciiToHex

Defined in

packages/web3-utils/src/converters.ts:290


fromDecimal

fromDecimal(value, hexstrict?): string

Converts value to it's hex representation

Parameters

NameType
valueNumbers
hexstrict?boolean

Returns

string

Alias

numberToHex

Defined in

packages/web3-utils/src/converters.ts:181


fromTwosComplement

fromTwosComplement(value, nibbleWidth?): number | bigint

Converts the twos complement into a decimal number or big int.

Parameters

NameTypeDefault valueDescription
valueNumbersundefinedThe value to be converted.
nibbleWidthnumber64The nibble width of the hex string (default is 64).

Returns

number | bigint

The decimal number or big int.

Example

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

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

Defined in

packages/web3-utils/src/string_manipulation.ts:148


fromUtf8

fromUtf8(str): string

Parameters

NameType
strstring

Returns

string

Alias

utf8ToHex

Defined in

packages/web3-utils/src/converters.ts:226


fromWei

fromWei(number, unit): string

Takes a number of wei and converts it to any other ether unit.

Parameters

NameTypeDescription
numberNumbersThe 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

Example

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

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

Defined in

packages/web3-utils/src/converters.ts:476


getStorageSlotNumForLongString

getStorageSlotNumForLongString(mainSlotNumber): undefined | string

Get slot number for storage long string in contract. Basically for getStorage method returns slotNumber where will data placed

Parameters

NameTypeDescription
mainSlotNumberstring | numberthe slot number where will be stored hash of long string

Returns

undefined | string

  • the slot number where will be stored long string

Defined in

packages/web3-utils/src/hash.ts:394


hexToAscii

hexToAscii(str): string

Should be called to get ascii from it's hex representation

Parameters

NameTypeDescription
strstringHex string to be converted to ascii

Returns

string

  • Ascii string

Example

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

Defined in

packages/web3-utils/src/converters.ts:317


hexToBytes

hexToBytes(bytes): Uint8Array

Convert a hex string to a byte array

Parameters

NameType
bytesstring

Returns

Uint8Array

  • The byte array representation of the input hex string

Example

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

Defined in

packages/web3-utils/src/converters.ts:138


hexToNumber

hexToNumber(value): number | bigint

Converts value to it's number representation

Parameters

NameTypeDescription
valuestringHex string to be converted

Returns

number | bigint

  • The number representation of the input value

Example

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

Defined in

packages/web3-utils/src/converters.ts:156


hexToNumberString

hexToNumberString(data): string

Converts value to it's decimal representation in string

Parameters

NameType
datastring

Returns

string

  • The decimal representation of the input value

Example

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

Defined in

packages/web3-utils/src/converters.ts:212


hexToString

hexToString(str): string

Parameters

NameType
strstring

Returns

string

Alias

hexToUtf8

Defined in

packages/web3-utils/src/converters.ts:259


hexToUtf8

hexToUtf8(str): string

Should be called to get utf8 from it's hex representation

Parameters

NameTypeDescription
strstringHex string to be converted

Returns

string

  • Utf8 string

Example

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

Defined in

packages/web3-utils/src/converters.ts:259


isAddress

isAddress(value, checkChecksum?): boolean

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

NameType
valueValidInputTypes
checkChecksum?boolean

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/address.d.ts:9


isBloom

isBloom(bloom): boolean

Returns true if the bloom is a valid bloom https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7

Parameters

NameType
bloomValidInputTypes

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/bloom.d.ts:6


isContractAddressInBloom

isContractAddressInBloom(bloom, contractAddress): boolean

Returns true if the contract address is part of the given bloom. note: false positives are possible.

Parameters

NameType
bloomstring
contractAddressstring

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/bloom.d.ts:20


isHex

isHex(hex): boolean

returns true if input is a hexstring, number or bigint

Parameters

NameType
hexValidInputTypes

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/string.d.ts:15


isHexStrict

isHexStrict(hex): boolean

Parameters

NameType
hexValidInputTypes

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/string.d.ts:6


isInBloom

isInBloom(bloom, value): boolean

Returns true if the value is part of the given bloom note: false positives are possible.

Parameters

NameType
bloomstring
valuestring | Uint8Array

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/bloom.d.ts:11


isTopic

isTopic(topic): boolean

Checks if its a valid topic

Parameters

NameType
topicstring

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/topic.d.ts:4


isTopicInBloom

isTopicInBloom(bloom, topic): boolean

Returns true if the topic is part of the given bloom. note: false positives are possible.

Parameters

NameType
bloomstring
topicstring

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/topic.d.ts:9


isUserEthereumAddressInBloom

isUserEthereumAddressInBloom(bloom, ethereumAddress): boolean

Returns true if the ethereum users address is part of the given bloom note: false positives are possible.

Parameters

NameType
bloomstring
ethereumAddressstring

Returns

boolean

Deprecated

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

Defined in

packages/web3-validator/lib/commonjs/validation/bloom.d.ts:15


keccak256Wrapper

keccak256Wrapper(data): string

A wrapper for ethereum-cryptography/keccak256 to allow hashing a string and a bigint in addition to UInt8Array

Parameters

NameTypeDescription
datastring | number | bigint | Uint8Array | readonly number[]the input to hash

Returns

string

  • the Keccak-256 hash of the input

Example

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

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

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

Defined in

packages/web3-utils/src/hash.ts:149


leftPad

leftPad(value, characterAmount, sign?): string

Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.

Parameters

NameTypeDefault value
valueNumbersundefined
characterAmountnumberundefined
signstring'0'

Returns

string

Alias

padLeft

Defined in

packages/web3-utils/src/string_manipulation.ts:41


numberToHex

numberToHex(value, hexstrict?): string

Converts value to it's hex representation

Parameters

NameTypeDescription
valueNumbersValue to be converted
hexstrict?booleanAdd padding to converted value if odd, to make it hexstrict

Returns

string

  • The hex representation of the input value

Example

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

Defined in

packages/web3-utils/src/converters.ts:181


padLeft

padLeft(value, characterAmount, sign?): string

Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.

Parameters

NameTypeDefault valueDescription
valueNumbersundefinedThe value to be padded.
characterAmountnumberundefinedThe amount of characters the string should have.
signstring'0'The sign to be added (default is 0).

Returns

string

The padded string.

Example


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

Defined in

packages/web3-utils/src/string_manipulation.ts:41


padRight

padRight(value, characterAmount, sign?): string

Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.

Parameters

NameTypeDefault valueDescription
valueNumbersundefinedThe value to be padded.
characterAmountnumberundefinedThe amount of characters the string should have.
signstring'0'The sign to be added (default is 0).

Returns

string

The padded string.

Example

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

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

Defined in

packages/web3-utils/src/string_manipulation.ts:73


processSolidityEncodePackedArgs

processSolidityEncodePackedArgs(arg): string

returns a string of the tightly packed value given based on the type

Parameters

NameTypeDescription
argSha3Inputthe input to return the tightly packed value

Returns

string

  • the tightly packed value

Defined in

packages/web3-utils/src/hash.ts:336


randomBytes

randomBytes(size): Uint8Array

Returns a random byte array by the given bytes size

Parameters

NameTypeDescription
sizenumberThe size of the random byte array returned

Returns

Uint8Array

  • random byte array

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
]

Defined in

packages/web3-utils/src/random.ts:41


randomHex

randomHex(byteSize): string

Returns a random hex string by the given bytes size

Parameters

NameTypeDescription
byteSizenumberThe size of the random hex string returned

Returns

string

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

Defined in

packages/web3-utils/src/random.ts:53


rightPad

rightPad(value, characterAmount, sign?): string

Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.

Parameters

NameTypeDefault value
valueNumbersundefined
characterAmountnumberundefined
signstring'0'

Returns

string

Alias

padRight

Defined in

packages/web3-utils/src/string_manipulation.ts:73


sha3

sha3(data): undefined | string

computes the Keccak-256 hash of the input and returns a hexstring

Parameters

NameTypeDescription
dataBytesthe input to hash

Returns

undefined | string

  • the Keccak-256 hash of the input

Example

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

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

Defined in

packages/web3-utils/src/hash.ts:91


sha3Raw

sha3Raw(data): 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.

Parameters

NameTypeDescription
dataBytesthe input to hash

Returns

string

  • the Keccak-256 hash of the input

Example

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

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

Defined in

packages/web3-utils/src/hash.ts:123


soliditySha3

soliditySha3(...values): 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

Parameters

NameTypeDescription
...valuesSha3Input[]the input to return the tightly packed values

Returns

undefined | string

  • the keccack246 of the tightly packed values

Example

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

Defined in

packages/web3-utils/src/hash.ts:370


soliditySha3Raw

soliditySha3Raw(...values): string

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

NameTypeDescription
...valuesTypedObject[] | TypedObjectAbbreviated[]the input to return the tightly packed values

Returns

string

  • the keccack246 of the tightly packed values

Example

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

Defined in

packages/web3-utils/src/hash.ts:385


stringToHex

stringToHex(str): string

Parameters

NameType
strstring

Returns

string

Alias

utf8ToHex

Defined in

packages/web3-utils/src/converters.ts:226


toAscii

toAscii(str): string

Parameters

NameType
strstring

Returns

string

Alias

hexToAscii

Defined in

packages/web3-utils/src/converters.ts:317


toBigInt

toBigInt(value): bigint

Auto converts any given value into it's bigint representation

Parameters

NameTypeDescription
valueunknownThe value to convert

Returns

bigint

  • Returns the value in bigint representation

Example

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

Defined in

packages/web3-utils/src/converters.ts:441


toChecksumAddress

toChecksumAddress(address): string

Will convert an upper or lowercase Ethereum address to a checksum address.

Parameters

NameTypeDescription
addressstringAn address string

Returns

string

The checksum address

Example

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

Defined in

packages/web3-utils/src/converters.ts:584


toDecimal

toDecimal(value): number | bigint

Converts value to it's number representation

Parameters

NameType
valuestring

Returns

number | bigint

Alias

hexToNumber

Defined in

packages/web3-utils/src/converters.ts:156


toHex

toHex(value, returnType?): string

Auto converts any given value into it's hex representation.

Parameters

NameTypeDescription
valuestring | number | bigint | boolean | object | Uint8ArrayValue to be converted to hex
returnType?booleanIf true, it will return the type of the value

Returns

string

Example

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

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

Defined in

packages/web3-utils/src/converters.ts:341


toNumber

toNumber(value): number | bigint

Converts any given value into it's number representation, if possible, else into it's bigint representation.

Parameters

NameTypeDescription
valueNumbersThe value to convert

Returns

number | bigint

  • Returns the value in number or 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

Defined in

packages/web3-utils/src/converters.ts:407


toTwosComplement

toTwosComplement(value, nibbleWidth?): string

Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.

Parameters

NameTypeDefault valueDescription
valueNumbersundefinedThe value to be converted.
nibbleWidthnumber64The nibble width of the hex string (default is 64).

Returns

string

The hex string of the two’s complement.

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

Defined in

packages/web3-utils/src/string_manipulation.ts:115


toUtf8

toUtf8(input): string

Parameters

NameType
inputstring | Uint8Array

Returns

string

Alias

hexToUtf8

Defined in

packages/web3-utils/src/converters.ts:264


toWei

toWei(number, unit): string

Takes a number of a unit and converts it to wei.

Parameters

NameTypeDescription
numberNumbersThe 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.

Example

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

Defined in

packages/web3-utils/src/converters.ts:534


utf8ToHex

utf8ToHex(str): string

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

Parameters

NameTypeDescription
strstringUtf8 string to be converted

Returns

string

  • The hex representation of the input string

Example

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

Defined in

packages/web3-utils/src/converters.ts:226


uuidV4

uuidV4(): string

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

Example

console.log(web3.utils.uuidV4());
> "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

Defined in

packages/web3-utils/src/uuid.ts:35