diff --git a/docs/web3.main.rst b/docs/web3.main.rst index d7e09e1b3c..e5c76c0ae8 100644 --- a/docs/web3.main.rst +++ b/docs/web3.main.rst @@ -324,6 +324,30 @@ Currency Conversions Decimal('1') +.. py:method:: Web3.to_wei_decimals(value, decimals) + + Returns the value in the denomination specified by the ``decimals`` argument + converted to wei. + + + .. code-block:: python + + >>> Web3.to_wei_decimals(1, 18) + 1000000000000000000 + + +.. py:method:: Web3.from_wei_decimals(value, decimals) + + Returns the value in wei converted to the given number of decimals. The value is returned + as a ``Decimal`` to ensure precision down to the wei. + + + .. code-block:: python + + >>> Web3.from_wei_decimals(1000000000000000000, 18) + Decimal('1') + + .. _overview_addresses: Addresses diff --git a/newsfragments/3768.feature.rst b/newsfragments/3768.feature.rst new file mode 100644 index 0000000000..dcb990e770 --- /dev/null +++ b/newsfragments/3768.feature.rst @@ -0,0 +1 @@ +Add static methods for converting to and from wei with decimals diff --git a/tests/core/web3-module/test_conversions.py b/tests/core/web3-module/test_conversions.py index 1fe13630fe..23eee4ecd7 100644 --- a/tests/core/web3-module/test_conversions.py +++ b/tests/core/web3-module/test_conversions.py @@ -1,5 +1,9 @@ import pytest +from eth_utils import ( + from_wei_decimals, + to_wei_decimals, +) from hexbytes import ( HexBytes, ) @@ -253,3 +257,13 @@ def test_to_json(val, expected): ) def test_to_json_with_transaction(tx, expected): assert Web3.to_json(tx) == expected + + +def test_to_wei_decimals_wiring(): + assert Web3.to_wei_decimals("1.5", 6) == to_wei_decimals("1.5", 6) + assert Web3.to_wei_decimals(2, 6) == 2000000 + + +def test_from_wei_decimals_wiring(): + assert Web3.from_wei_decimals(1500000, 6) == from_wei_decimals(1500000, 6) + assert Web3.from_wei_decimals(2000000, 6) == 2 diff --git a/web3/main.py b/web3/main.py index 1a124bb064..5d0d44b3c0 100644 --- a/web3/main.py +++ b/web3/main.py @@ -14,6 +14,7 @@ add_0x_prefix, apply_to_return_value, from_wei, + from_wei_decimals, is_address, is_checksum_address, keccak as eth_utils_keccak, @@ -23,6 +24,7 @@ to_int, to_text, to_wei, + to_wei_decimals, ) from functools import ( wraps, @@ -259,6 +261,18 @@ def to_wei(number: int | float | str | decimal.Decimal, unit: str) -> Wei: def from_wei(number: int, unit: str) -> int | decimal.Decimal: return from_wei(number, unit) + @staticmethod + @wraps(to_wei_decimals) + def to_wei_decimals( + number: Union[int, float, str, decimal.Decimal], decimals: int + ) -> Wei: + return cast(Wei, to_wei_decimals(number, decimals)) + + @staticmethod + @wraps(from_wei_decimals) + def from_wei_decimals(number: int, decimals: int) -> Union[int, decimal.Decimal]: + return from_wei_decimals(number, decimals) + # Address Utility @staticmethod @wraps(is_address)