-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathunit_converter.py
More file actions
63 lines (45 loc) · 2.14 KB
/
unit_converter.py
File metadata and controls
63 lines (45 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# import numpy as np
from decimal import Decimal, getcontext
from typing import Union
# 78 digits to cover uint256 max value (2^256 - 1)
getcontext().prec = 78
class UnitConverter:
WEI_MULTIPLIER = '1'
GWEI_MULTIPLIER = '1000000000' # 1e9
ARK_MULTIPLIER = '1000000000000000000' # 1e18
@staticmethod
def parse_units(value: Union[float, int, str, Decimal], unit='ark') -> Decimal:
value = Decimal(str(value))
unit = unit.lower()
if unit == 'wei':
return (value * Decimal(UnitConverter.WEI_MULTIPLIER)).normalize()
if unit == 'gwei':
return (value * Decimal(UnitConverter.GWEI_MULTIPLIER)).normalize()
if unit == 'ark':
return (value * Decimal(UnitConverter.ARK_MULTIPLIER)).normalize()
raise ValueError(f"Unsupported unit: {unit}. Supported units are 'wei', 'gwei', and 'ark'.")
@staticmethod
def format_units(value: Union[float, int, str, Decimal], unit='ark') -> Decimal:
value = Decimal(str(value))
unit = unit.lower()
if unit == 'wei':
return value / Decimal(UnitConverter.WEI_MULTIPLIER)
if unit == 'gwei':
return value / Decimal(UnitConverter.GWEI_MULTIPLIER)
if unit == 'ark':
return value / Decimal(UnitConverter.ARK_MULTIPLIER)
raise ValueError(f"Unsupported unit: {unit}. Supported units are 'wei', 'gwei', and 'ark'.")
@staticmethod
def wei_to_ark(value: Union[float, int, str, Decimal], suffix=None):
converted_value = UnitConverter.format_units(UnitConverter.parse_units(value, 'wei'), 'ark')
converted_value = format(converted_value.normalize(), 'f')
if suffix is not None:
return f"{converted_value} {suffix}"
return str(converted_value)
@staticmethod
def gwei_to_ark(value: Union[float, int, str, Decimal], suffix=None):
converted_value = UnitConverter.format_units(UnitConverter.parse_units(value, 'gwei'), 'ark')
converted_value = format(converted_value.normalize(), 'f')
if suffix is not None:
return f"{converted_value} {suffix}"
return str(converted_value)