0
# Currency and Units
1
2
Ethereum currency conversions between wei and various denominations with precise decimal handling and comprehensive denomination constants. Essential for handling Ether amounts in applications.
3
4
## Capabilities
5
6
### Wei Conversion Functions
7
8
Convert between wei (smallest unit) and named denominations.
9
10
```python { .api }
11
def to_wei(number, unit: str) -> int:
12
"""
13
Convert from specified unit to wei.
14
15
Args:
16
number: Amount in the specified unit (int, float, Decimal, or string)
17
unit (str): Unit name ('ether', 'gwei', 'finney', etc.)
18
19
Returns:
20
int: Amount in wei
21
22
Raises:
23
ValidationError: If unit is unknown or number is invalid
24
"""
25
26
def from_wei(number: int, unit: str) -> Union[int, Decimal]:
27
"""
28
Convert wei to specified unit.
29
30
Args:
31
number (int): Amount in wei
32
unit (str): Target unit name ('ether', 'gwei', 'finney', etc.)
33
34
Returns:
35
Union[int, Decimal]: Amount in specified unit (int if whole number, Decimal otherwise)
36
37
Raises:
38
ValidationError: If unit is unknown or number is invalid
39
"""
40
```
41
42
### Decimal-Based Conversions
43
44
Convert using custom decimal places for precision control.
45
46
```python { .api }
47
def to_wei_decimals(number, decimals: int) -> int:
48
"""
49
Convert to wei using specified decimal places.
50
51
Args:
52
number: Amount to convert
53
decimals (int): Number of decimal places (e.g., 18 for ether, 9 for gwei)
54
55
Returns:
56
int: Amount in wei
57
"""
58
59
def from_wei_decimals(number: int, decimals: int) -> Union[int, Decimal]:
60
"""
61
Convert wei using specified decimal places.
62
63
Args:
64
number (int): Amount in wei
65
decimals (int): Number of decimal places for target unit
66
67
Returns:
68
Union[int, Decimal]: Converted amount
69
"""
70
```
71
72
### Denomination Constants
73
74
Access denomination values and limits.
75
76
```python { .api }
77
class denoms:
78
"""Ethereum denomination constants."""
79
# Smallest units
80
wei = 1
81
kwei = 1000
82
babbage = 1000
83
femtoether = 1000
84
85
# Common units
86
mwei = 1000000
87
lovelace = 1000000
88
picoether = 1000000
89
90
gwei = 1000000000
91
shannon = 1000000000
92
nanoether = 1000000000
93
nano = 1000000000
94
95
# Larger units
96
szabo = 1000000000000
97
microether = 1000000000000
98
micro = 1000000000000
99
100
finney = 1000000000000000
101
milliether = 1000000000000000
102
milli = 1000000000000000
103
104
# Standard unit
105
ether = 1000000000000000000
106
107
# Large units
108
kether = 1000000000000000000000
109
grand = 1000000000000000000000
110
mether = 1000000000000000000000000
111
gether = 1000000000000000000000000000
112
tether = 1000000000000000000000000000000
113
114
# Wei limits
115
MIN_WEI = 0
116
MAX_WEI = 2**256 - 1
117
```
118
119
## Usage Examples
120
121
### Basic Currency Conversions
122
123
```python
124
from eth_utils import to_wei, from_wei, denoms
125
126
# Convert ether to wei
127
eth_amount = 1.5
128
wei_amount = to_wei(eth_amount, 'ether')
129
print(wei_amount) # 1500000000000000000
130
131
# Convert wei back to ether
132
ether_amount = from_wei(wei_amount, 'ether')
133
print(ether_amount) # 1.5
134
135
# Working with gwei (common for gas prices)
136
gas_price_gwei = 20
137
gas_price_wei = to_wei(gas_price_gwei, 'gwei')
138
print(gas_price_wei) # 20000000000
139
140
# Convert large wei amount to readable ether
141
large_wei = 1234567890123456789012
142
readable_ether = from_wei(large_wei, 'ether')
143
print(readable_ether) # 1234.567890123456789012
144
```
145
146
### Working with Gas Calculations
147
148
```python
149
from eth_utils import to_wei, from_wei
150
151
# Gas calculation example
152
gas_limit = 21000
153
gas_price_gwei = 30
154
155
# Calculate total gas cost in wei
156
gas_price_wei = to_wei(gas_price_gwei, 'gwei')
157
total_gas_wei = gas_limit * gas_price_wei
158
print(f"Gas cost in wei: {total_gas_wei}") # 630000000000000
159
160
# Convert to readable ether amount
161
gas_cost_ether = from_wei(total_gas_wei, 'ether')
162
print(f"Gas cost in ether: {gas_cost_ether}") # 0.00063
163
```
164
165
### Using Denomination Constants
166
167
```python
168
from eth_utils import denoms, from_wei
169
170
# Access denomination values directly
171
print(f"1 ether = {denoms.ether} wei")
172
print(f"1 gwei = {denoms.gwei} wei")
173
print(f"1 finney = {denoms.finney} wei")
174
175
# Calculate amounts using constants
176
amount_wei = 5 * denoms.ether + 250 * denoms.gwei
177
print(f"Total: {amount_wei} wei")
178
179
# Convert to readable format
180
readable = from_wei(amount_wei, 'ether')
181
print(f"Readable: {readable} ETH")
182
```
183
184
### Precision Handling with Decimals
185
186
```python
187
from eth_utils import to_wei_decimals, from_wei_decimals
188
from decimal import Decimal
189
190
# Work with custom token (18 decimals like ether)
191
token_amount = Decimal('123.456789012345678901')
192
token_wei = to_wei_decimals(token_amount, 18)
193
print(token_wei) # 123456789012345678901
194
195
# Convert back maintaining precision
196
original_amount = from_wei_decimals(token_wei, 18)
197
print(original_amount) # 123.456789012345678901
198
199
# Work with USDC (6 decimals)
200
usdc_amount = 1000.50
201
usdc_base_units = to_wei_decimals(usdc_amount, 6)
202
print(usdc_base_units) # 1000500000
203
204
usdc_readable = from_wei_decimals(usdc_base_units, 6)
205
print(usdc_readable) # 1000.5
206
```
207
208
### Unit Validation and Conversion
209
210
```python
211
from eth_utils import to_wei, from_wei, ValidationError
212
213
def safe_convert_to_wei(amount, unit):
214
"""Safely convert amount to wei with error handling."""
215
try:
216
return to_wei(amount, unit)
217
except ValidationError as e:
218
print(f"Invalid conversion: {e}")
219
return None
220
221
def format_ether_amount(wei_amount):
222
"""Format wei amount as readable ether."""
223
if wei_amount == 0:
224
return "0 ETH"
225
226
ether_amount = from_wei(wei_amount, 'ether')
227
return f"{ether_amount} ETH"
228
229
# Usage examples
230
wei1 = safe_convert_to_wei(1.5, 'ether') # Valid
231
wei2 = safe_convert_to_wei(1.5, 'invalid_unit') # None (invalid unit)
232
233
if wei1:
234
print(format_ether_amount(wei1)) # 1.5 ETH
235
```
236
237
### Batch Processing
238
239
```python
240
from eth_utils import to_wei, from_wei
241
242
def process_transaction_amounts(transactions):
243
"""Process list of transaction amounts."""
244
processed = []
245
246
for tx in transactions:
247
# Convert input amounts to wei for processing
248
if tx['unit'] != 'wei':
249
tx['amount_wei'] = to_wei(tx['amount'], tx['unit'])
250
else:
251
tx['amount_wei'] = tx['amount']
252
253
# Add readable ether amount
254
tx['amount_eth'] = from_wei(tx['amount_wei'], 'ether')
255
processed.append(tx)
256
257
return processed
258
259
# Example usage
260
transactions = [
261
{'amount': 1.5, 'unit': 'ether'},
262
{'amount': 500, 'unit': 'gwei'},
263
{'amount': 1000000000000000000, 'unit': 'wei'}
264
]
265
266
processed_txs = process_transaction_amounts(transactions)
267
for tx in processed_txs:
268
print(f"{tx['amount_eth']} ETH ({tx['amount_wei']} wei)")
269
```
270
271
## Supported Units
272
273
The following unit names are supported for conversions:
274
275
### Common Units
276
- `wei` - Base unit (1 wei)
277
- `gwei` - Gigawei (10^9 wei) - commonly used for gas prices
278
- `ether` - Standard unit (10^18 wei)
279
280
### All Named Units
281
- `wei`, `kwei`, `babbage`, `femtoether`
282
- `mwei`, `lovelace`, `picoether`
283
- `gwei`, `shannon`, `nanoether`, `nano`
284
- `szabo`, `microether`, `micro`
285
- `finney`, `milliether`, `milli`
286
- `ether`
287
- `kether`, `grand`
288
- `mether`, `gether`, `tether`
289
290
## Precision Considerations
291
292
- All conversions maintain full precision using Python's `Decimal` type
293
- Wei amounts are always returned as `int` (no fractional wei)
294
- Conversions from wei return `int` when result is whole number, `Decimal` otherwise
295
- Use `Decimal` inputs for maximum precision in calculations