Web3.js Utility Functions
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
-
TypeError: (0 , web3_utils_1.toWei) is not a function
cause Attempting to import named exports using a CommonJS `require()` statement or incorrect bundling in an ESM-only context.fixEnsure you are using `import { toWei } from 'web3-utils'` for named ESM imports. If in a CommonJS environment that doesn't transpile ESM, consider using a bundler or ensuring your Node.js version supports ESM, or downgrade to web3.js v1.x if CJS is strictly required and cannot be transpiled. -
Error: Invalid number value. Value must be a string or BigInt.
cause Passing a standard JavaScript `number` type directly to a web3-utils function (e.g., `toWei`, `toBigInt`) that expects a string or `BigInt` for precise numerical handling.fixConvert the number to a string (e.g., `value.toString()`) or explicitly cast to a `BigInt` (e.g., `BigInt(value)`) before passing it to the utility function. -
TypeError: Cannot read properties of undefined (reading 'toBN')
cause Attempting to use the `toBN` function in web3-utils v4+. This function was removed in favor of `toBigInt` when web3.js migrated to native `BigInt`.fixReplace all occurrences of `toBN` with `toBigInt`. Update numerical operations to use native `BigInt` arithmetic rather than `BigNumber.js` methods.
Warnings
- breaking web3.js v4 (and consequently web3-utils) has fundamentally shifted from using `BigNumber.js` library instances to native JavaScript `BigInt` for all large number operations. This is a major breaking change from web3.js v1.x. Functions like `toBN` are replaced by `toBigInt` and methods like `_sendPendingRequests` now catch errors differently.
- gotcha web3-utils is part of the web3.js monorepo. Using a version of `web3-utils` that is significantly different from other `web3-*` packages (e.g., `web3-eth`, `web3-eth-accounts`) can lead to runtime errors or unexpected behavior due to API inconsistencies or internal type mismatches, as hinted by `TransactionFactory.registerTransactionType` fixes in v4.12.0/v4.12.1.
- gotcha Many web3-utils functions that deal with numerical inputs (e.g., `toWei`, `fromWei`, `padLeft`, `padRight`) expect numeric values to be passed as strings or BigInts for precision. Passing a standard JavaScript `number` can lead to precision loss for very large or very small values, or even throw 'Invalid number value' errors.
Install
-
npm install web3-utils -
yarn add web3-utils -
pnpm add web3-utils
Imports
- toWei
const { toWei } = require('web3-utils')import { toWei } from 'web3-utils' - isAddress
import isAddress from 'web3-utils'
import { isAddress } from 'web3-utils' - sha3
import { sha3 } from 'web3-utils' - toBigInt
import { toBN } from 'web3-utils'import { toBigInt } from 'web3-utils'
Quickstart
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}`);