An amount field that knows its token's decimals: it rejects more fraction digits than the token has instead of rounding, Max fills the exact balance, and the hint shows the balance and the amount's value. Validation runs through Form.
Loading GPUI…
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{field, Form, FormExt, Mode, Schema};
use crate::ui::input_group::InputGroup;
use crate::ui::onchain::{format_amount, format_units, format_usd_cents, parse_units, usd_cents, AmountError};
use crate::ui::tabs::Tabs;
use crate::ui::toast::{toast, Toast, Toaster};
struct Token {
symbol: &'static str,
decimals: u8,
/// Sample USD price with 8 decimals.
price_e8: u128,
/// Sample balance in base units.
balance: u128,
}
/// Sample data with each token's real decimals.
const TOKENS: [Token; 3] = [
Token { symbol: "USDC", decimals: 6, price_e8: 100_000_000, balance: 2_500_120_000 },
Token { symbol: "WBTC", decimals: 8, price_e8: 6_000_000_000_000, balance: 4_210_337 },
Token { symbol: "ETH", decimals: 18, price_e8: 300_000_000_000, balance: 1_234_567_890_123_456_789 },
];
#[derive(Clone, Default, Debug, PartialEq)]
struct Transfer {
amount: String,
token: usize,
}
fn check(values: &Transfer) -> Result<u128, AmountError> {
parse_units(&values.amount, TOKENS[values.token].decimals)
}
/// One rule per way an amount can be wrong, in the order the user should fix them.
fn schema() -> Schema<Transfer> {
Schema::<Transfer>::new()
.refine("amount", |v| check(v) != Err(AmountError::Empty), "Enter an amount.")
.refine("amount", |v| check(v) != Err(AmountError::Invalid), "Use digits and one decimal point.")
.refine(
"amount",
|v| !matches!(check(v), Err(AmountError::TooManyDecimals { .. })),
"More decimal places than this token has.",
)
.refine("amount", |v| check(v) != Err(AmountError::Overflow), "Amount is too large.")
.refine("amount", |v| check(v) != Ok(0), "Enter an amount above zero.")
.refine("amount", |v| check(v).map_or(true, |units| units <= TOKENS[v.token].balance), "More than your balance.")
}
#[derive(Default)]
pub struct TokenAmountInputPattern;
impl Render for TokenAmountInputPattern {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let form = window.use_keyed_state("token-amount", cx, |_, _| {
Form::new(Transfer::default()).schema(schema()).mode(Mode::OnChange).on_success(|values, _, cx| {
let token = &TOKENS[values.token];
if let Ok(units) = check(values) {
// The host builds the transfer from `units`, never from the display string.
toast(
Toast::new(format!("Ready to send {} {}", format_units(units, token.decimals), token.symbol))
.description(format!("{units} base units")),
cx,
);
}
})
});
let input = form.input(field!(amount), window, cx, |input| input.placeholder("0.00").bare());
let theme = cx.theme().clone();
let f = form.read(cx);
let values = f.values().clone();
let token = &TOKENS[values.token];
let value = check(&values).ok().and_then(|units| usd_cents(units, token.decimals, token.price_e8));
let max = Button::new("max", "Max").variant(ButtonVariant::Secondary).size(ButtonSize::Xs).on_click({
let form = form.clone();
move |_, window, cx| {
let token = &TOKENS[form.read(cx).values().token];
// The exact balance, every digit, so the parsed amount equals it.
let amount = format_units(token.balance, token.decimals);
form.update(cx, |form, cx| form.set_value(&field!(amount), amount, window, cx));
}
});
let token_chip = div()
.flex()
.items_center()
.gap_1p5()
.pl_1()
.pr_2()
.py_0p5()
.rounded_full()
.border_1()
.border_color(theme.border)
.child(Avatar::new(&token.symbol[..1]).size(AvatarSize::Custom(px(20.0))))
.child(div().text_sm().font_weight(FontWeight::MEDIUM).text_color(theme.foreground).child(token.symbol));
let token_tabs = TOKENS.iter().fold(
Tabs::new("amount-token", values.token).on_select({
let form = form.clone();
move |ix: &usize, window, cx| {
let ix = *ix;
form.update(cx, |form, cx| {
form.set_value(&field!(token), ix, window, cx);
// The same text can be valid for one token and not another.
if !form.values().amount.is_empty() {
let _ = form.trigger("amount", cx);
}
});
}
}),
|tabs, token| tabs.tab(token.symbol),
);
div()
.w(px(400.0))
.child(
Card::new()
.title("Send")
.description("Sample balances. Decimals: USDC 6, WBTC 8, ETH 18.")
.child(
div()
.flex()
.flex_col()
.gap_3()
.child(token_tabs)
.child(
f.field("amount")
.label("Amount")
.child(InputGroup::new(input).trailing(max).trailing(token_chip)),
)
.child(
div()
.flex()
.justify_between()
.text_xs()
.text_color(theme.muted_foreground)
.child(format!(
"Balance {} {}",
format_amount(token.balance, token.decimals, 6),
token.symbol
))
.child(format!("\u{2248} {}", value.map_or("$0.00".into(), format_usd_cents))),
),
)
.footer(
div().w_full().child(
Button::new("send", "Continue").on_click(form.handle_submit()),
),
),
)
.child(Toaster::new())
}
}Installation
Add the components
$ cargo hyuskui add avatar button card form input-group onchain tabs toastUses Avatar, Button, Card, Form, Input Group, Onchain, Tabs and Toast.
Add the crates
$ cargo add sha3@0.10onchain.rshashes addresses with Keccak-256 for their EIP-55 checksum.cargo hyuskui addruns this for you; you need it only when copying the files by hand.Copy the pattern
Paste the code into
src/crypto/token_amount_input.rsand declare the module. The demo runs on sample data and fake addresses; feed it your wallet connection, balances and quotes, and send transactions from the handlers.src/crypto/token_amount_input.rs use gpui::{div, prelude::*, px, Context, FontWeight, Window}; use crate::theme::ActiveTheme; use crate::ui::avatar::{Avatar, AvatarSize}; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::card::Card; use crate::ui::form::{field, Form, FormExt, Mode, Schema}; use crate::ui::input_group::InputGroup; use crate::ui::onchain::{format_amount, format_units, format_usd_cents, parse_units, usd_cents, AmountError}; use crate::ui::tabs::Tabs; use crate::ui::toast::{toast, Toast, Toaster}; struct Token { symbol: &'static str, decimals: u8, /// Sample USD price with 8 decimals. price_e8: u128, /// Sample balance in base units. balance: u128, } /// Sample data with each token's real decimals. const TOKENS: [Token; 3] = [ Token { symbol: "USDC", decimals: 6, price_e8: 100_000_000, balance: 2_500_120_000 }, Token { symbol: "WBTC", decimals: 8, price_e8: 6_000_000_000_000, balance: 4_210_337 }, Token { symbol: "ETH", decimals: 18, price_e8: 300_000_000_000, balance: 1_234_567_890_123_456_789 }, ]; #[derive(Clone, Default, Debug, PartialEq)] struct Transfer { amount: String, token: usize, } fn check(values: &Transfer) -> Result<u128, AmountError> { parse_units(&values.amount, TOKENS[values.token].decimals) } /// One rule per way an amount can be wrong, in the order the user should fix them. fn schema() -> Schema<Transfer> { Schema::<Transfer>::new() .refine("amount", |v| check(v) != Err(AmountError::Empty), "Enter an amount.") .refine("amount", |v| check(v) != Err(AmountError::Invalid), "Use digits and one decimal point.") .refine( "amount", |v| !matches!(check(v), Err(AmountError::TooManyDecimals { .. })), "More decimal places than this token has.", ) .refine("amount", |v| check(v) != Err(AmountError::Overflow), "Amount is too large.") .refine("amount", |v| check(v) != Ok(0), "Enter an amount above zero.") .refine("amount", |v| check(v).map_or(true, |units| units <= TOKENS[v.token].balance), "More than your balance.") } #[derive(Default)] pub struct TokenAmountInputPattern; impl Render for TokenAmountInputPattern { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let form = window.use_keyed_state("token-amount", cx, |_, _| { Form::new(Transfer::default()).schema(schema()).mode(Mode::OnChange).on_success(|values, _, cx| { let token = &TOKENS[values.token]; if let Ok(units) = check(values) { // The host builds the transfer from `units`, never from the display string. toast( Toast::new(format!("Ready to send {} {}", format_units(units, token.decimals), token.symbol)) .description(format!("{units} base units")), cx, ); } }) }); let input = form.input(field!(amount), window, cx, |input| input.placeholder("0.00").bare()); let theme = cx.theme().clone(); let f = form.read(cx); let values = f.values().clone(); let token = &TOKENS[values.token]; let value = check(&values).ok().and_then(|units| usd_cents(units, token.decimals, token.price_e8)); let max = Button::new("max", "Max").variant(ButtonVariant::Secondary).size(ButtonSize::Xs).on_click({ let form = form.clone(); move |_, window, cx| { let token = &TOKENS[form.read(cx).values().token]; // The exact balance, every digit, so the parsed amount equals it. let amount = format_units(token.balance, token.decimals); form.update(cx, |form, cx| form.set_value(&field!(amount), amount, window, cx)); } }); let token_chip = div() .flex() .items_center() .gap_1p5() .pl_1() .pr_2() .py_0p5() .rounded_full() .border_1() .border_color(theme.border) .child(Avatar::new(&token.symbol[..1]).size(AvatarSize::Custom(px(20.0)))) .child(div().text_sm().font_weight(FontWeight::MEDIUM).text_color(theme.foreground).child(token.symbol)); let token_tabs = TOKENS.iter().fold( Tabs::new("amount-token", values.token).on_select({ let form = form.clone(); move |ix: &usize, window, cx| { let ix = *ix; form.update(cx, |form, cx| { form.set_value(&field!(token), ix, window, cx); // The same text can be valid for one token and not another. if !form.values().amount.is_empty() { let _ = form.trigger("amount", cx); } }); } }), |tabs, token| tabs.tab(token.symbol), ); div() .w(px(400.0)) .child( Card::new() .title("Send") .description("Sample balances. Decimals: USDC 6, WBTC 8, ETH 18.") .child( div() .flex() .flex_col() .gap_3() .child(token_tabs) .child( f.field("amount") .label("Amount") .child(InputGroup::new(input).trailing(max).trailing(token_chip)), ) .child( div() .flex() .justify_between() .text_xs() .text_color(theme.muted_foreground) .child(format!( "Balance {} {}", format_amount(token.balance, token.decimals, 6), token.symbol )) .child(format!("\u{2248} {}", value.map_or("$0.00".into(), format_usd_cents))), ), ) .footer( div().w_full().child( Button::new("send", "Continue").on_click(form.handle_submit()), ), ), ) .child(Toaster::new()) } }