Web3.js Utility Functions

4.3.3 · active · verified Sun Apr 19

web3-utils is a core package within the web3.js ecosystem, providing a collection of essential utility functions for Ethereum dApp development. These utilities cover common tasks such as converting between different Ether units (e.g., Ether to Wei), validating Ethereum addresses, cryptographic hashing (like SHA3), and handling large numbers. As of the provided information, the package version is 4.3.3, though recent releases indicate active development up to v4.16.0 within the broader web3.js monorepo. It maintains a frequent release cadence, often aligning with fixes and features across the web3.js suite. A key differentiator is its tight integration and API consistency with the rest of the web3.js library, making it the de-facto choice for projects built on web3.js. It ships with full TypeScript support, ensuring type safety for modern JavaScript projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates common web3-utils functions: converting between Ether and Wei, validating an Ethereum address, calculating a SHA3 hash, and using `toBigInt` for large number handling.

import { toWei, fromWei, isAddress, sha3, toBigInt } from 'web3-utils';

// 1. Unit Conversion
const ethValue = '1.5';
const weiValue = toWei(ethValue, 'ether');
console.log(`1.5 Ether in Wei: ${weiValue}`); // Outputs a BigInt

const backToEth = fromWei(weiValue, 'ether');
console.log(`Wei back to Ether: ${backToEth}`); // Outputs a string representation

// 2. Address Validation
const validAddress = '0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B';
const invalidAddress = '0x123invalidAddress';

console.log(`Is '${validAddress}' a valid address? ${isAddress(validAddress)}`);
console.log(`Is '${invalidAddress}' a valid address? ${isAddress(invalidAddress)}`);

// 3. Hashing
const dataToHash = 'Hello Web3!';
const hashedData = sha3(dataToHash);
console.log(`SHA3 hash of '${dataToHash}': ${hashedData}`);

// 4. BigInt Handling (v4+)
const bigNumberString = '1000000000000000000'; // 1 Ether in Wei
const bigIntValue = toBigInt(bigNumberString);
console.log(`Converted to BigInt: ${bigIntValue}, type: ${typeof bigIntValue}`);

view raw JSON →