Skip to content

Commit 13be020

Browse files
committed
Add displayable amount
1 parent 84e6a80 commit 13be020

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

src/aleph/sdk/evm_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def to_wei_token(amount: Decimal) -> Decimal:
3939

4040
def ether_rounding(amount: Decimal) -> Decimal:
4141
"""Rounds the given value to 18 decimals."""
42-
return amount.quantize(Decimal(1) / 10**18, rounding=ROUND_CEILING)
42+
return amount.quantize(Decimal(1) / Decimal(10**18), rounding=ROUND_CEILING)
4343

4444

4545
def get_chain_id(chain: Union[Chain, str, None]) -> Optional[int]:

src/aleph/sdk/exceptions.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from abc import ABC
22

3+
from aleph.sdk.utils import displayable_amount
4+
35

46
class QueryError(ABC, ValueError):
57
"""The result of an API query is inconsistent."""
@@ -73,8 +75,8 @@ class InsufficientFundsError(Exception):
7375
available_funds: float
7476

7577
def __init__(self, required_funds: float, available_funds: float):
76-
self.required_funds = required_funds
77-
self.available_funds = available_funds
78+
self.required_funds = displayable_amount(required_funds)
79+
self.available_funds = displayable_amount(available_funds)
7880
super().__init__(
7981
f"Insufficient funds: required {required_funds}, available {available_funds}"
8082
)

src/aleph/sdk/utils.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import os
99
import subprocess
1010
from datetime import date, datetime, time
11+
from decimal import ROUND_CEILING, Decimal
1112
from enum import Enum
1213
from pathlib import Path
1314
from shutil import make_archive
@@ -418,6 +419,26 @@ def safe_getattr(obj, attr, default=None):
418419
return obj
419420

420421

422+
def displayable_amount(
423+
amount: str | int | float | Decimal, decimals: Optional[int] = None
424+
) -> str:
425+
"""Returns the amount as a string without unnecessary decimals."""
426+
427+
str_amount = ""
428+
try:
429+
dec_amount = Decimal(amount)
430+
if decimals:
431+
dec_amount = dec_amount.quantize(
432+
Decimal(1) / Decimal(10**decimals), rounding=ROUND_CEILING
433+
)
434+
str_amount = str(dec_amount)
435+
if "." in str_amount:
436+
str_amount = str_amount.rstrip("0").rstrip(".")
437+
except ValueError as e:
438+
raise ValueError(f"Invalid amount: {amount}") from e
439+
return str_amount
440+
441+
421442
def make_instance_content(
422443
rootfs: str,
423444
rootfs_size: int,

0 commit comments

Comments
 (0)