0
# Utilities
1
2
Core utility functions for data conversion, encoding, validation, and Ethereum-specific operations including Wei conversions, address validation, hash functions, and data formatting.
3
4
## Capabilities
5
6
### Wei Conversion
7
8
Functions for converting between different Ethereum units.
9
10
```python { .api }
11
def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei:
12
"""
13
Convert number to Wei (smallest Ethereum unit).
14
15
Parameters:
16
- number: Number to convert
17
- unit: Source unit ('ether', 'gwei', 'finney', etc.)
18
19
Returns:
20
Amount in Wei
21
22
Examples:
23
to_wei(1, 'ether') -> 1000000000000000000
24
to_wei(20, 'gwei') -> 20000000000
25
"""
26
27
def from_wei(number: Wei, unit: str) -> decimal.Decimal:
28
"""
29
Convert Wei to specified unit.
30
31
Parameters:
32
- number: Amount in Wei
33
- unit: Target unit ('ether', 'gwei', 'finney', etc.)
34
35
Returns:
36
Amount in specified unit as Decimal for precision
37
38
Examples:
39
from_wei(1000000000000000000, 'ether') -> Decimal('1')
40
from_wei(20000000000, 'gwei') -> Decimal('20')
41
"""
42
```
43
44
### Address Utilities
45
46
Functions for address validation and formatting.
47
48
```python { .api }
49
def to_checksum_address(value: AnyAddress) -> ChecksumAddress:
50
"""
51
Convert address to EIP-55 checksum format.
52
53
Parameters:
54
- value: Address in any format
55
56
Returns:
57
Checksummed address
58
59
Examples:
60
to_checksum_address('0xd8da6bf26964af9d7eed9e03e53415d37aa96045')
61
-> '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
62
"""
63
64
def is_address(value: Any) -> bool:
65
"""
66
Check if value is valid Ethereum address.
67
68
Parameters:
69
- value: Value to check
70
71
Returns:
72
True if valid address format
73
"""
74
75
def is_checksum_address(value: Any) -> bool:
76
"""
77
Check if address is in valid checksum format.
78
79
Parameters:
80
- value: Address to check
81
82
Returns:
83
True if valid checksum address
84
"""
85
86
def is_same_address(address1: AnyAddress, address2: AnyAddress) -> bool:
87
"""
88
Compare two addresses for equality (case-insensitive).
89
90
Parameters:
91
- address1: First address
92
- address2: Second address
93
94
Returns:
95
True if addresses are the same
96
"""
97
```
98
99
### Hash Functions
100
101
Cryptographic hash functions for Ethereum operations.
102
103
```python { .api }
104
def keccak(
105
primitive: Optional[Primitives] = None,
106
text: Optional[str] = None,
107
hexstr: Optional[HexStr] = None
108
) -> HexBytes:
109
"""
110
Compute Keccak-256 hash.
111
112
Parameters:
113
- primitive: Raw bytes to hash
114
- text: Text string to hash (UTF-8 encoded)
115
- hexstr: Hex string to hash
116
117
Returns:
118
32-byte hash as HexBytes
119
120
Examples:
121
keccak(text='hello') -> HexBytes('0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8')
122
"""
123
124
def solidityKeccak(abi_types: List[str], values: List[Any]) -> HexBytes:
125
"""
126
Compute Solidity-compatible packed hash.
127
128
Parameters:
129
- abi_types: List of Solidity types
130
- values: List of values matching types
131
132
Returns:
133
Packed hash as HexBytes
134
135
Examples:
136
solidityKeccak(['uint256', 'string'], [123, 'hello'])
137
"""
138
139
def sha3(
140
primitive: Optional[Primitives] = None,
141
text: Optional[str] = None,
142
hexstr: Optional[HexStr] = None
143
) -> HexBytes:
144
"""
145
Alias for keccak function (deprecated, use keccak).
146
"""
147
```
148
149
### Data Encoding and Conversion
150
151
Functions for encoding and converting data types.
152
153
```python { .api }
154
def to_bytes(
155
primitive: Union[bool, int, str, bytes] = None,
156
hexstr: Optional[HexStr] = None,
157
text: Optional[str] = None
158
) -> bytes:
159
"""
160
Convert various types to bytes.
161
162
Parameters:
163
- primitive: Value to convert
164
- hexstr: Hex string to convert
165
- text: Text string to convert (UTF-8)
166
167
Returns:
168
Converted bytes
169
"""
170
171
def to_int(
172
primitive: Union[bytes, int, str] = None,
173
hexstr: Optional[HexStr] = None,
174
text: Optional[str] = None
175
) -> int:
176
"""
177
Convert various types to integer.
178
179
Parameters:
180
- primitive: Value to convert
181
- hexstr: Hex string to convert
182
- text: Text string to convert
183
184
Returns:
185
Converted integer
186
"""
187
188
def to_hex(
189
primitive: Union[bytes, int, str, bool] = None,
190
hexstr: Optional[HexStr] = None,
191
text: Optional[str] = None
192
) -> HexStr:
193
"""
194
Convert various types to hex string.
195
196
Parameters:
197
- primitive: Value to convert
198
- hexstr: Pass-through hex string
199
- text: Text string to convert (UTF-8)
200
201
Returns:
202
Hex string with 0x prefix
203
"""
204
205
def to_text(
206
primitive: Union[bytes, int, str] = None,
207
hexstr: Optional[HexStr] = None,
208
text: Optional[str] = None,
209
encoding: str = 'utf-8'
210
) -> str:
211
"""
212
Convert various types to text string.
213
214
Parameters:
215
- primitive: Value to convert
216
- hexstr: Hex string to convert
217
- text: Pass-through text string
218
- encoding: Text encoding (default UTF-8)
219
220
Returns:
221
Decoded text string
222
"""
223
```
224
225
### JSON and Formatting
226
227
Functions for JSON encoding and data formatting.
228
229
```python { .api }
230
def to_json(obj: Any) -> str:
231
"""
232
Convert object to JSON string with Ethereum-specific formatting.
233
234
Parameters:
235
- obj: Object to serialize
236
237
Returns:
238
JSON string
239
"""
240
241
def attributedict_to_dict(obj: Any) -> Any:
242
"""
243
Convert AttributeDict objects to regular dictionaries recursively.
244
245
Parameters:
246
- obj: Object to convert
247
248
Returns:
249
Converted object with regular dicts
250
"""
251
252
def remove_0x_prefix(value: str) -> str:
253
"""
254
Remove 0x prefix from hex string.
255
256
Parameters:
257
- value: Hex string potentially with 0x prefix
258
259
Returns:
260
Hex string without 0x prefix
261
"""
262
263
def add_0x_prefix(value: str) -> HexStr:
264
"""
265
Add 0x prefix to hex string if not present.
266
267
Parameters:
268
- value: Hex string
269
270
Returns:
271
Hex string with 0x prefix
272
"""
273
```
274
275
### ABI Utilities
276
277
Functions for working with ABI encoding and decoding.
278
279
```python { .api }
280
def encode_abi(types: List[str], args: List[Any]) -> HexBytes:
281
"""
282
Encode data according to ABI specification.
283
284
Parameters:
285
- types: List of ABI types
286
- args: List of values matching types
287
288
Returns:
289
ABI-encoded data
290
"""
291
292
def decode_abi(types: List[str], data: HexBytes) -> List[Any]:
293
"""
294
Decode ABI-encoded data.
295
296
Parameters:
297
- types: List of expected ABI types
298
- data: ABI-encoded data
299
300
Returns:
301
List of decoded values
302
"""
303
304
def function_abi_to_4byte_selector(function_abi: Dict[str, Any]) -> HexBytes:
305
"""
306
Generate 4-byte function selector from ABI.
307
308
Parameters:
309
- function_abi: Function ABI definition
310
311
Returns:
312
4-byte function selector
313
"""
314
315
def event_abi_to_log_topic(event_abi: Dict[str, Any]) -> HexBytes:
316
"""
317
Generate log topic from event ABI.
318
319
Parameters:
320
- event_abi: Event ABI definition
321
322
Returns:
323
Event topic hash
324
"""
325
```
326
327
### Contract Utilities
328
329
Functions for contract-related operations.
330
331
```python { .api }
332
def get_create_address(address: AnyAddress, nonce: int) -> ChecksumAddress:
333
"""
334
Calculate contract address from deployer address and nonce.
335
336
Parameters:
337
- address: Deployer address
338
- nonce: Transaction nonce
339
340
Returns:
341
Contract address
342
"""
343
344
def get_create2_address(
345
address: AnyAddress,
346
salt: Union[bytes, int, str],
347
init_code: bytes
348
) -> ChecksumAddress:
349
"""
350
Calculate CREATE2 contract address.
351
352
Parameters:
353
- address: Factory contract address
354
- salt: Salt value for deterministic address
355
- init_code: Contract initialization code
356
357
Returns:
358
Deterministic contract address
359
"""
360
```
361
362
### Validation Utilities
363
364
Functions for validating Ethereum data formats.
365
366
```python { .api }
367
def is_hex(value: Any) -> bool:
368
"""
369
Check if value is valid hex string.
370
371
Parameters:
372
- value: Value to check
373
374
Returns:
375
True if valid hex format
376
"""
377
378
def is_0x_prefixed(value: str) -> bool:
379
"""
380
Check if string has 0x prefix.
381
382
Parameters:
383
- value: String to check
384
385
Returns:
386
True if has 0x prefix
387
"""
388
389
def is_bytes(value: Any) -> bool:
390
"""
391
Check if value is bytes type.
392
393
Parameters:
394
- value: Value to check
395
396
Returns:
397
True if bytes type
398
"""
399
400
def is_string(value: Any) -> bool:
401
"""
402
Check if value is string type.
403
404
Parameters:
405
- value: Value to check
406
407
Returns:
408
True if string type
409
"""
410
```
411
412
## Types
413
414
Utility-related type definitions.
415
416
```python { .api }
417
Wei = NewType('Wei', int)
418
HexStr = NewType('HexStr', str)
419
HexBytes = NewType('HexBytes', bytes)
420
Primitives = Union[bytes, int, bool]
421
AnyAddress = Union[str, bytes, ChecksumAddress]
422
423
# Unit conversion mappings
424
UNITS = {
425
'wei': 1,
426
'kwei': 10**3,
427
'mwei': 10**6,
428
'gwei': 10**9,
429
'szabo': 10**12,
430
'finney': 10**15,
431
'ether': 10**18,
432
}
433
```
434
435
## Usage Examples
436
437
### Wei Conversions
438
439
```python
440
from web3 import Web3
441
442
w3 = Web3()
443
444
# Convert to Wei
445
eth_amount = 1.5
446
wei_amount = w3.to_wei(eth_amount, 'ether')
447
print(f"{eth_amount} ETH = {wei_amount} Wei")
448
449
gwei_amount = 20
450
wei_from_gwei = w3.to_wei(gwei_amount, 'gwei')
451
print(f"{gwei_amount} Gwei = {wei_from_gwei} Wei")
452
453
# Convert from Wei
454
large_wei = 1500000000000000000
455
eth_converted = w3.from_wei(large_wei, 'ether')
456
gwei_converted = w3.from_wei(large_wei, 'gwei')
457
458
print(f"{large_wei} Wei = {eth_converted} ETH")
459
print(f"{large_wei} Wei = {gwei_converted} Gwei")
460
```
461
462
### Address Operations
463
464
```python
465
from web3 import Web3
466
467
w3 = Web3()
468
469
# Convert to checksum address
470
address = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'
471
checksum_addr = w3.to_checksum_address(address)
472
print(f"Checksum address: {checksum_addr}")
473
474
# Validate addresses
475
print(f"Is valid address: {w3.is_address(address)}")
476
print(f"Is checksum address: {w3.is_checksum_address(checksum_addr)}")
477
478
# Compare addresses
479
addr1 = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'
480
addr2 = '0xD8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
481
print(f"Addresses are same: {w3.is_same_address(addr1, addr2)}")
482
```
483
484
### Hash Functions
485
486
```python
487
from web3 import Web3
488
489
w3 = Web3()
490
491
# Keccak hash of string
492
message = "Hello, Ethereum!"
493
hash_result = w3.keccak(text=message)
494
print(f"Keccak hash: {hash_result.hex()}")
495
496
# Hash of bytes
497
data = b"binary data"
498
hash_bytes = w3.keccak(primitive=data)
499
print(f"Hash of bytes: {hash_bytes.hex()}")
500
501
# Solidity-style packed hash
502
types = ['uint256', 'string', 'address']
503
values = [12345, 'test', '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045']
504
packed_hash = w3.solidityKeccak(types, values)
505
print(f"Packed hash: {packed_hash.hex()}")
506
```
507
508
### Data Conversions
509
510
```python
511
from web3 import Web3
512
513
w3 = Web3()
514
515
# Convert text to bytes
516
text = "Hello World"
517
text_bytes = w3.to_bytes(text=text)
518
print(f"Text as bytes: {text_bytes}")
519
520
# Convert hex to integer
521
hex_value = "0xff"
522
int_value = w3.to_int(hexstr=hex_value)
523
print(f"Hex {hex_value} as int: {int_value}")
524
525
# Convert integer to hex
526
number = 255
527
hex_result = w3.to_hex(primitive=number)
528
print(f"Int {number} as hex: {hex_result}")
529
530
# Convert bytes back to text
531
message_bytes = b'Hello World'
532
decoded_text = w3.to_text(primitive=message_bytes)
533
print(f"Bytes as text: {decoded_text}")
534
```
535
536
### ABI Encoding
537
538
```python
539
from web3 import Web3
540
541
w3 = Web3()
542
543
# Encode data for contract call
544
types = ['uint256', 'string', 'bool']
545
values = [42, 'hello', True]
546
encoded = w3.encode_abi(types, values)
547
print(f"Encoded data: {encoded.hex()}")
548
549
# Decode ABI data
550
decoded = w3.decode_abi(types, encoded)
551
print(f"Decoded values: {decoded}")
552
553
# Function selector
554
function_abi = {
555
'name': 'transfer',
556
'type': 'function',
557
'inputs': [
558
{'name': 'to', 'type': 'address'},
559
{'name': 'value', 'type': 'uint256'}
560
]
561
}
562
selector = w3.function_abi_to_4byte_selector(function_abi)
563
print(f"Transfer function selector: {selector.hex()}")
564
```
565
566
### Contract Address Calculation
567
568
```python
569
from web3 import Web3
570
571
w3 = Web3()
572
573
# Calculate contract address from deployer
574
deployer = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
575
nonce = 42
576
contract_addr = w3.get_create_address(deployer, nonce)
577
print(f"Contract address: {contract_addr}")
578
579
# Calculate CREATE2 address
580
factory = '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8'
581
salt = w3.keccak(text="my-salt")
582
init_code = b'\x60\x80\x60\x40...' # Contract bytecode
583
create2_addr = w3.get_create2_address(factory, salt, init_code)
584
print(f"CREATE2 address: {create2_addr}")
585
```
586
587
### Validation Functions
588
589
```python
590
from web3 import Web3
591
592
w3 = Web3()
593
594
# Validate data formats
595
values_to_check = [
596
"0x1234", # hex string
597
"1234", # non-hex string
598
b"binary", # bytes
599
123, # integer
600
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" # address
601
]
602
603
for value in values_to_check:
604
print(f"Value: {value}")
605
print(f" Is hex: {w3.is_hex(value)}")
606
print(f" Is bytes: {w3.is_bytes(value)}")
607
print(f" Is string: {w3.is_string(value)}")
608
print(f" Is address: {w3.is_address(value)}")
609
610
if isinstance(value, str):
611
print(f" Has 0x prefix: {w3.is_0x_prefixed(value)}")
612
print()
613
```
614
615
### JSON Formatting
616
617
```python
618
from web3 import Web3
619
import json
620
621
w3 = Web3()
622
623
# Create complex data structure
624
data = {
625
'address': w3.to_checksum_address('0xd8da6bf26964af9d7eed9e03e53415d37aa96045'),
626
'balance': w3.to_wei(1.5, 'ether'),
627
'hash': w3.keccak(text='test'),
628
'number': 12345
629
}
630
631
# Convert to JSON with proper formatting
632
json_str = w3.to_json(data)
633
print("Formatted JSON:")
634
print(json.dumps(json.loads(json_str), indent=2))
635
```
636
637
### Batch Utility Operations
638
639
```python
640
from web3 import Web3
641
642
w3 = Web3()
643
644
# Process multiple addresses
645
addresses = [
646
'0xd8da6bf26964af9d7eed9e03e53415d37aa96045',
647
'0x742d35cc6635c0532925a3b8d5c0d9e3c4b3c8',
648
'invalid-address'
649
]
650
651
checksum_addresses = []
652
for addr in addresses:
653
if w3.is_address(addr):
654
checksum_addr = w3.to_checksum_address(addr)
655
checksum_addresses.append(checksum_addr)
656
print(f"✓ {addr} -> {checksum_addr}")
657
else:
658
print(f"✗ Invalid address: {addr}")
659
660
print(f"Processed {len(checksum_addresses)} valid addresses")
661
```