Skip to content

Commit

Permalink
Fixes after merge
Browse files Browse the repository at this point in the history
  • Loading branch information
sdbondi committed Oct 15, 2021
1 parent e7c35dd commit 32cfc93
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 127 deletions.
15 changes: 8 additions & 7 deletions base_layer/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,37 +35,38 @@ async-trait = "0.1.50"
bincode = "1.1.4"
bitflags = "1.0.4"
blake2 = "^0.9.0"
sha3 = "0.9"
bytes = "0.5"
chrono = { version = "0.4.6", features = ["serde"] }
croaring = { version = "=0.4.5", optional = true }
decimal-rs = "0.1.20"
derive_more = "0.99.16"
digest = "0.9.0"
futures = { version = "^0.3.16", features = ["async-await"] }
fs2 = "0.3.0"
futures = { version = "^0.3.16", features = ["async-await"] }
hex = "0.4.2"
integer-encoding = "3.0.2"
lazy_static = "1.4.0"
lmdb-zero = "0.4.4"
log = "0.4"
monero = { version = "^0.13.0", features = ["serde_support"], optional = true }
newtype-ops = "0.1.4"
num = "0.3"
num-format = "0.4.0"
prost = "0.8.0"
prost-types = "0.8.0"
rand = "0.8"
randomx-rs = { version = "1.1.9", optional = true }
serde = { version = "1.0.106", features = ["derive"] }
serde_json = "1.0"
sha3 = "0.9"
strum_macros = "0.17.1"
thiserror = "1.0.26"
tokio = { version = "1.11", features = ["time", "sync", "macros"] }
ttl_cache = "0.5.1"
uint = { version = "0.9", default-features = false }
num-format = "0.4.0"
tracing = "0.1.26"
tracing-futures = "*"
tracing-attributes = "*"
derive_more = "0.99.16"
tracing-futures = "*"
ttl_cache = "0.5.1"
uint = { version = "0.9", default-features = false }

[dev-dependencies]
tari_p2p = { version = "^0.11", path = "../../base_layer/p2p", features = ["test-mocks"] }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,51 +24,44 @@
/// # Examples
///
/// ```
/// use tari_core::transactions::display_currency::display_currency;
/// assert_eq!(String::from("12,345.12"), display_currency(12345.12, 2, ","));
/// assert_eq!(String::from("12,345"), display_currency(12345.12, 0, ","));
/// use tari_core::transactions::helpers::format_currency;
/// assert_eq!("12,345.12", format_currency("12345.12", ','));
/// assert_eq!("12,345", format_currency("12345", ','));
/// ```
pub fn display_currency(value: f64, precision: usize, separator: &str) -> String {
let whole = value as usize;
let decimal = ((value - whole as f64) * num::pow(10_f64, precision)).round() as usize;
let formatted_whole_value = whole
.to_string()
.chars()
.rev()
.enumerate()
.fold(String::new(), |acc, (i, c)| {
if i != 0 && i % 3 == 0 {
format!("{}{}{}", acc, separator, c)
} else {
format!("{}{}", acc, c)
}
})
.chars()
.rev()
.collect::<String>();

if precision > 0 {
format!("{}.{:0>2$}", formatted_whole_value, decimal, precision)
} else {
formatted_whole_value
pub fn format_currency(value: &str, separator: char) -> String {
let full_len = value.len();
let mut buffer = String::with_capacity(full_len / 3 + full_len);
let mut iter = value.splitn(2, '.');
let whole = iter.next().unwrap_or("");
let mut idx = whole.len() as isize - 1;
for c in whole.chars() {
buffer.push(c);
if idx > 0 && idx % 3 == 0 {
buffer.push(separator);
}
idx -= 1;
}
if let Some(decimal) = iter.next() {
buffer.push('.');
buffer.push_str(decimal);
}
buffer
}

#[cfg(test)]
#[allow(clippy::excessive_precision)]
mod test {
use super::format_currency;

#[test]
fn display_currency() {
assert_eq!(String::from("0.00"), super::display_currency(0.0f64, 2, ","));
assert_eq!(String::from("0.000000000000"), super::display_currency(0.0f64, 12, ","));
assert_eq!(
String::from("123,456.123456789"),
super::display_currency(123_456.123_456_789_012_f64, 9, ",")
);
assert_eq!(
String::from("123,456"),
super::display_currency(123_456.123_456_789_012_f64, 0, ",")
);
assert_eq!(String::from("1,234"), super::display_currency(1234.1f64, 0, ","));
fn test_format_currency() {
assert_eq!("0.00", format_currency("0.00", ','));
assert_eq!("0.000000000000", format_currency("0.000000000000", ','));
assert_eq!("123,456.123456789", format_currency("123456.123456789", ','));
assert_eq!("123,456", format_currency("123456", ','));
assert_eq!("123", format_currency("123", ','));
assert_eq!("7,123", format_currency("7123", ','));
assert_eq!(".00", format_currency(".00", ','));
assert_eq!("00.", format_currency("00.", ','));
}
}
4 changes: 3 additions & 1 deletion base_layer/core/src/transactions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ pub use crypto_factories::CryptoFactories;
mod coinbase_builder;
pub use coinbase_builder::{CoinbaseBuildError, CoinbaseBuilder};

pub mod display_currency;
pub mod fee;
pub mod tari_amount;
pub mod transaction;

mod format_currency;
pub use format_currency::format_currency;

pub mod transaction_protocol;
pub use transaction_protocol::{recipient::ReceiverTransactionProtocol, sender::SenderTransactionProtocol};

Expand Down
11 changes: 5 additions & 6 deletions base_layer/core/src/transactions/tari_amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::transactions::display_currency::display_currency;
use newtype_ops::newtype_ops;
use serde::{Deserialize, Serialize};
use crate::transactions::helpers;
use super::format_currency;
use decimal_rs::{Decimal, DecimalConvertError};
use derive_more::{Add, AddAssign, Div, From, FromStr, Into, Mul, Rem, Sub, SubAssign};
use newtype_ops::newtype_ops;
use serde::{Deserialize, Serialize};
use std::{
convert::{TryFrom, TryInto},
fmt::{Display, Error, Formatter},
Expand Down Expand Up @@ -214,7 +213,7 @@ impl From<MicroTari> for FormattedMicroTari {
impl Display for FormattedMicroTari {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let value = format!("{}", self.0);
let formatted = helpers::format_currency(&value, ',');
let formatted = format_currency(&value, ',');
f.write_str(&formatted)?;
f.write_str(" µT")?;
Ok(())
Expand All @@ -233,7 +232,7 @@ impl From<Tari> for FormattedTari {
impl Display for FormattedTari {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let value = format!("{:.2}", self.0);
let formatted = helpers::format_currency(&value, ',');
let formatted = format_currency(&value, ',');
f.write_str(&formatted)?;
f.write_str(" T")?;
Ok(())
Expand Down
93 changes: 19 additions & 74 deletions base_layer/core/src/transactions/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,26 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::sync::Arc;

use rand::rngs::OsRng;
use tari_crypto::{
commitment::HomomorphicCommitmentFactory,
common::Blake256,
inputs,
keys::{PublicKey as PK, SecretKey},
range_proof::RangeProofService,
script,
script::{ExecutionStack, TariScript},
};

use crate::transactions::{
crypto_factories::CryptoFactories,
fee::Fee,
tari_amount::MicroTari,
transaction::{
KernelBuilder,
KernelFeatures,
OutputFeatures,
Transaction,
TransactionInput,
TransactionKernel,
TransactionOutput,
UnblindedOutput,
use crate::{
consensus::{ConsensusEncodingSized, ConsensusEncodingWrapper, ConsensusManager},
transactions::{
crypto_factories::CryptoFactories,
fee::Fee,
tari_amount::MicroTari,
transaction::{
KernelBuilder,
KernelFeatures,
OutputFeatures,
Transaction,
TransactionInput,
TransactionKernel,
TransactionOutput,
UnblindedOutput,
},
transaction_protocol::{build_challenge, TransactionMetadata},
weight::TransactionWeight,
SenderTransactionProtocol,
},
transaction_protocol::{build_challenge, TransactionMetadata},
SenderTransactionProtocol,
};
use rand::rngs::OsRng;
use std::sync::Arc;
Expand Down Expand Up @@ -602,49 +593,3 @@ pub fn schema_to_transaction(txns: &[TransactionSchema]) -> (Vec<Arc<Transaction
});
(tx, utxos)
}

/// Return a currency styled `String`
/// # Examples
///
/// ```
/// use tari_core::transactions::helpers::format_currency;
/// assert_eq!("12,345.12", format_currency("12345.12", ','));
/// assert_eq!("12,345", format_currency("12345", ','));
/// ```
pub fn format_currency(value: &str, separator: char) -> String {
let full_len = value.len();
let mut buffer = String::with_capacity(full_len / 3 + full_len);
let mut iter = value.splitn(2, '.');
let whole = iter.next().unwrap_or("");
let mut idx = whole.len() as isize - 1;
for c in whole.chars() {
buffer.push(c);
if idx > 0 && idx % 3 == 0 {
buffer.push(separator);
}
idx -= 1;
}
if let Some(decimal) = iter.next() {
buffer.push('.');
buffer.push_str(decimal);
}
buffer
}

#[cfg(test)]
#[allow(clippy::excessive_precision)]
mod test {
use super::format_currency;

#[test]
fn test_format_currency() {
assert_eq!("0.00", format_currency("0.00", ','));
assert_eq!("0.000000000000", format_currency("0.000000000000", ','));
assert_eq!("123,456.123456789", format_currency("123456.123456789", ','));
assert_eq!("123,456", format_currency("123456", ','));
assert_eq!("123", format_currency("123", ','));
assert_eq!("7,123", format_currency("7123", ','));
assert_eq!(".00", format_currency(".00", ','));
assert_eq!("00.", format_currency("00.", ','));
}
}
2 changes: 1 addition & 1 deletion base_layer/wallet/tests/output_manager_service/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,7 @@ async fn sending_transaction_with_short_term_clear() {
.prepare_transaction_to_send(
OsRng.next_u64(),
MicroTari::from(1000),
fee_per_gram,
MicroTari::from(4),
None,
"".to_string(),
script!(Nop),
Expand Down

0 comments on commit 32cfc93

Please sign in to comment.