0
# Utilities and Encoding
1
2
The utils module provides essential utility functions for data conversion, validation, hashing, and Ethereum-specific operations. These utilities handle common tasks like unit conversion, address validation, data formatting, and cryptographic operations.
3
4
## Capabilities
5
6
### Unit Conversion
7
8
Convert between different Ethereum units and number formats.
9
10
```typescript { .api }
11
/**
12
* Convert value to wei (smallest unit)
13
* @param value - Value to convert
14
* @param unit - Unit to convert from (ether, gwei, etc.)
15
* @returns Value in wei as string
16
*/
17
toWei(value: NumberLike, unit?: EtherUnits): string;
18
19
/**
20
* Convert value from wei to specified unit
21
* @param value - Value in wei to convert
22
* @param unit - Unit to convert to (ether, gwei, etc.)
23
* @returns Converted value as string
24
*/
25
fromWei(value: NumberLike, unit?: EtherUnits): string;
26
27
/**
28
* Convert value to hex representation
29
* @param value - Value to convert (number, string, bytes, boolean)
30
* @returns Hex string with 0x prefix
31
*/
32
toHex(value: Numbers | Bytes | Address | boolean): HexString;
33
34
/**
35
* Convert hex to number
36
* @param hex - Hex string to convert
37
* @returns Number value
38
*/
39
hexToNumber(hex: HexString): number;
40
41
/**
42
* Convert hex to bigint
43
* @param hex - Hex string to convert
44
* @returns BigInt value
45
*/
46
hexToBigInt(hex: HexString): bigint;
47
48
/**
49
* Convert number to hex
50
* @param value - Number to convert
51
* @returns Hex string
52
*/
53
numberToHex(value: Numbers): HexString;
54
```
55
56
**Usage Examples:**
57
58
```typescript
59
// Unit conversions
60
const weiValue = web3.utils.toWei('1', 'ether');
61
console.log(weiValue); // '1000000000000000000'
62
63
const etherValue = web3.utils.fromWei('1000000000000000000', 'ether');
64
console.log(etherValue); // '1'
65
66
const gweiValue = web3.utils.fromWei('20000000000', 'gwei');
67
console.log(gweiValue); // '20'
68
69
// Hex conversions
70
const hexValue = web3.utils.toHex(255);
71
console.log(hexValue); // '0xff'
72
73
const numberValue = web3.utils.hexToNumber('0xff');
74
console.log(numberValue); // 255
75
76
const bigIntValue = web3.utils.hexToBigInt('0x1fffffffffffff');
77
console.log(bigIntValue); // 9007199254740991n
78
```
79
80
### Address Validation and Formatting
81
82
Validate and format Ethereum addresses with checksum support.
83
84
```typescript { .api }
85
/**
86
* Check if string is valid Ethereum address
87
* @param address - Address string to validate
88
* @returns Boolean indicating validity
89
*/
90
isAddress(address: string): boolean;
91
92
/**
93
* Convert address to checksum format
94
* @param address - Address to convert
95
* @returns Checksummed address
96
*/
97
toChecksumAddress(address: string): string;
98
99
/**
100
* Check if address has valid checksum
101
* @param address - Address to check
102
* @returns Boolean indicating valid checksum
103
*/
104
checkAddressChecksum(address: string): boolean;
105
106
/**
107
* Check if addresses are equal (case-insensitive)
108
* @param address1 - First address
109
* @param address2 - Second address
110
* @returns Boolean indicating equality
111
*/
112
isAddressEqual(address1: string, address2: string): boolean;
113
```
114
115
**Usage Examples:**
116
117
```typescript
118
// Address validation
119
const address = '0x742c1382dfa68ea2a8b37ae3b72b476e1bb51aef';
120
console.log(web3.utils.isAddress(address)); // true
121
122
// Checksum conversion
123
const checksummed = web3.utils.toChecksumAddress(address);
124
console.log(checksummed); // '0x742C1382DfA68eA2a8b37ae3B72b476e1bB51AeF'
125
126
// Checksum validation
127
console.log(web3.utils.checkAddressChecksum(checksummed)); // true
128
129
// Address comparison
130
const addr1 = '0x742c1382dfa68ea2a8b37ae3b72b476e1bb51aef';
131
const addr2 = '0x742C1382DfA68eA2a8b37ae3B72b476e1bB51AeF';
132
console.log(web3.utils.isAddressEqual(addr1, addr2)); // true
133
```
134
135
### Hashing Functions
136
137
Cryptographic hashing functions for data integrity and Ethereum operations.
138
139
```typescript { .api }
140
/**
141
* Calculate Keccak-256 hash
142
* @param data - Data to hash
143
* @returns Hash as hex string
144
*/
145
keccak256(data: Bytes): string;
146
147
/**
148
* Calculate SHA-3 hash (alias for keccak256)
149
* @param data - Data to hash
150
* @returns Hash as hex string
151
*/
152
sha3(data: Bytes): string;
153
154
/**
155
* Calculate SHA-3 hash handling null input
156
* @param data - Data to hash
157
* @returns Hash as hex string or null
158
*/
159
sha3Raw(data: Bytes): string | null;
160
161
/**
162
* Calculate Solidity-compatible packed hash
163
* @param values - Values to pack and hash
164
* @returns Hash as hex string
165
*/
166
soliditySha3(...values: unknown[]): string | null;
167
168
/**
169
* Calculate Solidity-compatible packed hash (raw)
170
* @param values - Values to pack and hash
171
* @returns Hash as hex string
172
*/
173
soliditySha3Raw(...values: unknown[]): string;
174
```
175
176
**Usage Examples:**
177
178
```typescript
179
// Basic hashing
180
const hash = web3.utils.keccak256('Hello, Web3!');
181
console.log(hash); // '0x...'
182
183
const sha3Hash = web3.utils.sha3('Hello, Web3!');
184
console.log(sha3Hash); // Same as keccak256
185
186
// Solidity-style hashing
187
const packedHash = web3.utils.soliditySha3('uint256', 123, 'string', 'Hello');
188
console.log(packedHash);
189
190
// Packed hash with types
191
const typedHash = web3.utils.soliditySha3(
192
{ type: 'uint256', value: '123' },
193
{ type: 'string', value: 'Hello' }
194
);
195
```
196
197
### Random Number Generation
198
199
Generate cryptographically secure random values.
200
201
```typescript { .api }
202
/**
203
* Generate random hex string
204
* @param bytesSize - Number of bytes to generate
205
* @returns Random hex string
206
*/
207
randomHex(bytesSize: number): HexString;
208
209
/**
210
* Generate random bytes
211
* @param bytesSize - Number of bytes to generate
212
* @returns Random bytes as Uint8Array
213
*/
214
randomBytes(bytesSize: number): Uint8Array;
215
```
216
217
**Usage Examples:**
218
219
```typescript
220
// Generate random hex
221
const randomHex = web3.utils.randomHex(32);
222
console.log(randomHex); // '0x...' (64 hex characters + 0x)
223
224
// Generate random bytes
225
const randomBytes = web3.utils.randomBytes(32);
226
console.log(randomBytes); // Uint8Array(32) [...]
227
```
228
229
### String Manipulation
230
231
String utility functions for various data operations.
232
233
```typescript { .api }
234
/**
235
* Convert string to hex
236
* @param str - String to convert
237
* @returns Hex representation
238
*/
239
asciiToHex(str: string): HexString;
240
241
/**
242
* Convert hex to string
243
* @param hex - Hex string to convert
244
* @returns ASCII string
245
*/
246
hexToAscii(hex: HexString): string;
247
248
/**
249
* Convert string to hex (UTF-8)
250
* @param str - String to convert
251
* @returns Hex representation
252
*/
253
utf8ToHex(str: string): HexString;
254
255
/**
256
* Convert hex to string (UTF-8)
257
* @param hex - Hex string to convert
258
* @returns UTF-8 string
259
*/
260
hexToUtf8(hex: HexString): string;
261
262
/**
263
* Convert string to bytes
264
* @param str - String to convert
265
* @returns Bytes representation
266
*/
267
stringToBytes(str: string): Uint8Array;
268
269
/**
270
* Convert bytes to string
271
* @param bytes - Bytes to convert
272
* @returns String representation
273
*/
274
bytesToString(bytes: Uint8Array): string;
275
```
276
277
**Usage Examples:**
278
279
```typescript
280
// String to hex conversion
281
const hexFromAscii = web3.utils.asciiToHex('Hello');
282
console.log(hexFromAscii); // '0x48656c6c6f'
283
284
const asciiFromHex = web3.utils.hexToAscii('0x48656c6c6f');
285
console.log(asciiFromHex); // 'Hello'
286
287
// UTF-8 conversions
288
const utf8Hex = web3.utils.utf8ToHex('Hello, 世界!');
289
const utf8String = web3.utils.hexToUtf8(utf8Hex);
290
console.log(utf8String); // 'Hello, 世界!'
291
292
// Bytes conversions
293
const bytes = web3.utils.stringToBytes('Hello');
294
const string = web3.utils.bytesToString(bytes);
295
console.log(string); // 'Hello'
296
```
297
298
### Data Validation
299
300
Validation functions for various data types and formats.
301
302
```typescript { .api }
303
/**
304
* Check if value is hex string
305
* @param value - Value to check
306
* @returns Boolean indicating if hex
307
*/
308
isHex(value: unknown): boolean;
309
310
/**
311
* Check if value is hex string with specific byte length
312
* @param value - Value to check
313
* @param length - Expected byte length
314
* @returns Boolean indicating valid hex with length
315
*/
316
isHexStrict(value: unknown, length?: number): boolean;
317
318
/**
319
* Check if value is valid block number
320
* @param value - Value to check
321
* @returns Boolean indicating validity
322
*/
323
isBlockNumber(value: unknown): boolean;
324
325
/**
326
* Check if value represents bloom filter
327
* @param bloom - Value to check
328
* @returns Boolean indicating validity
329
*/
330
isBloom(bloom: unknown): boolean;
331
332
/**
333
* Check if value is valid topic
334
* @param topic - Value to check
335
* @returns Boolean indicating validity
336
*/
337
isTopic(topic: unknown): boolean;
338
```
339
340
**Usage Examples:**
341
342
```typescript
343
// Hex validation
344
console.log(web3.utils.isHex('0x123')); // true
345
console.log(web3.utils.isHex('123')); // false
346
347
console.log(web3.utils.isHexStrict('0x123abc', 3)); // true (3 bytes)
348
console.log(web3.utils.isHexStrict('0x123', 3)); // false (not 3 bytes)
349
350
// Block number validation
351
console.log(web3.utils.isBlockNumber(123)); // true
352
console.log(web3.utils.isBlockNumber('0x7b')); // true
353
console.log(web3.utils.isBlockNumber('latest')); // true
354
```
355
356
### Data Formatting
357
358
Functions for formatting and padding data.
359
360
```typescript { .api }
361
/**
362
* Pad string to specified length with character
363
* @param str - String to pad
364
* @param characterAmount - Target length
365
* @param sign - Character to pad with
366
* @returns Padded string
367
*/
368
padLeft(str: string, characterAmount: number, sign?: string): string;
369
370
/**
371
* Pad string to right with specified character
372
* @param str - String to pad
373
* @param characterAmount - Target length
374
* @param sign - Character to pad with
375
* @returns Padded string
376
*/
377
padRight(str: string, characterAmount: number, sign?: string): string;
378
379
/**
380
* Left pad hex string to specified bytes
381
* @param hex - Hex string to pad
382
* @param bytes - Target byte length
383
* @returns Padded hex string
384
*/
385
leftPad(hex: string, bytes: number): string;
386
387
/**
388
* Right pad hex string to specified bytes
389
* @param hex - Hex string to pad
390
* @param bytes - Target byte length
391
* @returns Padded hex string
392
*/
393
rightPad(hex: string, bytes: number): string;
394
```
395
396
## Types
397
398
```typescript { .api }
399
type EtherUnits =
400
| 'noether'
401
| 'wei'
402
| 'kwei'
403
| 'Kwei'
404
| 'babbage'
405
| 'femtoether'
406
| 'mwei'
407
| 'Mwei'
408
| 'lovelace'
409
| 'picoether'
410
| 'gwei'
411
| 'Gwei'
412
| 'shannon'
413
| 'nanoether'
414
| 'nano'
415
| 'szabo'
416
| 'microether'
417
| 'micro'
418
| 'finney'
419
| 'milliether'
420
| 'milli'
421
| 'ether'
422
| 'kether'
423
| 'grand'
424
| 'mether'
425
| 'gether'
426
| 'tether';
427
428
type NumberLike = number | bigint | string;
429
type Numbers = number | bigint | string | HexString;
430
type Bytes = string | Uint8Array;
431
type HexString = string;
432
type Address = string;
433
```