Skip to content
This repository has been archived by the owner on Aug 22, 2024. It is now read-only.

feat: improve near amount display #41

Closed
wants to merge 6 commits into from
Closed
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
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ __pycache__/
# Virtual env for sideload (macOS and Windows)
ledger/
# Build directory
build/
build/

fmt_buffer/Cargo.lock
near_token/Cargo.lock
21 changes: 14 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ ledger_secure_sdk_sys = "1.2.0"
include_gif = "1.0.1"
hex = { version = "0.4.3", default-features = false, features = ["serde"] }
bs58 = { version = "0.5.0", default-features = false }
fmt_buffer = { version = "0.1.0", path = "./fmt_buffer" }
near_token = { version = "0.1.0", path = "./near_token" }
numtoa = "0.2.4"
dtoa = "1.0.9"

[profile.release]
opt-level = 'z'
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ speculos --model nanox target/nanox/release/app-near-rust

See [local_test_helper.sh](./local_test_helper.sh).

#### Unit testing

See [local_unit_tests.sh](./local_unit_tests.sh).

## Continuous Integration

The following workflows are executed in [GitHub Actions](https://github.com/features/actions) :
Expand Down
2 changes: 2 additions & 0 deletions fmt_buffer/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "x86_64-unknown-linux-gnu"
11 changes: 11 additions & 0 deletions fmt_buffer/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "fmt_buffer"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[dev-dependencies]
numtoa = "0.2.4"
134 changes: 134 additions & 0 deletions fmt_buffer/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
#![no_std]
pub struct Buffer<const N: usize> {
buffer: [u8; N],
used: usize,
truncated: bool,
pub leftover: usize,
}

impl<const N: usize> Buffer<N> {
pub fn new() -> Self {
Buffer {
buffer: [0u8; N],
used: 0,
truncated: false,
leftover: 0,
}
}

pub fn as_str(&self) -> &str {
debug_assert!(self.used <= self.buffer.len());
use core::str::from_utf8_unchecked;
unsafe { from_utf8_unchecked(&self.buffer[..self.used]) }
}

#[allow(unused)]
pub fn truncated(&self) -> bool {
self.truncated
}
}

impl<const N: usize> Buffer<N> {
pub fn write_str(&mut self, s: &str) {
let remaining_buf = &mut self.buffer[self.used..];
let raw_s = s.as_bytes();

let raw_s_len = raw_s.len();
let remaining_len = remaining_buf.len();

let bytes_written = if remaining_len < raw_s_len {
self.truncated = true;
match s.char_indices().rfind(|&(ind, _char)| ind <= remaining_len) {
None => {
// noop, truncating all reftover chars
0
}
Some((ind, _cahr)) => ind,
}
} else {
raw_s_len
};
remaining_buf[..bytes_written].copy_from_slice(&raw_s[..bytes_written]);
self.used += bytes_written;
self.leftover += raw_s_len - bytes_written;
}
}

#[cfg(test)]
mod tests {
use super::Buffer;

use numtoa::NumToA;

#[test]
pub fn test() {
let mut buffer = Buffer::<30>::new();
let mut numtoa = [0u8; 10];

buffer.write_str(42u32.numtoa_str(10, &mut numtoa));
buffer.write_str(" - 0x");
buffer.write_str(42u32.numtoa_str(16, &mut numtoa));

assert_eq!("42 - 0x2A", buffer.as_str());
assert_eq!(false, buffer.truncated());
}

#[test]
pub fn test_longer() {
let mut buffer = Buffer::<30>::new();
let mut numtoa = [0u8; 10];

buffer.write_str(4000u32.numtoa_str(10, &mut numtoa));
buffer.write_str(" - 0x");
buffer.write_str(4001u32.numtoa_str(16, &mut numtoa));

assert_eq!("4000 - 0xFA1", buffer.as_str());
assert_eq!(false, buffer.truncated());
}

#[test]
pub fn test_longer_trunc() {
let mut buffer = Buffer::<30>::new();
let mut numtoa = [0u8; 10];

buffer.write_str("long: ");
buffer.write_str(400000u32.numtoa_str(10, &mut numtoa));
buffer.write_str(" - 0x");
buffer.write_str(400100u32.numtoa_str(16, &mut numtoa));

assert_eq!("long: 400000 - 0x61AE4", buffer.as_str());
assert_eq!(false, buffer.truncated());
}

#[test]
pub fn test_too_long() {
let mut buffer = Buffer::<30>::new();
let mut numtoa = [0u8; 10];

buffer.write_str("toooooo long: ");
buffer.write_str(400000u32.numtoa_str(10, &mut numtoa));
buffer.write_str(" - 0x");
buffer.write_str(400100u32.numtoa_str(16, &mut numtoa));

assert_eq!("toooooo long: 400000 - 0x61", buffer.as_str());
assert_eq!(true, buffer.truncated());
}

#[test]
pub fn test_too_long_over_the_end() {
let mut buffer = Buffer::<30>::new();
let mut numtoa = [0u8; 10];

buffer.write_str("toooooo long: ");
buffer.write_str(400000u32.numtoa_str(10, &mut numtoa));
buffer.write_str(" - 0x");
buffer.write_str(400100u32.numtoa_str(16, &mut numtoa));

assert_eq!("toooooo long: 400000 - 0x61", buffer.as_str());
assert_eq!(true, buffer.truncated());

buffer.write_str("some more");
assert_eq!("toooooo long: 400000 - 0x61", buffer.as_str());
assert_eq!(true, buffer.truncated());
}
}
7 changes: 7 additions & 0 deletions local_unit_tests.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
set -xe
pushd fmt_buffer
cargo +stable test
popd
pushd near_token
cargo +stable test
popd
2 changes: 2 additions & 0 deletions near_token/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "x86_64-unknown-linux-gnu"
10 changes: 10 additions & 0 deletions near_token/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "near_token"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
fmt_buffer = { version = "0.1.0", path = "../fmt_buffer" }
numtoa = "0.2.4"
126 changes: 126 additions & 0 deletions near_token/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#![no_std]
use fmt_buffer::Buffer;

/// Balance is type for storing amounts of tokens.
pub type Balance = u128;

const ONE_MILLINEAR: u128 = 10_u128.pow(21);
use numtoa::NumToA;

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct NearToken(pub Balance);

impl NearToken {
/// `from_yoctonear` is a function that takes value by a number of yocto-near.
/// # Examples
/// ```
/// use near_token::NearToken;
/// assert_eq!( NearToken::from_yoctonear(10u128.pow(21)), NearToken::from_millinear(1))
/// ```
pub const fn from_yoctonear(inner: u128) -> Self {
Self(inner)
}

/// `from_millinear` is a function that takes value by a number of mili-near and converts it to an equivalent to the yocto-near.
/// # Examples
/// ```
/// use near_token::NearToken;
/// assert_eq!(NearToken::from_millinear(1), NearToken::from_yoctonear(10u128.pow(21)))
/// ```
pub const fn from_millinear(inner: u128) -> Self {
Self(inner * ONE_MILLINEAR)
}

/// `as_yoctonear` is a function that shows a number of yocto-near.
/// # Examples
/// ```
/// use near_token::NearToken;
/// assert_eq!(NearToken::from_yoctonear(10).as_yoctonear(), 10)
/// ```
pub const fn as_yoctonear(&self) -> u128 {
self.0
}

pub fn display_as_buffer(&self, result: &mut Buffer<30>) {
if *self == NearToken::from_yoctonear(0) {
result.write_str("0 NEAR");
} else if *self == NearToken::from_yoctonear(1) {
result.write_str("1 yoctoNEAR");
} else if *self < NearToken::from_millinear(1) {
result.write_str("less than 0.001 NEAR");
} else if *self <= NearToken::from_millinear(999) {
let millinear_rounded_up =
(self.as_yoctonear().saturating_add(ONE_MILLINEAR - 1) / ONE_MILLINEAR) as u32;

let mut millis_str_buf = [0u8; 10];

result.write_str("0.");
let millis_str = millinear_rounded_up.numtoa_str(10, &mut millis_str_buf);
let leading_zeros = 3 - millis_str.len();
for _ in 0..leading_zeros {
result.write_str("0");
}
result.write_str(millis_str);
result.write_str(" NEAR");
} else {
let near_rounded_up =
self.as_yoctonear().saturating_add(10 * ONE_MILLINEAR - 1) / ONE_MILLINEAR / 10;
let mut str_buf = [0u8; 20];

result.write_str((near_rounded_up as u64 / 100).numtoa_str(10, &mut str_buf));
result.write_str(".");
let hundreds_str = (near_rounded_up as u64 % 100).numtoa_str(10, &mut str_buf);
let leading_zeros = 2 - hundreds_str.len();
for _ in 0..leading_zeros {
result.write_str("0");
}
result.write_str(hundreds_str);
result.write_str(" NEAR");
}
}
}

#[cfg(test)]
mod tests {
use super::NearToken;
use fmt_buffer::Buffer;

#[test]
fn test_display() {
for (integer, expected) in [
(1234560000000000000000000000u128, "1234.56 NEAR"),
(10000000000000000000, "less than 0.001 NEAR"),
(0, "0 NEAR"),
(1, "1 yoctoNEAR"),
] {
let mut buffer: Buffer<30> = Buffer::new();

let token = NearToken::from_yoctonear(integer);

token.display_as_buffer(&mut buffer);

assert_eq!(buffer.as_str(), expected);
assert_eq!(buffer.truncated(), false);
}

for (integer_millis, expected) in [
(1, "0.001 NEAR"),
(11, "0.011 NEAR"),
(111, "0.111 NEAR"),
(1000, "1.00 NEAR"),
(1001, "1.01 NEAR"),
(1010, "1.01 NEAR"),
(1100, "1.10 NEAR"),
(1000 * 1_000_000, "1000000.00 NEAR"),
] {
let mut buffer: Buffer<30> = Buffer::new();

let token = NearToken::from_millinear(integer_millis);

token.display_as_buffer(&mut buffer);

assert_eq!(buffer.as_str(), expected);
assert_eq!(buffer.truncated(), false);
}
}
}
4 changes: 2 additions & 2 deletions src/app_ui/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@
*****************************************************************************/

use crate::utils::crypto;
use crate::utils::types::fmt_buffer::FmtBuffer;
use crate::AppSW;
use fmt_buffer::Buffer;
use ledger_device_sdk::ui::bitmaps::{CROSSMARK, EYE, VALIDATE_14};
use ledger_device_sdk::ui::gadgets::{Field, MultiFieldReview};

pub fn ui_display_pk_base58(public_key: &crypto::PublicKeyBe) -> Result<bool, AppSW> {
let mut out_buf = FmtBuffer::<60>::new();
let mut out_buf = Buffer::<60>::new();
public_key.display_str_base58(&mut out_buf)?;

let my_field = [Field {
Expand Down
Loading
Loading