diff --git a/eth_utils/currency.py b/eth_utils/currency.py index b3b6a7af..f0590167 100644 --- a/eth_utils/currency.py +++ b/eth_utils/currency.py @@ -36,11 +36,11 @@ class denoms: MAX_WEI = 2**256 - 1 -def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: +def from_wei(number: int, unit: Union[str, int]) -> Union[int, decimal.Decimal]: """ Takes a number of wei and converts it to any other ether unit. """ - if unit.lower() not in units: + if is_string(number) and unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) @@ -51,7 +51,10 @@ def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: if number < MIN_WEI or number > MAX_WEI: raise ValueError("value must be between 1 and 2**256 - 1") - unit_value = units[unit.lower()] + if is_integer(unit): + unit_value = decimal.Decimal(10) ** decimal.Decimal(unit) + else: + unit_value = units[unit.lower()] with localcontext() as ctx: ctx.prec = 999 @@ -61,11 +64,11 @@ def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: return result_value -def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> int: +def to_wei(number: Union[int, float, str, decimal.Decimal], unit: Union[str, int]) -> int: """ Takes a number of a unit and converts it to wei. """ - if unit.lower() not in units: + if is_string(number) and unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) @@ -80,7 +83,11 @@ def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> int: raise TypeError("Unsupported type. Must be one of integer, float, or string") s_number = str(number) - unit_value = units[unit.lower()] + + if is_integer(unit): + unit_value = decimal.Decimal(10) ** decimal.Decimal(unit) + else: + unit_value = units[unit.lower()] if d_number == decimal.Decimal(0): return 0 diff --git a/tests/currency-utils/test_currency_tools.py b/tests/currency-utils/test_currency_tools.py index 537bbb83..21c62584 100644 --- a/tests/currency-utils/test_currency_tools.py +++ b/tests/currency-utils/test_currency_tools.py @@ -116,6 +116,19 @@ def test_float_ether(value): assert from_wei(to_wei(value, "ether"), "ether") == decimal.Decimal(str(value)) +@pytest.mark.parametrize( + "value", + [ + 1, # 1000000 wei + 0.1, # 100000 wei + 0.01, # 10000 wei + 0.001, # 1000 wei + ], +) +def test_float_usdt(value): + assert from_wei(to_wei(value, 6), 6) == decimal.Decimal(str(value)) + + @pytest.mark.parametrize( "value", [