Skip to content

Commit

Permalink
Revert decimals overriding existing functs
Browse files Browse the repository at this point in the history
  • Loading branch information
KaffinPX committed Sep 24, 2024
1 parent 8e71af0 commit 255a235
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 51 deletions.
19 changes: 9 additions & 10 deletions cli/src/extensions/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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}", ""));
Expand All @@ -161,20 +160,20 @@ 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(),
));
} else {
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(),
));
Expand Down
8 changes: 4 additions & 4 deletions cli/src/modules/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
Expand All @@ -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...");
Expand Down Expand Up @@ -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));
}
})),
)
Expand Down
2 changes: 1 addition & 1 deletion cli/src/modules/pskb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion cli/src/modules/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl Rpc {
let addresses = argv.iter().map(|s| Address::try_from(s.as_str())).collect::<std::result::Result<Vec<_>, _>>()?;
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 => {
Expand Down
2 changes: 1 addition & 1 deletion cli/src/modules/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>().join("\n"));

Ok(())
Expand Down
43 changes: 15 additions & 28 deletions wallet/core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: Into<String>>(s: S, decimals: Option<u32>) -> Result<Option<u64>> {
pub fn try_kaspa_str_to_sompi<S: Into<String>>(s: S) -> Result<Option<u64>> {
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: Into<String>>(s: S) -> Result<Option<i64>> {
Expand All @@ -31,11 +31,8 @@ pub fn try_kaspa_str_to_sompi_i64<S: Into<String>>(s: S) -> Result<Option<i64>>
}

#[inline]
pub fn sompi_to_kaspa(sompi: u64, decimals: Option<u32>) -> 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]
Expand All @@ -44,13 +41,13 @@ pub fn kaspa_to_sompi(kaspa: f64) -> u64 {
}

#[inline]
pub fn sompi_to_kaspa_string(sompi: u64, decimals: Option<u32>) -> 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 {
Expand All @@ -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}")
}
Expand Down Expand Up @@ -93,31 +90,21 @@ pub fn format_address_colors(address: &Address, range: Option<usize>) -> String
format!("{prefix}:{left}:{center}:{right}")
}

fn str_to_sompi(amount: &str, decimals: Option<u32>) -> Result<u64> {
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<u64> {
let Some(dot_idx) = amount.find('.') else {
return Ok(amount.parse::<u64>()? * sompi_per_unit);
return Ok(amount.parse::<u64>()? * SOMPI_PER_KASPA);
};

// Parse the integer part of the amount
let integer = amount[..dot_idx].parse::<u64>()? * sompi_per_unit;

let integer = amount[..dot_idx].parse::<u64>()? * 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::<u64>()? * 10u64.pow(decimals - decimal_len as u32)
} else if decimal_len <= 8 {
decimal.parse::<u64>()? * 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::<u64>()?
decimal[..8].parse::<u64>()?
};
Ok(integer + decimal)
}
4 changes: 2 additions & 2 deletions wallet/core/src/utxo/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ impl From<(Option<&Balance>, &NetworkType, Option<usize>)> for BalanceStrings {
fn from((balance, network_type, padding): (Option<&Balance>, &NetworkType, Option<usize>)) -> 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));
Expand Down
8 changes: 4 additions & 4 deletions wallet/core/src/wasm/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>) -> Option<BigInt> {
crate::utils::try_kaspa_str_to_sompi(kaspa, decimals).ok().flatten().map(Into::into)
pub fn kaspa_to_sompi(kaspa: String) -> Option<BigInt> {
crate::utils::try_kaspa_str_to_sompi(kaspa).ok().flatten().map(Into::into)
}

///
Expand All @@ -26,9 +26,9 @@ pub fn kaspa_to_sompi(kaspa: String, decimals: Option<u32>) -> Option<BigInt> {
/// @category Wallet SDK
///
#[wasm_bindgen(js_name = "sompiToKaspaString")]
pub fn sompi_to_kaspa_string(sompi: ISompiToKaspa, decimals: Option<u32>) -> Result<String> {
pub fn sompi_to_kaspa_string(sompi: ISompiToKaspa) -> Result<String> {
let sompi = sompi.try_as_u64()?;
Ok(crate::utils::sompi_to_kaspa_string(sompi, decimals))
Ok(crate::utils::sompi_to_kaspa_string(sompi))
}

///
Expand Down

0 comments on commit 255a235

Please sign in to comment.