Skip to content

Commit

Permalink
Add displayable amount
Browse files Browse the repository at this point in the history
  • Loading branch information
philogicae committed Feb 6, 2025
1 parent 84e6a80 commit 13be020
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/aleph/sdk/evm_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def to_wei_token(amount: Decimal) -> Decimal:

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


def get_chain_id(chain: Union[Chain, str, None]) -> Optional[int]:
Expand Down
6 changes: 4 additions & 2 deletions src/aleph/sdk/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from abc import ABC

from aleph.sdk.utils import displayable_amount


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

def __init__(self, required_funds: float, available_funds: float):
self.required_funds = required_funds
self.available_funds = available_funds
self.required_funds = displayable_amount(required_funds)
self.available_funds = displayable_amount(available_funds)
super().__init__(
f"Insufficient funds: required {required_funds}, available {available_funds}"
)
Expand Down
21 changes: 21 additions & 0 deletions src/aleph/sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import os
import subprocess
from datetime import date, datetime, time
from decimal import ROUND_CEILING, Decimal
from enum import Enum
from pathlib import Path
from shutil import make_archive
Expand Down Expand Up @@ -418,6 +419,26 @@ def safe_getattr(obj, attr, default=None):
return obj


def displayable_amount(
amount: str | int | float | Decimal, decimals: Optional[int] = None
) -> str:
"""Returns the amount as a string without unnecessary decimals."""

str_amount = ""
try:
dec_amount = Decimal(amount)
if decimals:
dec_amount = dec_amount.quantize(
Decimal(1) / Decimal(10**decimals), rounding=ROUND_CEILING
)
str_amount = str(dec_amount)
if "." in str_amount:
str_amount = str_amount.rstrip("0").rstrip(".")
except ValueError as e:
raise ValueError(f"Invalid amount: {amount}") from e
return str_amount


def make_instance_content(
rootfs: str,
rootfs_size: int,
Expand Down

0 comments on commit 13be020

Please sign in to comment.