2020-05-18 14:22:23 +02:00
|
|
|
import re
|
2018-10-03 22:38:47 +02:00
|
|
|
import textwrap
|
2020-04-12 21:30:25 +02:00
|
|
|
from decimal import Decimal
|
2020-05-18 14:22:23 +02:00
|
|
|
|
|
|
|
from lbry.constants import COIN
|
2018-10-03 22:38:47 +02:00
|
|
|
|
|
|
|
|
2018-11-30 22:11:23 +01:00
|
|
|
def lbc_to_dewies(lbc: str) -> int:
|
2018-11-20 01:23:23 +01:00
|
|
|
try:
|
2020-05-18 14:22:23 +02:00
|
|
|
if not isinstance(lbc, str):
|
|
|
|
raise ValueError("{coins} must be a string")
|
|
|
|
result = re.search(r'^(\d{1,10})\.(\d{1,8})$', lbc)
|
|
|
|
if result is not None:
|
|
|
|
whole, fractional = result.groups()
|
|
|
|
return int(whole + fractional.ljust(8, "0"))
|
|
|
|
raise ValueError(f"'{lbc}' is not a valid coin decimal")
|
2018-11-20 01:23:23 +01:00
|
|
|
except ValueError:
|
|
|
|
raise ValueError(textwrap.dedent(
|
2019-10-08 18:19:01 +02:00
|
|
|
f"""
|
2018-11-20 01:23:23 +01:00
|
|
|
Decimal inputs require a value in the ones place and in the tenths place
|
2019-10-08 18:19:01 +02:00
|
|
|
separated by a period. The value provided, '{lbc}', is not of the correct
|
2018-11-20 01:23:23 +01:00
|
|
|
format.
|
|
|
|
|
|
|
|
The following are examples of valid decimal inputs:
|
|
|
|
|
|
|
|
1.0
|
|
|
|
0.001
|
|
|
|
2.34500
|
|
|
|
4534.4
|
|
|
|
2323434.0000
|
|
|
|
|
|
|
|
The following are NOT valid:
|
|
|
|
|
|
|
|
83
|
|
|
|
.456
|
|
|
|
123.
|
2019-10-08 18:19:01 +02:00
|
|
|
"""
|
2018-11-20 01:23:23 +01:00
|
|
|
))
|
2018-10-03 22:38:47 +02:00
|
|
|
|
|
|
|
|
2018-11-30 22:11:23 +01:00
|
|
|
def dewies_to_lbc(dewies) -> str:
|
2020-05-18 14:22:23 +02:00
|
|
|
coins = '{:.8f}'.format(dewies / COIN).rstrip('0')
|
|
|
|
if coins.endswith('.'):
|
|
|
|
return coins+'0'
|
|
|
|
else:
|
|
|
|
return coins
|
2019-10-14 01:32:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
def dict_values_to_lbc(d):
|
2019-11-05 15:31:33 +01:00
|
|
|
lbc_dict = {}
|
2019-10-14 01:32:10 +02:00
|
|
|
for key, value in d.items():
|
2020-04-12 21:30:25 +02:00
|
|
|
if isinstance(value, (int, Decimal)):
|
2019-11-05 15:31:33 +01:00
|
|
|
lbc_dict[key] = dewies_to_lbc(value)
|
2019-10-14 01:32:10 +02:00
|
|
|
elif isinstance(value, dict):
|
2019-11-05 15:31:33 +01:00
|
|
|
lbc_dict[key] = dict_values_to_lbc(value)
|
|
|
|
else:
|
|
|
|
lbc_dict[key] = value
|
|
|
|
return lbc_dict
|