From 255a23583dca5d5d117be2ce8cd037b98e69b50a Mon Sep 17 00:00:00 2001 From: KaffinPX Date: Wed, 25 Sep 2024 00:17:53 +0300 Subject: [PATCH] Revert decimals overriding existing functs --- cli/src/extensions/transaction.rs | 19 +++++++------- cli/src/modules/account.rs | 8 +++--- cli/src/modules/pskb.rs | 2 +- cli/src/modules/rpc.rs | 2 +- cli/src/modules/send.rs | 2 +- wallet/core/src/utils.rs | 43 +++++++++++-------------------- wallet/core/src/utxo/balance.rs | 4 +-- wallet/core/src/wasm/utils.rs | 8 +++--- 8 files changed, 37 insertions(+), 51 deletions(-) diff --git a/cli/src/extensions/transaction.rs b/cli/src/extensions/transaction.rs index 3b85ea690..415aa7a34 100644 --- a/cli/src/extensions/transaction.rs +++ b/cli/src/extensions/transaction.rs @@ -132,7 +132,7 @@ impl TransactionExtension for TransactionRecord { | TransactionData::External { utxo_entries, aggregate_input_value } | TransactionData::Change { utxo_entries, aggregate_input_value, .. } => { let aggregate_input_value = - transaction_type.style_with_sign(sompi_to_kaspa_string(*aggregate_input_value, None).as_str(), history); + transaction_type.style_with_sign(sompi_to_kaspa_string(*aggregate_input_value).as_str(), history); lines.push(format!("{:>4}UTXOs: {} Total: {}", "", utxo_entries.len(), aggregate_input_value)); if include_utxos { for utxo_entry in utxo_entries { @@ -145,8 +145,7 @@ impl TransactionExtension for TransactionRecord { } else { style(format!("standard utxo [{index}]")).dim() }; - let amount = - transaction_type.style_with_sign(sompi_to_kaspa_string(utxo_entry.amount, None).as_str(), history); + let amount = transaction_type.style_with_sign(sompi_to_kaspa_string(utxo_entry.amount).as_str(), history); lines.push(format!("{:>4}{address}", "")); lines.push(format!("{:>4}{amount} {suffix} {is_coinbase}", "")); @@ -161,10 +160,10 @@ impl TransactionExtension for TransactionRecord { lines.push(format!( "{:>4}Payment: {} Used: {} Fees: {} Change: {} UTXOs: [{}↠{}]", "", - style(sompi_to_kaspa_string(*payment_value, None)).red(), - style(sompi_to_kaspa_string(*aggregate_input_value, None)).blue(), - style(sompi_to_kaspa_string(*fees, None)).red(), - style(sompi_to_kaspa_string(*change_value, None)).green(), + style(sompi_to_kaspa_string(*payment_value)).red(), + style(sompi_to_kaspa_string(*aggregate_input_value)).blue(), + style(sompi_to_kaspa_string(*fees)).red(), + style(sompi_to_kaspa_string(*change_value)).green(), transaction.inputs.len(), transaction.outputs.len(), )); @@ -172,9 +171,9 @@ impl TransactionExtension for TransactionRecord { lines.push(format!( "{:>4}Sweep: {} Fees: {} Change: {} UTXOs: [{}↠{}]", "", - style(sompi_to_kaspa_string(*aggregate_input_value, None)).blue(), - style(sompi_to_kaspa_string(*fees, None)).red(), - style(sompi_to_kaspa_string(*change_value, None)).green(), + style(sompi_to_kaspa_string(*aggregate_input_value)).blue(), + style(sompi_to_kaspa_string(*fees)).red(), + style(sompi_to_kaspa_string(*change_value)).green(), transaction.inputs.len(), transaction.outputs.len(), )); diff --git a/cli/src/modules/account.rs b/cli/src/modules/account.rs index 458d24b56..9d423e46d 100644 --- a/cli/src/modules/account.rs +++ b/cli/src/modules/account.rs @@ -122,7 +122,7 @@ impl Account { tprintln!( ctx_, "Scan detected {} KAS at index {}; transfer txid: {}", - sompi_to_kaspa_string(balance, None), + sompi_to_kaspa_string(balance), processed, txid ); @@ -131,7 +131,7 @@ impl Account { ctx_, "Scanned {} derivations, found {} KAS", processed, - sompi_to_kaspa_string(balance, None) + sompi_to_kaspa_string(balance) ); } else { tprintln!(ctx_, "Please wait... scanning for account UTXOs..."); @@ -302,12 +302,12 @@ impl Account { tprintln!( ctx_, "Scan detected {} KAS at index {}; transfer txid: {}", - sompi_to_kaspa_string(balance, None), + sompi_to_kaspa_string(balance), processed, txid ); } else { - tprintln!(ctx_, "Scanned {} derivations, found {} KAS", processed, sompi_to_kaspa_string(balance, None)); + tprintln!(ctx_, "Scanned {} derivations, found {} KAS", processed, sompi_to_kaspa_string(balance)); } })), ) diff --git a/cli/src/modules/pskb.rs b/cli/src/modules/pskb.rs index bcfdfd0f6..3757f939a 100644 --- a/cli/src/modules/pskb.rs +++ b/cli/src/modules/pskb.rs @@ -138,7 +138,7 @@ impl Pskb { "{} locked UTXO{} found with total amount of {} KAS", spend_utxos.len(), if spend_utxos.len() == 1 { "" } else { "s" }, - sompi_to_kaspa(total_locked_sompi, None) + sompi_to_kaspa(total_locked_sompi) ); // Sweep UTXO set. diff --git a/cli/src/modules/rpc.rs b/cli/src/modules/rpc.rs index 8502a841e..f32523c4a 100644 --- a/cli/src/modules/rpc.rs +++ b/cli/src/modules/rpc.rs @@ -164,7 +164,7 @@ impl Rpc { let addresses = argv.iter().map(|s| Address::try_from(s.as_str())).collect::, _>>()?; for address in addresses { let result = rpc.get_balance_by_address_call(None, GetBalanceByAddressRequest { address }).await?; - self.println(&ctx, sompi_to_kaspa(result.balance, None)); + self.println(&ctx, sompi_to_kaspa(result.balance)); } } RpcApiOps::GetBalancesByAddresses => { diff --git a/cli/src/modules/send.rs b/cli/src/modules/send.rs index 465b35771..8c28679a9 100644 --- a/cli/src/modules/send.rs +++ b/cli/src/modules/send.rs @@ -42,7 +42,7 @@ impl Send { .await?; tprintln!(ctx, "Send - {summary}"); - tprintln!(ctx, "\nSending {} KAS to {address}, tx ids:", sompi_to_kaspa_string(amount_sompi, None)); + tprintln!(ctx, "\nSending {} KAS to {address}, tx ids:", sompi_to_kaspa_string(amount_sompi)); // tprintln!(ctx, "{}\n", ids.into_iter().map(|a| a.to_string()).collect::>().join("\n")); Ok(()) diff --git a/wallet/core/src/utils.rs b/wallet/core/src/utils.rs index 838eab323..c732e3f68 100644 --- a/wallet/core/src/utils.rs +++ b/wallet/core/src/utils.rs @@ -9,14 +9,14 @@ use kaspa_consensus_core::network::NetworkType; use separator::{separated_float, separated_int, separated_uint_with_output, Separatable}; use workflow_log::style; -pub fn try_kaspa_str_to_sompi>(s: S, decimals: Option) -> Result> { +pub fn try_kaspa_str_to_sompi>(s: S) -> Result> { let s: String = s.into(); let amount = s.trim(); if amount.is_empty() { return Ok(None); } - Ok(Some(str_to_sompi(amount, decimals)?)) + Ok(Some(str_to_sompi(amount)?)) } pub fn try_kaspa_str_to_sompi_i64>(s: S) -> Result> { @@ -31,11 +31,8 @@ pub fn try_kaspa_str_to_sompi_i64>(s: S) -> Result> } #[inline] -pub fn sompi_to_kaspa(sompi: u64, decimals: Option) -> f64 { - let decimals = decimals.unwrap_or(8); - let sompi_per_unit = 10u64.pow(decimals); - - sompi as f64 / sompi_per_unit as f64 +pub fn sompi_to_kaspa(sompi: u64) -> f64 { + sompi as f64 / SOMPI_PER_KASPA as f64 } #[inline] @@ -44,13 +41,13 @@ pub fn kaspa_to_sompi(kaspa: f64) -> u64 { } #[inline] -pub fn sompi_to_kaspa_string(sompi: u64, decimals: Option) -> String { - sompi_to_kaspa(sompi, decimals).separated_string() +pub fn sompi_to_kaspa_string(sompi: u64) -> String { + sompi_to_kaspa(sompi).separated_string() } #[inline] pub fn sompi_to_kaspa_string_with_trailing_zeroes(sompi: u64) -> String { - separated_float!(format!("{:.8}", sompi_to_kaspa(sompi, None))) + separated_float!(format!("{:.8}", sompi_to_kaspa(sompi))) } pub fn kaspa_suffix(network_type: &NetworkType) -> &'static str { @@ -64,7 +61,7 @@ pub fn kaspa_suffix(network_type: &NetworkType) -> &'static str { #[inline] pub fn sompi_to_kaspa_string_with_suffix(sompi: u64, network_type: &NetworkType) -> String { - let kas = sompi_to_kaspa_string(sompi, None); + let kas = sompi_to_kaspa_string(sompi); let suffix = kaspa_suffix(network_type); format!("{kas} {suffix}") } @@ -93,31 +90,21 @@ pub fn format_address_colors(address: &Address, range: Option) -> String format!("{prefix}:{left}:{center}:{right}") } -fn str_to_sompi(amount: &str, decimals: Option) -> Result { - let decimals = decimals.unwrap_or(8); - let sompi_per_unit = 10u64.pow(decimals); - - // Check if the amount contains a decimal point, if doesn't return value directly. +fn str_to_sompi(amount: &str) -> Result { let Some(dot_idx) = amount.find('.') else { - return Ok(amount.parse::()? * sompi_per_unit); + return Ok(amount.parse::()? * SOMPI_PER_KASPA); }; - - // Parse the integer part of the amount - let integer = amount[..dot_idx].parse::()? * sompi_per_unit; - + let integer = amount[..dot_idx].parse::()? * SOMPI_PER_KASPA; let decimal = &amount[dot_idx + 1..]; let decimal_len = decimal.len(); let decimal = if decimal_len == 0 { - // If there are no digits after the decimal point, the fractional value is 0. 0 - } else if decimal_len <= decimals as usize { - // If its within allowed decimals range, parse it as u64 and pad with zeros to the right to reach the correct precision. - decimal.parse::()? * 10u64.pow(decimals - decimal_len as u32) + } else if decimal_len <= 8 { + decimal.parse::()? * 10u64.pow(8 - decimal_len as u32) } else { - // Truncate values longer than allowed decimal places. - // TODO - discuss how to handle values longer than supplied decimal places. + // TODO - discuss how to handle values longer than 8 decimal places // (reject, truncate, ceil(), etc.) - decimal[..decimals as usize].parse::()? + decimal[..8].parse::()? }; Ok(integer + decimal) } diff --git a/wallet/core/src/utxo/balance.rs b/wallet/core/src/utxo/balance.rs index 3686ce2d2..f16ce94ff 100644 --- a/wallet/core/src/utxo/balance.rs +++ b/wallet/core/src/utxo/balance.rs @@ -190,8 +190,8 @@ impl From<(Option<&Balance>, &NetworkType, Option)> for BalanceStrings { fn from((balance, network_type, padding): (Option<&Balance>, &NetworkType, Option)) -> Self { let suffix = utils::kaspa_suffix(network_type); if let Some(balance) = balance { - let mut mature = utils::sompi_to_kaspa_string(balance.mature, None); - let mut pending = if balance.pending > 0 { Some(utils::sompi_to_kaspa_string(balance.pending, None)) } else { None }; + let mut mature = utils::sompi_to_kaspa_string(balance.mature); + let mut pending = if balance.pending > 0 { Some(utils::sompi_to_kaspa_string(balance.pending)) } else { None }; if let Some(padding) = padding { mature = mature.pad_to_width(padding); pending = pending.map(|pending| pending.pad_to_width(padding)); diff --git a/wallet/core/src/wasm/utils.rs b/wallet/core/src/wasm/utils.rs index 8336698ce..a06c6136a 100644 --- a/wallet/core/src/wasm/utils.rs +++ b/wallet/core/src/wasm/utils.rs @@ -16,8 +16,8 @@ extern "C" { /// can be used to parse user input. /// @category Wallet SDK #[wasm_bindgen(js_name = "kaspaToSompi")] -pub fn kaspa_to_sompi(kaspa: String, decimals: Option) -> Option { - crate::utils::try_kaspa_str_to_sompi(kaspa, decimals).ok().flatten().map(Into::into) +pub fn kaspa_to_sompi(kaspa: String) -> Option { + crate::utils::try_kaspa_str_to_sompi(kaspa).ok().flatten().map(Into::into) } /// @@ -26,9 +26,9 @@ pub fn kaspa_to_sompi(kaspa: String, decimals: Option) -> Option { /// @category Wallet SDK /// #[wasm_bindgen(js_name = "sompiToKaspaString")] -pub fn sompi_to_kaspa_string(sompi: ISompiToKaspa, decimals: Option) -> Result { +pub fn sompi_to_kaspa_string(sompi: ISompiToKaspa) -> Result { let sompi = sompi.try_as_u64()?; - Ok(crate::utils::sompi_to_kaspa_string(sompi, decimals)) + Ok(crate::utils::sompi_to_kaspa_string(sompi)) } ///