EIP-55 addresses, decimal-aware token amounts in integer base units, and basis-point math for rates, slippage, vault shares and health factors.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::badge::{Badge, BadgeVariant};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
use crate::ui::onchain::{format_units, parse_units, Address};
use crate::ui::tabs::Tabs;
/// Sample tokens with their real decimals. The demo touches no chain.
const TOKENS: [(&str, u8); 3] = [("ETH", 18), ("USDC", 6), ("WBTC", 8)];
/// Type an address to check its EIP-55 checksum, or an amount to see it in base units.
#[derive(Default)]
pub struct OnchainDemo {
token: usize,
}
impl Render for OnchainDemo {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Keyed state redraws this view on every keystroke, so the results follow the text.
let address = window.use_keyed_state("onchain-address", cx, |_, cx| {
TextInput::new(cx).default_value("0x00000000000000000000000000000000000a11ce")
});
let amount = window.use_keyed_state("onchain-amount", cx, |_, cx| {
TextInput::new(cx).default_value("1.5")
});
let theme = cx.theme().clone();
let (symbol, decimals) = TOKENS[self.token];
let address_text = address.read(cx).text();
let (address_badge, address_note) = match Address::parse(&address_text) {
Ok(parsed) if parsed.checksummed() == address_text.as_ref() => {
(Badge::new("Checksummed").variant(BadgeVariant::Secondary), parsed.short())
}
Ok(parsed) => (Badge::new("No checksum").variant(BadgeVariant::Outline), parsed.to_string()),
Err(error) => (Badge::new("Invalid").variant(BadgeVariant::Destructive), error.to_string()),
};
let amount_text = amount.read(cx).text();
let (amount_badge, amount_note) = match parse_units(&amount_text, decimals) {
Ok(units) => (
Badge::new(format!("{units} base units")).variant(BadgeVariant::Secondary),
format!("{} {symbol}", format_units(units, decimals)),
),
Err(error) => (Badge::new("Invalid").variant(BadgeVariant::Destructive), error.to_string()),
};
let result = |badge: Badge, note: String| {
div()
.flex()
.items_center()
.gap_2()
.min_w_0()
.child(badge)
.child(div().min_w_0().truncate().text_xs().font_family("Geist Mono").text_color(theme.muted_foreground).child(note))
};
div()
.w(px(480.0))
.flex()
.flex_col()
.gap_6()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(Field::new().label("Address").child(address))
.child(result(address_badge, address_note)),
)
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.flex()
.items_center()
.justify_between()
.child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Amount"))
.child(
TOKENS.iter().fold(
Tabs::new("onchain-token", self.token).on_select(cx.listener(
|this, ix: &usize, _, cx| {
this.token = *ix;
cx.notify();
},
)),
|tabs, (symbol, _)| tabs.tab(*symbol),
),
),
)
.child(amount)
.child(result(amount_badge, amount_note)),
)
}
}Installation
Copies src/ui/onchain.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
It also runs cargo add sha3@0.10 for the crates this component uses, unless your Cargo.toml already lists them.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Add the crates
$ cargo add sha3@0.10Copy the source
Paste the code below into
src/ui/onchain.rs.src/ui/onchain.rs //! Pure helpers for onchain UIs: EIP-55 addresses, token amounts in integer base units, and the //! basis-point math behind rates, slippage, price impact, vault shares and health factors. //! //! No floats anywhere: a token amount is a `u128` count of base units (wei for an 18-decimal //! token), and percentages are basis points (10_000 bps = 100%). `u128` holds up to about //! 3.4e38, which is smaller than Solidity's `uint256`: values that don't fit come back as an //! error or `None`, never wrapped or clamped. The host app owns wallets and RPC; this file only //! parses, checks and formats what the UI shows. //! //! Needs the `sha3` crate for Keccak-256: `cargo add sha3`. use std::fmt; use sha3::{Digest, Keccak256}; /// 100% in basis points. pub const BPS: u128 = 10_000; /// Largest decimals a `u128` amount can carry: 10^38 still fits, 10^39 doesn't. pub const MAX_DECIMALS: u8 = 38; /// Keccak-256, the hash Ethereum uses. Not the same as FIPS SHA3-256, which pads differently. pub fn keccak256(bytes: &[u8]) -> [u8; 32] { Keccak256::digest(bytes).into() } // --------------------------------------------------------------------------------------------- // Addresses // --------------------------------------------------------------------------------------------- /// A 20-byte account or contract address. `Display` prints it EIP-55 checksummed. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Address(pub [u8; 20]); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AddressError { /// Missing the `0x` prefix. MissingPrefix, /// Not exactly 40 hex digits after `0x`. WrongLength, /// A character that isn't a hex digit. NotHex, /// Mixed case that doesn't match the EIP-55 checksum: likely a typo. BadChecksum, } impl fmt::Display for AddressError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::MissingPrefix => "Addresses start with 0x.", Self::WrongLength => "An address is 40 hex characters after 0x.", Self::NotHex => "Only 0-9 and a-f are allowed.", Self::BadChecksum => "Checksum mismatch. Check the address for typos.", }) } } impl Address { /// Parses `0x` + 40 hex digits. All-lowercase and all-uppercase input carries no checksum and /// is accepted; mixed case must match EIP-55 exactly. pub fn parse(input: &str) -> Result<Self, AddressError> { let hex = input.strip_prefix("0x").ok_or(AddressError::MissingPrefix)?; if hex.len() != 40 { return Err(AddressError::WrongLength); } let mut bytes = [0u8; 20]; for (ix, pair) in hex.as_bytes().chunks(2).enumerate() { let hi = hex_value(pair[0]).ok_or(AddressError::NotHex)?; let lo = hex_value(pair[1]).ok_or(AddressError::NotHex)?; bytes[ix] = hi << 4 | lo; } let address = Self(bytes); let has_lower = hex.bytes().any(|b| b.is_ascii_lowercase()); let has_upper = hex.bytes().any(|b| b.is_ascii_uppercase()); if has_lower && has_upper && address.checksummed() != input { return Err(AddressError::BadChecksum); } Ok(address) } /// The EIP-55 spelling: a hex letter is uppercase when the matching nibble of /// keccak256(lowercase hex) is 8 or more. pub fn checksummed(&self) -> String { let lower: String = self.0.iter().map(|b| format!("{b:02x}")).collect(); let hash = keccak256(lower.as_bytes()); let mut out = String::with_capacity(42); out.push_str("0x"); for (ix, c) in lower.chars().enumerate() { let nibble = if ix % 2 == 0 { hash[ix / 2] >> 4 } else { hash[ix / 2] & 0x0f }; out.push(if nibble >= 8 { c.to_ascii_uppercase() } else { c }); } out } /// `0x1234…abcd`, for display only. Copy, compare and send the full address. pub fn short(&self) -> String { truncate_middle(&self.checksummed(), 6, 4) } } impl fmt::Display for Address { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.checksummed()) } } /// Whether `input` is spelled exactly as its EIP-55 checksum. pub fn is_checksummed(input: &str) -> bool { Address::parse(input).is_ok_and(|address| address.checksummed() == input) } /// Keeps `head` leading and `tail` trailing characters around an ellipsis: `0x1234…abcd` for an /// address, `0xab12…9f3c` for a transaction hash. Display only. pub fn truncate_middle(text: &str, head: usize, tail: usize) -> String { let chars: Vec<char> = text.chars().collect(); if chars.len() <= head + tail + 1 { return text.to_string(); } let start: String = chars[..head].iter().collect(); let end: String = chars[chars.len() - tail..].iter().collect(); format!("{start}\u{2026}{end}") } fn hex_value(byte: u8) -> Option<u8> { match byte { b'0'..=b'9' => Some(byte - b'0'), b'a'..=b'f' => Some(byte - b'a' + 10), b'A'..=b'F' => Some(byte - b'A' + 10), _ => None, } } // --------------------------------------------------------------------------------------------- // Amounts // --------------------------------------------------------------------------------------------- #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AmountError { /// Nothing to parse, or only a dot. Empty, /// Anything other than digits and one dot: signs, exponents, separators, spaces. Invalid, /// More fraction digits than the token has decimals. Never rounded away. TooManyDecimals { max: u8 }, /// Too large for a `u128` of base units. Overflow, } impl fmt::Display for AmountError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Empty => f.write_str("Enter an amount."), Self::Invalid => f.write_str("Use digits and one decimal point."), Self::TooManyDecimals { max } => write!(f, "At most {max} decimal places."), Self::Overflow => f.write_str("Amount is too large."), } } } /// `10^decimals`, or `None` past [`MAX_DECIMALS`]. pub fn pow10(decimals: u8) -> Option<u128> { 10u128.checked_pow(decimals as u32) } /// Parses a human amount such as `"1.5"` into base units: `parse_units("1.5", 6) == Ok(1_500_000)`. /// /// Accepts `".5"` (0.5) and `"1."` (1), the way people type. Rejects an empty string, a lone /// dot, signs, exponents, thousands separators and inner spaces. More fraction digits than /// `decimals` is an error, not a rounding. pub fn parse_units(input: &str, decimals: u8) -> Result<u128, AmountError> { let input = input.trim(); if decimals > MAX_DECIMALS { return Err(AmountError::Overflow); } let (whole, fraction) = match input.split_once('.') { Some((whole, fraction)) => (whole, fraction), None => (input, ""), }; if whole.is_empty() && fraction.is_empty() { return Err(AmountError::Empty); } let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit()); if !digits(whole) || !digits(fraction) { return Err(AmountError::Invalid); } if fraction.len() > decimals as usize { return Err(AmountError::TooManyDecimals { max: decimals }); } let scale = pow10(decimals).ok_or(AmountError::Overflow)?; let mut units: u128 = 0; for b in whole.bytes() { units = units .checked_mul(10) .and_then(|u| u.checked_add((b - b'0') as u128)) .ok_or(AmountError::Overflow)?; } units = units.checked_mul(scale).ok_or(AmountError::Overflow)?; let mut frac: u128 = 0; for b in fraction.bytes() { frac = frac * 10 + (b - b'0') as u128; } // `fraction` has at most `decimals` digits, so this power and product stay below `scale`. frac *= 10u128.pow((decimals as usize - fraction.len()) as u32); units.checked_add(frac).ok_or(AmountError::Overflow) } /// Every digit of `units` as a decimal string, trailing zeros trimmed: `format_units(1_500_000, 6)` /// is `"1.5"`. Use it to fill an input, such as the Max button, so the value round-trips exactly. pub fn format_units(units: u128, decimals: u8) -> String { let digits = units.to_string(); let decimals = decimals as usize; if decimals == 0 { return digits; } let padded = format!("{digits:0>width$}", width = decimals + 1); let (whole, fraction) = padded.split_at(padded.len() - decimals); let fraction = fraction.trim_end_matches('0'); if fraction.is_empty() { whole.to_string() } else { format!("{whole}.{fraction}") } } /// A balance for display: at most `max_fraction` digits, rounded *down* so it never reads larger /// than it is, with thousands separators. A non-zero value that rounds to zero shows as /// `<0.0001` rather than a misleading `0`. pub fn format_amount(units: u128, decimals: u8, max_fraction: u8) -> String { let full = format_units(units, decimals); let (whole, fraction) = full.split_once('.').unwrap_or((&full, "")); let kept: String = fraction.chars().take(max_fraction as usize).collect(); let kept = kept.trim_end_matches('0'); if units > 0 && whole == "0" && kept.is_empty() { return if max_fraction == 0 { "<1".to_string() } else { format!("<0.{}1", "0".repeat(max_fraction as usize - 1)) }; } let whole = group_thousands(whole); if kept.is_empty() { whole } else { format!("{whole}.{kept}") } } /// A USD value held as cents: `$1,234.56`. pub fn format_usd_cents(cents: u128) -> String { format!("${}.{:02}", group_thousands(&(cents / 100).to_string()), cents % 100) } /// Basis points as a percentage with two decimals: `50` is `"0.50%"`. pub fn format_bps(bps: u128) -> String { format!("{}.{:02}%", group_thousands(&(bps / 100).to_string()), bps % 100) } fn group_thousands(digits: &str) -> String { let mut out = String::with_capacity(digits.len() + digits.len() / 3); for (ix, c) in digits.chars().enumerate() { if ix > 0 && (digits.len() - ix) % 3 == 0 { out.push(','); } out.push(c); } out } // --------------------------------------------------------------------------------------------- // Integer math // --------------------------------------------------------------------------------------------- /// `a * b / denominator`, rounded down, with a 256-bit intermediate so the product can't /// overflow. `None` when `denominator` is zero or the result doesn't fit a `u128`. pub fn mul_div(a: u128, b: u128, denominator: u128) -> Option<u128> { if denominator == 0 { return None; } if let Some(product) = a.checked_mul(b) { return Some(product / denominator); } let (hi, lo) = mul_wide(a, b); if hi >= denominator { return None; } // Shift-subtract long division of the 256-bit (hi, lo) by `denominator`. `rem` stays below // `denominator`, and the bit that falls off its top is kept in `carry`. let mut rem = hi; let mut quotient: u128 = 0; for bit in (0..128).rev() { let carry = rem >> 127; rem = rem << 1 | (lo >> bit) & 1; quotient <<= 1; if carry == 1 || rem >= denominator { rem = rem.wrapping_sub(denominator); quotient |= 1; } } Some(quotient) } /// `a * b / denominator`, rounded up: for amounts the user must hand over, so a rounding never /// works in their favor at the protocol's expense. pub fn mul_div_up(a: u128, b: u128, denominator: u128) -> Option<u128> { let down = mul_div(a, b, denominator)?; // Exact when the rounded-down quotient times the denominator gives back the full product. let exact = mul_wide(down, denominator) == mul_wide(a, b); if exact { Some(down) } else { down.checked_add(1) } } /// The full 256-bit product of two `u128`s as (high, low) halves. fn mul_wide(a: u128, b: u128) -> (u128, u128) { const MASK: u128 = u64::MAX as u128; let (a_hi, a_lo) = (a >> 64, a & MASK); let (b_hi, b_lo) = (b >> 64, b & MASK); let lo_lo = a_lo * b_lo; let hi_lo = a_hi * b_lo; let lo_hi = a_lo * b_hi; let hi_hi = a_hi * b_hi; let cross = (lo_lo >> 64) + (hi_lo & MASK) + (lo_hi & MASK); let lo = (cross << 64) | (lo_lo & MASK); let hi = hi_hi + (hi_lo >> 64) + (lo_hi >> 64) + (cross >> 64); (hi, lo) } /// What `amount` of a token is worth in USD cents, given its price in USD with 8 decimals (the /// way most price feeds report it). Rounded down. pub fn usd_cents(amount: u128, decimals: u8, price_e8: u128) -> Option<u128> { // amount / 10^decimals * price / 10^8 * 100 = amount * price / 10^(decimals + 6) let scale = pow10(decimals.checked_add(6)?)?; mul_div(amount, price_e8, scale) } /// Converts `amount` of one token into another at their USD prices (8 decimals each), rounded /// down. A quote for display; the router's own quote is the one to sign. pub fn convert(amount: u128, from_decimals: u8, from_price_e8: u128, to_decimals: u8, to_price_e8: u128) -> Option<u128> { // Scale before dividing, so a token with more decimals keeps its precision. if to_decimals >= from_decimals { mul_div(amount, from_price_e8.checked_mul(pow10(to_decimals - from_decimals)?)?, to_price_e8) } else { mul_div(amount, from_price_e8, to_price_e8.checked_mul(pow10(from_decimals - to_decimals)?)?) } } /// The least a swap may return once `slippage_bps` is allowed: `amount * (1 - slippage)`, /// rounded down, the usual convention. The floor can loosen the guard by at most one base unit. pub fn min_received(amount: u128, slippage_bps: u128) -> Option<u128> { mul_div(amount, BPS.checked_sub(slippage_bps)?, BPS) } /// The output of a constant-product pool (x * y = k) for `amount_in`, after a fee in bps. pub fn constant_product_out(amount_in: u128, reserve_in: u128, reserve_out: u128, fee_bps: u128) -> Option<u128> { let in_after_fee = mul_div(amount_in, BPS.checked_sub(fee_bps)?, BPS)?; let new_reserve_in = reserve_in.checked_add(in_after_fee)?; mul_div(reserve_out, in_after_fee, new_reserve_in) } /// How much worse a fill is than the pool's spot price, in bps: `1 - (out / in) / (reserve_out / /// reserve_in)`. Rounded up, so the warning is never understated. pub fn price_impact_bps(amount_in: u128, amount_out: u128, reserve_in: u128, reserve_out: u128) -> Option<u128> { if amount_in == 0 { return Some(0); } // Spot output for amount_in, then the shortfall of the real output against it. let spot_out = mul_div(amount_in, reserve_out, reserve_in)?; if spot_out == 0 || amount_out >= spot_out { return Some(0); } let shortfall = spot_out - amount_out; let impact = mul_div(shortfall, BPS, spot_out)?; let exact = mul_div(impact, spot_out, BPS)? == shortfall; Some(if exact { impact } else { impact + 1 }) } /// Shares minted for depositing `assets` into a vault holding `total_assets` against /// `total_shares`, rounded down as ERC-4626 requires. An empty vault mints 1:1. pub fn preview_deposit(assets: u128, total_assets: u128, total_shares: u128) -> Option<u128> { if total_shares == 0 || total_assets == 0 { return Some(assets); } mul_div(assets, total_shares, total_assets) } /// Shares burned to withdraw exactly `assets`, rounded up as ERC-4626 requires. pub fn preview_withdraw(assets: u128, total_assets: u128, total_shares: u128) -> Option<u128> { if total_shares == 0 || total_assets == 0 { return Some(assets); } mul_div_up(assets, total_shares, total_assets) } /// Assets returned for redeeming `shares`, rounded down. pub fn preview_redeem(shares: u128, total_assets: u128, total_shares: u128) -> Option<u128> { if total_shares == 0 { return Some(0); } mul_div(shares, total_assets, total_shares) } /// A lending position's health factor in bps (10_000 = 1.00): collateral weighted by its /// liquidation threshold, over debt. `None` when there is no debt: the position can't be /// liquidated, so show "No debt" rather than dividing by zero. pub fn health_factor_bps(collateral_cents: u128, liquidation_threshold_bps: u128, debt_cents: u128) -> Option<u128> { if debt_cents == 0 { return None; } mul_div(collateral_cents, liquidation_threshold_bps, debt_cents) } /// How close a health factor is to liquidation, for coloring a meter. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Health { /// No debt. Safe, /// 2.00 and above. Healthy, /// 1.10 to 2.00. Moderate, /// Below 1.10: close to liquidation. AtRisk, /// Below 1.00: can be liquidated now. Liquidatable, } pub fn health(health_factor_bps: Option<u128>) -> Health { match health_factor_bps { None => Health::Safe, Some(hf) if hf < BPS => Health::Liquidatable, Some(hf) if hf < 11_000 => Health::AtRisk, Some(hf) if hf < 20_000 => Health::Moderate, Some(_) => Health::Healthy, } } /// A health factor for display, two decimals rounded down: `18_550` is `"1.85"`. pub fn format_health_factor(health_factor_bps: Option<u128>) -> String { match health_factor_bps { None => "No debt".to_string(), Some(hf) => format!("{}.{:02}", group_thousands(&(hf / BPS).to_string()), hf % BPS / 100), } } #[cfg(test)] mod tests { use super::*; // Checksums below come from Foundry's `cast to-check-sum-address`, not from this code. const MIXED: &str = "0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD"; const DIGITS_THEN_LETTERS: &str = "0x0123456789abcDEF0123456789abCDef01234567"; const SAMPLE: &str = "0x00000000000000000000000000000000000A11cE"; #[test] fn keccak_matches_known_digests() { let hex = |bytes: [u8; 32]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>(); assert_eq!(hex(keccak256(b"")), "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"); assert_eq!(hex(keccak256(b"abc")), "4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"); } #[test] fn checksums_match_eip55() { for expected in [MIXED, DIGITS_THEN_LETTERS, SAMPLE, "0x000000000000000000000000000000000000c0DE"] { let address = Address::parse(&expected.to_lowercase()).unwrap(); assert_eq!(address.checksummed(), expected); assert!(is_checksummed(expected)); } // All digits: nothing to case, so the checksum is the input. assert!(is_checksummed("0x0000000000000000000000000000000000001006")); } #[test] fn rejects_bad_checksums() { // One letter's case flipped. let flipped = MIXED.replacen("ABcd", "aBcd", 1); assert_eq!(Address::parse(&flipped), Err(AddressError::BadChecksum)); assert!(!is_checksummed(&flipped)); let flipped = SAMPLE.replace("A11cE", "A11ce"); assert_eq!(Address::parse(&flipped), Err(AddressError::BadChecksum)); } #[test] fn accepts_unchecksummed_single_case() { let lower = MIXED.to_lowercase(); let upper = format!("0x{}", &MIXED[2..].to_uppercase()); assert_eq!(Address::parse(&lower).unwrap().to_string(), MIXED); assert_eq!(Address::parse(&upper).unwrap().to_string(), MIXED); // Valid addresses, but not spelled as their checksum. assert!(!is_checksummed(&lower)); } #[test] fn rejects_malformed_addresses() { assert_eq!(Address::parse("00000000000000000000000000000000000a11ce"), Err(AddressError::MissingPrefix)); assert_eq!(Address::parse("0x1234"), Err(AddressError::WrongLength)); assert_eq!(Address::parse(""), Err(AddressError::MissingPrefix)); assert_eq!(Address::parse("0x00000000000000000000000000000000000a11cg"), Err(AddressError::NotHex)); } #[test] fn truncates_for_display_only() { let address = Address::parse(SAMPLE).unwrap(); assert_eq!(address.short(), "0x0000\u{2026}11cE"); assert_eq!(address.to_string(), SAMPLE); assert_eq!(truncate_middle("0xabc", 6, 4), "0xabc"); } #[test] fn parses_units_at_6_8_and_18_decimals() { assert_eq!(parse_units("1.5", 6), Ok(1_500_000)); assert_eq!(parse_units("0.00000001", 8), Ok(1)); assert_eq!(parse_units("21000000", 8), Ok(2_100_000_000_000_000)); assert_eq!(parse_units("1", 18), Ok(1_000_000_000_000_000_000)); assert_eq!(parse_units("0.000000000000000001", 18), Ok(1)); assert_eq!(parse_units(" 2.25 ", 18), Ok(2_250_000_000_000_000_000)); } #[test] fn parses_zero() { assert_eq!(parse_units("0", 18), Ok(0)); assert_eq!(parse_units("0.0", 6), Ok(0)); assert_eq!(parse_units("000", 8), Ok(0)); } #[test] fn parses_leading_and_trailing_dot() { assert_eq!(parse_units(".5", 6), Ok(500_000)); assert_eq!(parse_units("1.", 6), Ok(1_000_000)); assert_eq!(parse_units(".", 6), Err(AmountError::Empty)); assert_eq!(parse_units("", 6), Err(AmountError::Empty)); } #[test] fn rejects_too_many_decimals() { assert_eq!(parse_units("1.0000001", 6), Err(AmountError::TooManyDecimals { max: 6 })); assert_eq!(parse_units("0.000000001", 8), Err(AmountError::TooManyDecimals { max: 8 })); assert_eq!(parse_units("1.5", 0), Err(AmountError::TooManyDecimals { max: 0 })); // Trailing zeros are still digits the token can't hold: rejected rather than trimmed. assert_eq!(parse_units("1.0000000", 6), Err(AmountError::TooManyDecimals { max: 6 })); } #[test] fn rejects_non_numbers() { for input in ["-1", "+1", "1e18", "1.2.3", "1,000", "1 000", "0x10", "abc", "1_000"] { assert_eq!(parse_units(input, 18), Err(AmountError::Invalid), "{input}"); } } #[test] fn handles_max_values() { let max = u128::MAX.to_string(); assert_eq!(parse_units(&max, 0), Ok(u128::MAX)); assert_eq!(parse_units("340282366920938463463374607431768211456", 0), Err(AmountError::Overflow)); // 1e21 tokens at 18 decimals is 1e39 base units: past u128. assert_eq!(parse_units("1000000000000000000000", 18), Err(AmountError::Overflow)); assert_eq!(parse_units("1", 39), Err(AmountError::Overflow)); // The largest amount round-trips through formatting. let text = format_units(u128::MAX, 18); assert_eq!(parse_units(&text, 18), Ok(u128::MAX)); } #[test] fn formats_units_exactly() { assert_eq!(format_units(0, 18), "0"); assert_eq!(format_units(1, 18), "0.000000000000000001"); assert_eq!(format_units(1_500_000, 6), "1.5"); assert_eq!(format_units(123_456_789, 8), "1.23456789"); assert_eq!(format_units(42, 0), "42"); for (units, decimals) in [(987_654_321_u128, 6), (1, 8), (10u128.pow(18), 18)] { assert_eq!(parse_units(&format_units(units, decimals), decimals), Ok(units)); } } #[test] fn display_rounds_down_and_groups() { // 1,234.5678 USDC shown with 2 digits: rounded down, never up. assert_eq!(format_amount(1_234_567_800, 6, 2), "1,234.56"); assert_eq!(format_amount(1_999_999, 6, 2), "1.99"); assert_eq!(format_amount(0, 18, 4), "0"); assert_eq!(format_amount(1, 18, 4), "<0.0001"); assert_eq!(format_amount(1_000_000_000, 6, 2), "1,000"); assert_eq!(format_usd_cents(123_456_789), "$1,234,567.89"); assert_eq!(format_bps(50), "0.50%"); assert_eq!(format_bps(12_345), "123.45%"); } #[test] fn mul_div_survives_wide_products() { assert_eq!(mul_div(6, 7, 3), Some(14)); assert_eq!(mul_div(1, 1, 0), None); assert_eq!(mul_div(u128::MAX, u128::MAX, u128::MAX), Some(u128::MAX)); assert_eq!(mul_div(u128::MAX, 2, 4), Some(u128::MAX / 2)); assert_eq!(mul_div(u128::MAX, 3, 2), None); // 1e27 base units at a 1e21 price: the product needs 160 bits. assert_eq!(mul_div(10u128.pow(27), 10u128.pow(21), 10u128.pow(30)), Some(10u128.pow(18))); } #[test] fn values_and_converts_across_decimals() { // 1.5 ETH at $3,000.00 is $4,500.00. assert_eq!(usd_cents(1_500_000_000_000_000_000, 18, 300_000_000_000), Some(450_000)); // 2.5 USDC at $1 is $2.50. assert_eq!(usd_cents(2_500_000, 6, 100_000_000), Some(250)); // 1 ETH at $3,000 into USDC at $1: 3,000 USDC (6 decimals). assert_eq!(convert(10u128.pow(18), 18, 300_000_000_000, 6, 100_000_000), Some(3_000_000_000)); // 3,000 USDC into WBTC at $60,000: 0.05 WBTC (8 decimals). assert_eq!(convert(3_000_000_000, 6, 100_000_000, 8, 6_000_000_000_000), Some(5_000_000)); } #[test] fn slippage_and_price_impact() { assert_eq!(min_received(1_000_000, 50), Some(995_000)); assert_eq!(min_received(1_000_000, 0), Some(1_000_000)); assert_eq!(min_received(1_000_000, BPS + 1), None); // 1% of a 1,000,000 / 1,000,000 pool with no fee: 9,900 out, ~1% impact. let out = constant_product_out(10_000, 1_000_000, 1_000_000, 0).unwrap(); assert_eq!(out, 9_900); assert_eq!(price_impact_bps(10_000, out, 1_000_000, 1_000_000), Some(100)); assert_eq!(price_impact_bps(0, 0, 1, 1), Some(0)); } #[test] fn vault_shares_round_down() { assert_eq!(preview_deposit(1_000, 0, 0), Some(1_000)); // 1,000 assets into a vault where 3 assets back 2 shares: 666.67 shares, rounded down. assert_eq!(preview_deposit(1_000, 3_000, 2_000), Some(666)); assert_eq!(preview_redeem(666, 3_000, 2_000), Some(999)); // Withdrawing 1,000 assets burns 666.67 shares: rounded up to 667. assert_eq!(preview_withdraw(1_000, 3_000, 2_000), Some(667)); assert_eq!(preview_withdraw(1_500, 3_000, 2_000), Some(1_000)); assert_eq!(mul_div_up(7, 1, 2), Some(4)); assert_eq!(mul_div_up(u128::MAX, u128::MAX, u128::MAX), Some(u128::MAX)); assert_eq!(mul_div_up(u128::MAX, 3, 4), Some(u128::MAX / 4 * 3 + 3)); } #[test] fn health_factor_in_bps() { // $10,000 collateral at an 80% threshold against $4,000 debt: 2.00. let hf = health_factor_bps(1_000_000, 8_000, 400_000); assert_eq!(hf, Some(20_000)); assert_eq!(health(hf), Health::Healthy); assert_eq!(format_health_factor(hf), "2.00"); assert_eq!(health_factor_bps(1_000_000, 8_000, 0), None); assert_eq!(health(None), Health::Safe); assert_eq!(format_health_factor(None), "No debt"); assert_eq!(health(Some(10_500)), Health::AtRisk); assert_eq!(health(Some(9_999)), Health::Liquidatable); assert_eq!(format_health_factor(Some(18_559)), "1.85"); } }Register the module
// src/ui/mod.rs pub mod onchain;
Usage
use crate::ui::onchain::*;API Reference
Address
A 20-byte account or contract address. Display prints it EIP-55 checksummed.
Address::parse(input: &str) -> Result<Self, AddressError>Parses 0x + 40 hex digits. All-lowercase and all-uppercase input carries no checksum and is accepted; mixed case must match EIP-55 exactly.
.checksummed() -> StringThe EIP-55 spelling: a hex letter is uppercase when the matching nibble of keccak256(lowercase hex) is 8 or more.
.short() -> String0x1234…abcd, for display only. Copy, compare and send the full address.
AddressError
AddressError::MissingPrefixMissing the 0x prefix.
AddressError::WrongLengthNot exactly 40 hex digits after 0x.
AddressError::NotHexA character that isn't a hex digit.
AddressError::BadChecksumMixed case that doesn't match the EIP-55 checksum: likely a typo.
AmountError
AmountError::EmptyNothing to parse, or only a dot.
AmountError::InvalidAnything other than digits and one dot: signs, exponents, separators, spaces.
AmountError::TooManyDecimalsMore fraction digits than the token has decimals. Never rounded away.
AmountError::OverflowToo large for a u128 of base units.
Health
How close a health factor is to liquidation, for coloring a meter.
Health::SafeNo debt.
Health::Healthy2.00 and above.
Health::Moderate1.10 to 2.00.
Health::AtRiskBelow 1.10: close to liquidation.
Health::LiquidatableBelow 1.00: can be liquidated now.