进阶 docs.web3js.org 2026-10-19 02:32:30 · 12 阅读
第16章 Web3 Utils 模块指南:实用工具函数详解
掌握实用工具函数
在本指南中,您将学习 web3 utils 包提供的各类功能。这里涵盖了不同格式的随机字节生成、Hex 值与数字间的转换、哈希函数、地址处理以及填充打包。最后一部分将演示如何比较区块编号。
安装
只安装 web3 utils 包
npm i web3-utils
或者安装整个 web3 库,然后访问 web3.utils
npm i web3
导入方式
有三种不同的方式导入 utils 包。
导入完整的 web3 库
// import web3 module
import { Web3 } from 'web3';
// no need to initialize a provider
Web3.utils.toHex('web3');
//=> 0x77656233
// initializing a provider
const web3 = new Web3('https:// eth.llamarpc.com');
// access the utils package
web3.utils.toHex('web3');
//=> 0x77656233
导入 utils 模块
// import utils module
import { utils } from 'web3';
// access the utils package
utils.toWei('1', 'ether');
导入特定方法
// import toWei and toHex functions
import { toWei, toHex } from 'web3-utils';
// usage
toWei('1', 'ether');
toHex('');
方法示例
随机 Hex 和 Bytes
// Random bytes in hex format and array format
console.log(web3.utils.randomBytes(32));
/* => array format
Uint8Array(32) [
251, 70, 124, 65, 203, 180, 92, 234,
210, 236, 72, 154, 83, 219, 171, 223,
212, 136, 117, 140, 67, 117, 86, 81,
234, 245, 148, 186, 175, 83, 98, 78
]
*/
console.log(web3.utils.randomHex(32));
/* => hex string format
0x594386dc9b2e150979416f9b2a093e01f84a37c4f8db5fc1b0d9b1dc83a12c1f
*/
如果您没有提供任何参数,这两个函数的默认值均为 32。
以太坊单位转换
我们有两个不同的函数用于在以太坊单位之间进行转换。
console.log(web3.utils.fromWei('1', 'ether'));
// 0.000000000000000001
console.log(web3.utils.toWei('1', 'ether'));
// 1_000_000_000_000_000_000
转换为 Hex 值
// most versatile one
console.log(web3.utils.toHex(10));
// 0xa
console.log(web3.utils.toHex(true));
// 0x01
console.log(web3.utils.numberToHex(10));
// 0xa
console.log(web3.utils.fromDecimal(10));
// 0xa
const arr = new Uint8Array([1, 2, 3, 4]);
console.log(web3.utils.toHex(arr));
// 0x7b2230223a312c2231223a322c2232223a332c2233223a347d
console.log(web3.utils.bytesToHex(arr));
// 0x01020304
UTF 和 ASCII 转换 console.log(web3.utils.utf8ToHex('😊'));
// 0xf09f988a
console.log(web3.utils.fromUtf8('😊'));
// 0xf09f988a
console.log(web3.utils.asciiToHex('😊'));
// 0xd83dde0a
console.log(web3.utils.toUtf8('0xf09f988a'));
// 😊
console.log(web3.utils.hexToUtf8('0xf09f988a'));
// 😊
console.log(web3.utils.hexToString('0xf09f988a'));
// 😊
// 表情符号不是 ASCII 字符,因此此操作无效
console.log(web3.utils.toAscii('0x4869'));
// Hi
console.log(web3.utils.hexToAscii('0x4869'));
// Hi
数字和 BigInt 转换 console.log(web3.utils.toNumber('0xa'));
// 10 (number)
console.log(web3.utils.hexToNumber('0xa'));
// 10 (number)
console.log(web3.utils.toDecimal('0xa'));
// 10 (number)
console.log(web3.utils.hexToNumberString('0xa'));
// 10 (string)
console.log(web3.utils.toBigInt('0xa'));
// 10n (bigint)
哈希函数 // 如果传入空字符串作为参数,两者都将返回 undefined
console.log(web3.utils.sha3('hello web3'));
// 0x6c171485a0138b7b0a49d72b570e1d9c589d42a79ae57329d90671d1ac702d74
console.log(web3.utils.soliditySha3({ type: 'string', value: 'hello web3' }));
// 0x6c171485a0138b7b0a49d72b570e1d9c589d42a79ae57329d90671d1ac702d74
地址 // isAddress() 已废弃,可使用 toCheckSumAddress() 来验证传入的十六进制字符串是否为有效的以太坊地址
// 传入全小写的地址
console.log(web3.utils.toChecksumAddress('0xa3286628134bad128faeef82f44e99aa64085c94'));
// 0xA3286628134baD128faeef82F44e99AA64085C94
// 传入错误的地址
console.log(web3.utils.toChecksumAddress('0xa3286628134bad128faeef82f44e99aa64085c9'));
// InvalidAddressError: 值无效 "0xa286628134bad128faeef82f44e99aa64085c94"。错误:无效的以太坊地址。
打包和填充 // 等同于 Solidity 中的 abi.encodePacked()(参数必须为字符串)
// 将全部转换为十六进制并打包,不进行填充
console.log(web3.utils.encodePacked('1', '1', '1'));
// 0x313131
// 将数字 10 转换为十六进制 'a',并填充 0 直到长度为 32 个字符
// 第三个参数用来填充整个十六进制字符串,这里是 '0'
console.log(web3.utils.padRight(10, 32, 0));
// 0xa0000000000000000000000000000000
console.log(web3.utils.rightPad(10, 32, 0));
// 0xa0000000000000000000000000000000
console.log(web3.utils.padLeft(10, 32, 0));
// 0x0000000000000000000000000000000a
console.log(web3.utils.leftPad(10, 32, 0));
// 0x0000000000000000000000000000000a
比较区块号 // 支持数字和格式化字符串
console.log(web3.utils.compareBlockNumbers('pending', 'latest'));
// 1
console.log(web3.utils.compareBlockNumbers('latest', 'pending'));
// -1
console.log(web3.utils.compareBlockNumbers('latest', 'latest'));
// 0
console.log(web3.utils.compareBlockNumbers(2, 2));
// 0
格式化 web3-utils 包中的 format 函数用于在等价格式之间转换数据。例如,以 Uint8Array 类型表示的字节可以格式化为十六进制字符串(如 "0xdd"),JavaScript 原生 Number 类型可以转换为 BigInt 类型。format 函数接收两个必填参数 schema 和 data,以及一个可选参数 returnFormat。schema 参数描述如何解释数据,data 参数是要格式化的数据,returnFormat 参数指定输出的格式。 下面是一些展示 format 函数用法的示例: import { format } from 'web3-utils';
import { FMT_BYTES, FMT_NUMBER } from 'web3-types';
// 把原生数字格式化为十六进制字符串
console.log(format({ format: 'uint' }, 221, { number: FMT_NUMBER.HEX }));
// ↳ 0xdd
// 把原生数字格式化为 BigInt
console.log(format({ format: 'uint' }, 221, { number: FMT_NUMBER.BIGINT }));
// ↳ 221n
// 把字符串形式的数字格式化为十六进制字符串
console.log(format({ format: 'uint' }, '221', { number: FMT_NUMBER.HEX }));
// ↳ 0xdd
// 把 Uint8Array 字节数组格式化为十六进制字符串
console.log(
format({ format: 'bytes' }, new Uint8Array([2, 33]), {
bytes: FMT_BYTES.HEX,
}),
);
// ↳ 0x0221
// 格式化一个数组
console.log(
format({ type: 'array', items: { format: 'uint' } }, ['221', 1983], {
number: FMT_NUMBER.HEX,
}),
);
// ↳ [ '0xdd', '0x7bf' ]
// 0x7b2230223a312c2231223a322c2232223a332c2233223a347d
console.log(web3.utils.bytesToHex(arr));
// 0x01020304
UTF 和 ASCII 转换 console.log(web3.utils.utf8ToHex('😊'));
// 0xf09f988a
console.log(web3.utils.fromUtf8('😊'));
// 0xf09f988a
console.log(web3.utils.asciiToHex('😊'));
// 0xd83dde0a
console.log(web3.utils.toUtf8('0xf09f988a'));
// 😊
console.log(web3.utils.hexToUtf8('0xf09f988a'));
// 😊
console.log(web3.utils.hexToString('0xf09f988a'));
// 😊
// 表情符号不是 ASCII 字符,因此此操作无效
console.log(web3.utils.toAscii('0x4869'));
// Hi
console.log(web3.utils.hexToAscii('0x4869'));
// Hi
数字和 BigInt 转换 console.log(web3.utils.toNumber('0xa'));
// 10 (number)
console.log(web3.utils.hexToNumber('0xa'));
// 10 (number)
console.log(web3.utils.toDecimal('0xa'));
// 10 (number)
console.log(web3.utils.hexToNumberString('0xa'));
// 10 (string)
console.log(web3.utils.toBigInt('0xa'));
// 10n (bigint)
哈希函数 // 如果传入空字符串作为参数,两者都将返回 undefined
console.log(web3.utils.sha3('hello web3'));
// 0x6c171485a0138b7b0a49d72b570e1d9c589d42a79ae57329d90671d1ac702d74
console.log(web3.utils.soliditySha3({ type: 'string', value: 'hello web3' }));
// 0x6c171485a0138b7b0a49d72b570e1d9c589d42a79ae57329d90671d1ac702d74
地址 // isAddress() 已废弃,可使用 toCheckSumAddress() 来验证传入的十六进制字符串是否为有效的以太坊地址
// 传入全小写的地址
console.log(web3.utils.toChecksumAddress('0xa3286628134bad128faeef82f44e99aa64085c94'));
// 0xA3286628134baD128faeef82F44e99AA64085C94
// 传入错误的地址
console.log(web3.utils.toChecksumAddress('0xa3286628134bad128faeef82f44e99aa64085c9'));
// InvalidAddressError: 值无效 "0xa286628134bad128faeef82f44e99aa64085c94"。错误:无效的以太坊地址。
打包和填充 // 等同于 Solidity 中的 abi.encodePacked()(参数必须为字符串)
// 将全部转换为十六进制并打包,不进行填充
console.log(web3.utils.encodePacked('1', '1', '1'));
// 0x313131
// 将数字 10 转换为十六进制 'a',并填充 0 直到长度为 32 个字符
// 第三个参数用来填充整个十六进制字符串,这里是 '0'
console.log(web3.utils.padRight(10, 32, 0));
// 0xa0000000000000000000000000000000
console.log(web3.utils.rightPad(10, 32, 0));
// 0xa0000000000000000000000000000000
console.log(web3.utils.padLeft(10, 32, 0));
// 0x0000000000000000000000000000000a
console.log(web3.utils.leftPad(10, 32, 0));
// 0x0000000000000000000000000000000a
比较区块号 // 支持数字和格式化字符串
console.log(web3.utils.compareBlockNumbers('pending', 'latest'));
// 1
console.log(web3.utils.compareBlockNumbers('latest', 'pending'));
// -1
console.log(web3.utils.compareBlockNumbers('latest', 'latest'));
// 0
console.log(web3.utils.compareBlockNumbers(2, 2));
// 0
格式化 web3-utils 包中的 format 函数用于在等价格式之间转换数据。例如,以 Uint8Array 类型表示的字节可以格式化为十六进制字符串(如 "0xdd"),JavaScript 原生 Number 类型可以转换为 BigInt 类型。format 函数接收两个必填参数 schema 和 data,以及一个可选参数 returnFormat。schema 参数描述如何解释数据,data 参数是要格式化的数据,returnFormat 参数指定输出的格式。 下面是一些展示 format 函数用法的示例: import { format } from 'web3-utils';
import { FMT_BYTES, FMT_NUMBER } from 'web3-types';
// 把原生数字格式化为十六进制字符串
console.log(format({ format: 'uint' }, 221, { number: FMT_NUMBER.HEX }));
// ↳ 0xdd
// 把原生数字格式化为 BigInt
console.log(format({ format: 'uint' }, 221, { number: FMT_NUMBER.BIGINT }));
// ↳ 221n
// 把字符串形式的数字格式化为十六进制字符串
console.log(format({ format: 'uint' }, '221', { number: FMT_NUMBER.HEX }));
// ↳ 0xdd
// 把 Uint8Array 字节数组格式化为十六进制字符串
console.log(
format({ format: 'bytes' }, new Uint8Array([2, 33]), {
bytes: FMT_BYTES.HEX,
}),
);
// ↳ 0x0221
// 格式化一个数组
console.log(
format({ type: 'array', items: { format: 'uint' } }, ['221', 1983], {
number: FMT_NUMBER.HEX,
}),
);
// ↳ [ '0xdd', '0x7bf' ]
// 格式化一个包含多个属性的对象
console.log(
format(
{
type: 'object',
properties: {
aNumber: { format: 'uint' },
someBytes: { format: 'bytes' },
},
},
{ aNumber: '221', someBytes: new Uint8Array([2, 33]) },
{ bytes: FMT_BYTES.UINT8ARRAY, number: FMT_NUMBER.HEX },
),
);
// ↳ { aNumber: '0xdd', someBytes: Uint8Array(2) [ 2, 33 ] }
返回格式
支持以下返回格式:
字节
- FMT_BYTES.HEX:十六进制字符串(如 "0xdd")
- FMT_BYTES.UINT8ARRAY:Uint8Array(如 [ 2, 33 ])
数字
- FMT_NUMBER.BIGINT:BigInt(如 221n)
- FMT_NUMBER.HEX:十六进制字符串(如 "0xdd")
- FMT_NUMBER.NUMBER:Number(如 221)
- FMT_NUMBER.STR:字符串(如 "221")