Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/web3.main.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions newsfragments/3768.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add static methods for converting to and from wei with decimals
14 changes: 14 additions & 0 deletions tests/core/web3-module/test_conversions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import pytest

from eth_utils import (
from_wei_decimals,
to_wei_decimals,
)
from hexbytes import (
HexBytes,
)
Expand Down Expand Up @@ -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
14 changes: 14 additions & 0 deletions web3/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -23,6 +24,7 @@
to_int,
to_text,
to_wei,
to_wei_decimals,
)
from functools import (
wraps,
Expand Down Expand Up @@ -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)
Expand Down