Python 3 library and CLI application for SporeStack
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.7 KiB

  1. """
  2. Various utility functions for SporeStack.
  3. """
  4. from . import validate
  5. def payment_to_uri(address, currency, amount):
  6. """
  7. payment_to_uri: Converts address, currency, and amount (in Satoshis)
  8. to a payment URI.
  9. amount is called amount because we may add a currency that doesn't have
  10. 'satoshis' one day. This is meant to be normalizing.
  11. This does *not* validate address.
  12. """
  13. if not isinstance(address, str):
  14. raise TypeError("address must be string.")
  15. if not isinstance(currency, str):
  16. raise TypeError("currency must be string.")
  17. if not validate.unsigned_int(amount):
  18. raise TypeError("amount must be unsigned int.")
  19. if len(address) == 0:
  20. raise ValueError("address cannot be 0 length.")
  21. btc_decimal_amount = "{0:.8f}".format(amount * 0.00000001)
  22. if currency == "btc":
  23. uri = "bitcoin:{}?amount={}".format(address, btc_decimal_amount)
  24. elif currency == "bch":
  25. # This does not support "legacy" base58 addresses for Bitcoin Cash.
  26. uri = "{}?amount={}".format(address, btc_decimal_amount)
  27. elif currency == "bsv":
  28. # This does not support "legacy" cashaddr addresses for Bitcoin SV.
  29. uri = "bitcoin:{}?amount={}".format(address, btc_decimal_amount)
  30. elif currency == "xmr":
  31. xmr_decimal_amount = "{0:.12f}".format(amount * 0.000000000001)
  32. uri = "monero:{}?tx_amount={}".format(address, xmr_decimal_amount)
  33. else:
  34. raise ValueError("Currency must be one of: btc, bch, bsv, xmr")
  35. return uri
  36. def cents_to_usd(cents):
  37. """
  38. cents_to_usd: Convert cents to USD string.
  39. """
  40. if not validate.unsigned_int(cents):
  41. raise TypeError("cents must be unsigned int.")
  42. return "${:,.2f}".format(cents * 0.01)