Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix asset value display #293

Merged
merged 4 commits into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
### Added

### Changed
- [\#293](https://github.com/Manta-Network/manta-rs/pull/293) Add decimals argument to AssetMetadata display

### Deprecated

Expand Down
22 changes: 10 additions & 12 deletions manta-accounting/src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,29 +1073,27 @@ pub struct AssetMetadata {
}

impl AssetMetadata {
/// Returns a string formatting of only the `value` interpreted using `self` as the metadata.
/// Returns a string formatting of only the `value` with `digits` fractional digits,
/// interpreted using `self` as the metadata.
#[inline]
pub fn display_value<V>(&self, value: V) -> String
pub fn display_value<V>(&self, value: V, digits: u32) -> String
where
for<'v> &'v V: Div<u128, Output = u128>,
{
// TODO: What if we want more than three `FRACTIONAL_DIGITS`? How do we make this method
// more general?
const FRACTIONAL_DIGITS: u32 = 3;
let value_base_units = &value / (10u128.pow(self.decimals));
let fractional_digits = &value / (10u128.pow(self.decimals - FRACTIONAL_DIGITS))
% (10u128.pow(FRACTIONAL_DIGITS));
format!("{value_base_units}.{fractional_digits:0>3}")
let fractional_digits =
&value / (10u128.pow(self.decimals - digits)) % (10u128.pow(digits));
format!("{value_base_units}.{fractional_digits}")
}

/// Returns a string formatting of `value` interpreted using `self` as the metadata including
/// the symbol.
/// Returns a string formatting of `value` with `digits` fractional digits, interpreted using
/// `self` as the metadata including the symbol.
#[inline]
pub fn display<V>(&self, value: V) -> String
pub fn display<V>(&self, value: V, digits: u32) -> String
where
for<'v> &'v V: Div<u128, Output = u128>,
{
format!("{} {}", self.display_value(value), self.symbol)
format!("{} {}", self.display_value(value, digits), self.symbol)
}
}

Expand Down