1use crate::error::Error;
2use crate::result::Result;
3use kaspa_consensus_core::constants::SOMPI_PER_KASPA;
4use std::fmt::Display;
5
6pub fn try_parse_required_nonzero_kaspa_as_sompi_u64<S: ToString + Display>(kaspa_amount: Option<S>) -> Result<u64> {
7 if let Some(kaspa_amount) = kaspa_amount {
8 let sompi_amount = kaspa_amount
9 .to_string()
10 .parse::<f64>()
11 .map_err(|_| Error::custom(format!("Supplied Kasapa amount is not valid: '{kaspa_amount}'")))?
12 * SOMPI_PER_KASPA as f64;
13 if sompi_amount < 0.0 {
14 Err(Error::custom("Supplied Kaspa amount is not valid: '{kaspa_amount}'"))
15 } else {
16 let sompi_amount = sompi_amount as u64;
17 if sompi_amount == 0 {
18 Err(Error::custom("Supplied required kaspa amount must not be a zero: '{kaspa_amount}'"))
19 } else {
20 Ok(sompi_amount)
21 }
22 }
23 } else {
24 Err(Error::custom("Missing Kaspa amount"))
25 }
26}
27
28pub fn try_parse_required_kaspa_as_sompi_u64<S: ToString + Display>(kaspa_amount: Option<S>) -> Result<u64> {
29 if let Some(kaspa_amount) = kaspa_amount {
30 let sompi_amount = kaspa_amount
31 .to_string()
32 .parse::<f64>()
33 .map_err(|_| Error::custom(format!("Supplied Kasapa amount is not valid: '{kaspa_amount}'")))?
34 * SOMPI_PER_KASPA as f64;
35 if sompi_amount < 0.0 {
36 Err(Error::custom("Supplied Kaspa amount is not valid: '{kaspa_amount}'"))
37 } else {
38 Ok(sompi_amount as u64)
39 }
40 } else {
41 Err(Error::custom("Missing Kaspa amount"))
42 }
43}
44
45pub fn try_parse_optional_kaspa_as_sompi_i64<S: ToString + Display>(kaspa_amount: Option<S>) -> Result<Option<i64>> {
46 if let Some(kaspa_amount) = kaspa_amount {
47 let sompi_amount = kaspa_amount
48 .to_string()
49 .parse::<f64>()
50 .map_err(|_e| Error::custom(format!("Supplied Kasapa amount is not valid: '{kaspa_amount}'")))?
51 * SOMPI_PER_KASPA as f64;
52 if sompi_amount < 0.0 {
53 Err(Error::custom("Supplied Kaspa amount is not valid: '{kaspa_amount}'"))
54 } else {
55 Ok(Some(sompi_amount as i64))
56 }
57 } else {
58 Ok(None)
59 }
60}