hyuskui

Token Picker

A token button that opens a searchable dialog: common tokens as chips, then every token with its balance. Search matches symbol and name; a pasted address is checked against its EIP-55 checksum before it is offered as an unlisted token.

Loading GPUI…
use gpui::{div, prelude::*, px, AnyElement, Context, Focusable, FontWeight, SharedString, Window};

use crate::icons::{icon, CHEVRON_DOWN, SEARCH, TRIANGLE_ALERT};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::badge::{Badge, BadgeVariant};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dialog::Dialog;
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
use crate::ui::onchain::{format_amount, Address, AddressError};
use crate::ui::popover::focus_when_mounted;
use crate::ui::scroll_area::ScrollArea;

pub struct TokenInfo {
    pub symbol: &'static str,
    pub name: &'static str,
    pub decimals: u8,
    /// Sample balance in base units.
    pub balance: u128,
    /// A fake, EIP-55-valid address that belongs to no contract.
    pub address: &'static str,
}

/// Sample token list. Symbols and decimals are the real ones; addresses and balances are not.
pub const TOKENS: [TokenInfo; 6] = [
    TokenInfo { symbol: "ETH", name: "Ether", decimals: 18, balance: 1_234_567_890_123_456_789, address: "0x0000000000000000000000000000000000001001" },
    TokenInfo { symbol: "USDC", name: "USD Coin", decimals: 6, balance: 2_500_120_000, address: "0x0000000000000000000000000000000000001006" },
    TokenInfo { symbol: "WBTC", name: "Wrapped Bitcoin", decimals: 8, balance: 4_210_337, address: "0x0000000000000000000000000000000000001008" },
    TokenInfo { symbol: "DAI", name: "Dai Stablecoin", decimals: 18, balance: 820_500_000_000_000_000_000, address: "0x0000000000000000000000000000000000001018" },
    TokenInfo { symbol: "SMPL", name: "Sample Governance", decimals: 18, balance: 0, address: "0x00000000000000000000000000000000000fA017" },
    TokenInfo { symbol: "stSMPL", name: "Sample Staked Ether", decimals: 18, balance: 500_000_000_000_000_000, address: "0x00000000000000000000000000000000000CA5E1" },
];

/// Shown as quick picks above the list.
const COMMON: [usize; 4] = [0, 1, 2, 3];

#[derive(Default)]
pub struct TokenPickerPattern {
    selected: usize,
    open: bool,
}

impl TokenPickerPattern {
    fn pick(&mut self, ix: usize, cx: &mut Context<Self>) {
        self.selected = ix;
        self.open = false;
        cx.notify();
    }
}

impl Render for TokenPickerPattern {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let search = window.use_keyed_state("token-search", cx, |_, cx| {
            TextInput::new(cx).placeholder("Search name or paste address").bare()
        });
        let theme = cx.theme().clone();
        let query = search.read(cx).text().trim().to_string();
        let selected = self.selected;

        let chips = COMMON.iter().map(|&ix| {
            let token = &TOKENS[ix];
            div()
                .id(("common", ix))
                .flex()
                .items_center()
                .gap_1p5()
                .pl_1()
                .pr_2p5()
                .py_1()
                .rounded_full()
                .border_1()
                .border_color(theme.border)
                .text_sm()
                .font_weight(FontWeight::MEDIUM)
                .cursor_pointer()
                .when(ix == selected, |this| this.bg(theme.accent))
                .hover(|style| style.bg(theme.accent))
                .on_click(cx.listener(move |this, _, _, cx| this.pick(ix, cx)))
                .child(token_icon(token.symbol, px(20.0)))
                .child(token.symbol)
        });

        let needle = query.to_lowercase();
        let matches: Vec<usize> = (0..TOKENS.len())
            .filter(|&ix| {
                let token = &TOKENS[ix];
                needle.is_empty()
                    || token.symbol.to_lowercase().contains(&needle)
                    || token.name.to_lowercase().contains(&needle)
                    || token.address.to_lowercase() == needle
            })
            .collect();

        // A pasted address that isn't in the list: offer it only if it parses, and say why not.
        let unlisted: Option<AnyElement> = (query.starts_with("0x") && matches.is_empty()).then(|| {
            match Address::parse(&query) {
                Ok(address) => div()
                    .flex()
                    .items_center()
                    .gap_3()
                    .p_3()
                    .rounded(theme.radius)
                    .border_1()
                    .border_color(theme.border)
                    .child(icon(TRIANGLE_ALERT).size(px(16.0)).text_color(theme.muted_foreground))
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .flex()
                            .flex_col()
                            .child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Unlisted token"))
                            .child(
                                div()
                                    .text_xs()
                                    .font_family("Geist Mono")
                                    .text_color(theme.muted_foreground)
                                    .child(address.to_string()),
                            ),
                    )
                    .child(Badge::new("Not verified").variant(BadgeVariant::Outline))
                    .into_any_element(),
                Err(error) => div()
                    .p_3()
                    .text_sm()
                    .text_color(theme.destructive)
                    .child(match error {
                        AddressError::BadChecksum => SharedString::from(error.to_string()),
                        _ => SharedString::from(format!("Not an address. {error}")),
                    })
                    .into_any_element(),
            }
        });

        let rows = matches.iter().map(|&ix| {
            let token = &TOKENS[ix];
            div()
                .id(("token", ix))
                .flex()
                .items_center()
                .gap_3()
                .px_2()
                .py_2()
                .rounded(theme.radius)
                .cursor_pointer()
                .when(ix == selected, |this| this.bg(theme.accent))
                .hover(|style| style.bg(theme.accent))
                .on_click(cx.listener(move |this, _, _, cx| this.pick(ix, cx)))
                .child(token_icon(token.symbol, px(32.0)))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(token.symbol))
                        .child(div().text_xs().text_color(theme.muted_foreground).truncate().child(token.name)),
                )
                .child(
                    div()
                        .text_sm()
                        .text_color(if token.balance == 0 { theme.muted_foreground } else { theme.foreground })
                        .child(format_amount(token.balance, token.decimals, 4)),
                )
        });
        let empty = matches.is_empty() && unlisted.is_none();

        let token = &TOKENS[selected];
        let trigger = Button::new("token-trigger", token.symbol)
            .variant(ButtonVariant::Outline)
            .rounded_full()
            .leading(token_icon(token.symbol, px(20.0)))
            .trailing(icon(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground));

        let focus = search.read(cx).focus_handle(cx);
        let balance = format!("Balance {} {}", format_amount(token.balance, token.decimals, 4), token.symbol);
        let dialog = Dialog::new("token-picker", self.open)
            .trigger(trigger)
            .title("Select a token")
            .on_open_change(cx.listener(move |this, open: &bool, window, cx| {
                this.open = *open;
                if *open {
                    focus_when_mounted(focus.clone(), window);
                }
                cx.notify();
            }))
            .child(
                InputGroup::new(search.clone())
                    .leading(icon(SEARCH).size(px(16.0)).text_color(theme.muted_foreground)),
            )
            .child(div().flex().flex_wrap().gap_2().children(chips))
            .child(div().h_px().bg(theme.border))
            .child(
                ScrollArea::new("token-list").h(px(240.0)).child(
                    // Right padding keeps rows clear of the overlay scrollbar.
                    div()
                        .flex()
                        .flex_col()
                        .gap_0p5()
                        .pr_3()
                        .children(rows)
                        .children(unlisted)
                        .when(empty, |this| {
                            this.child(
                                div()
                                    .py_8()
                                    .text_center()
                                    .text_sm()
                                    .text_color(theme.muted_foreground)
                                    .child("No tokens found."),
                            )
                        }),
                ),
            )
            .child(div().text_xs().text_color(theme.muted_foreground).child("Sample token list and balances."));

        div()
            .flex()
            .flex_col()
            .items_center()
            .gap_2()
            .child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Pay with"))
            .child(dialog)
            .child(div().text_xs().text_color(theme.muted_foreground).child(balance))
    }
}

/// A token's stand-in logo: its first letter on a round, muted tile.
pub fn token_icon(symbol: &str, size: gpui::Pixels) -> Avatar {
    Avatar::new(SharedString::from(symbol.chars().next().map(String::from).unwrap_or_default()))
        .size(AvatarSize::Custom(size))
}

Installation

  1. Add the components

    $ cargo hyuskui add avatar badge button dialog input input-group onchain popover scroll-area icons

    Uses Avatar, Badge, Button, Dialog, Input, Input Group, Onchain, Popover and Scroll Area.

  2. Add the crates

    $ cargo add sha3@0.10

    onchain.rs hashes addresses with Keccak-256 for their EIP-55 checksum. cargo hyuskui add runs this for you; you need it only when copying the files by hand.

  3. Copy the pattern

    Paste the code into src/crypto/token_picker.rs and 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_picker.rs
    use gpui::{div, prelude::*, px, AnyElement, Context, Focusable, FontWeight, SharedString, Window};
    
    use crate::icons::{icon, CHEVRON_DOWN, SEARCH, TRIANGLE_ALERT};
    use crate::theme::ActiveTheme;
    use crate::ui::avatar::{Avatar, AvatarSize};
    use crate::ui::badge::{Badge, BadgeVariant};
    use crate::ui::button::{Button, ButtonVariant};
    use crate::ui::dialog::Dialog;
    use crate::ui::input::TextInput;
    use crate::ui::input_group::InputGroup;
    use crate::ui::onchain::{format_amount, Address, AddressError};
    use crate::ui::popover::focus_when_mounted;
    use crate::ui::scroll_area::ScrollArea;
    
    pub struct TokenInfo {
        pub symbol: &'static str,
        pub name: &'static str,
        pub decimals: u8,
        /// Sample balance in base units.
        pub balance: u128,
        /// A fake, EIP-55-valid address that belongs to no contract.
        pub address: &'static str,
    }
    
    /// Sample token list. Symbols and decimals are the real ones; addresses and balances are not.
    pub const TOKENS: [TokenInfo; 6] = [
        TokenInfo { symbol: "ETH", name: "Ether", decimals: 18, balance: 1_234_567_890_123_456_789, address: "0x0000000000000000000000000000000000001001" },
        TokenInfo { symbol: "USDC", name: "USD Coin", decimals: 6, balance: 2_500_120_000, address: "0x0000000000000000000000000000000000001006" },
        TokenInfo { symbol: "WBTC", name: "Wrapped Bitcoin", decimals: 8, balance: 4_210_337, address: "0x0000000000000000000000000000000000001008" },
        TokenInfo { symbol: "DAI", name: "Dai Stablecoin", decimals: 18, balance: 820_500_000_000_000_000_000, address: "0x0000000000000000000000000000000000001018" },
        TokenInfo { symbol: "SMPL", name: "Sample Governance", decimals: 18, balance: 0, address: "0x00000000000000000000000000000000000fA017" },
        TokenInfo { symbol: "stSMPL", name: "Sample Staked Ether", decimals: 18, balance: 500_000_000_000_000_000, address: "0x00000000000000000000000000000000000CA5E1" },
    ];
    
    /// Shown as quick picks above the list.
    const COMMON: [usize; 4] = [0, 1, 2, 3];
    
    #[derive(Default)]
    pub struct TokenPickerPattern {
        selected: usize,
        open: bool,
    }
    
    impl TokenPickerPattern {
        fn pick(&mut self, ix: usize, cx: &mut Context<Self>) {
            self.selected = ix;
            self.open = false;
            cx.notify();
        }
    }
    
    impl Render for TokenPickerPattern {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let search = window.use_keyed_state("token-search", cx, |_, cx| {
                TextInput::new(cx).placeholder("Search name or paste address").bare()
            });
            let theme = cx.theme().clone();
            let query = search.read(cx).text().trim().to_string();
            let selected = self.selected;
    
            let chips = COMMON.iter().map(|&ix| {
                let token = &TOKENS[ix];
                div()
                    .id(("common", ix))
                    .flex()
                    .items_center()
                    .gap_1p5()
                    .pl_1()
                    .pr_2p5()
                    .py_1()
                    .rounded_full()
                    .border_1()
                    .border_color(theme.border)
                    .text_sm()
                    .font_weight(FontWeight::MEDIUM)
                    .cursor_pointer()
                    .when(ix == selected, |this| this.bg(theme.accent))
                    .hover(|style| style.bg(theme.accent))
                    .on_click(cx.listener(move |this, _, _, cx| this.pick(ix, cx)))
                    .child(token_icon(token.symbol, px(20.0)))
                    .child(token.symbol)
            });
    
            let needle = query.to_lowercase();
            let matches: Vec<usize> = (0..TOKENS.len())
                .filter(|&ix| {
                    let token = &TOKENS[ix];
                    needle.is_empty()
                        || token.symbol.to_lowercase().contains(&needle)
                        || token.name.to_lowercase().contains(&needle)
                        || token.address.to_lowercase() == needle
                })
                .collect();
    
            // A pasted address that isn't in the list: offer it only if it parses, and say why not.
            let unlisted: Option<AnyElement> = (query.starts_with("0x") && matches.is_empty()).then(|| {
                match Address::parse(&query) {
                    Ok(address) => div()
                        .flex()
                        .items_center()
                        .gap_3()
                        .p_3()
                        .rounded(theme.radius)
                        .border_1()
                        .border_color(theme.border)
                        .child(icon(TRIANGLE_ALERT).size(px(16.0)).text_color(theme.muted_foreground))
                        .child(
                            div()
                                .flex_1()
                                .min_w_0()
                                .flex()
                                .flex_col()
                                .child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Unlisted token"))
                                .child(
                                    div()
                                        .text_xs()
                                        .font_family("Geist Mono")
                                        .text_color(theme.muted_foreground)
                                        .child(address.to_string()),
                                ),
                        )
                        .child(Badge::new("Not verified").variant(BadgeVariant::Outline))
                        .into_any_element(),
                    Err(error) => div()
                        .p_3()
                        .text_sm()
                        .text_color(theme.destructive)
                        .child(match error {
                            AddressError::BadChecksum => SharedString::from(error.to_string()),
                            _ => SharedString::from(format!("Not an address. {error}")),
                        })
                        .into_any_element(),
                }
            });
    
            let rows = matches.iter().map(|&ix| {
                let token = &TOKENS[ix];
                div()
                    .id(("token", ix))
                    .flex()
                    .items_center()
                    .gap_3()
                    .px_2()
                    .py_2()
                    .rounded(theme.radius)
                    .cursor_pointer()
                    .when(ix == selected, |this| this.bg(theme.accent))
                    .hover(|style| style.bg(theme.accent))
                    .on_click(cx.listener(move |this, _, _, cx| this.pick(ix, cx)))
                    .child(token_icon(token.symbol, px(32.0)))
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .flex()
                            .flex_col()
                            .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(token.symbol))
                            .child(div().text_xs().text_color(theme.muted_foreground).truncate().child(token.name)),
                    )
                    .child(
                        div()
                            .text_sm()
                            .text_color(if token.balance == 0 { theme.muted_foreground } else { theme.foreground })
                            .child(format_amount(token.balance, token.decimals, 4)),
                    )
            });
            let empty = matches.is_empty() && unlisted.is_none();
    
            let token = &TOKENS[selected];
            let trigger = Button::new("token-trigger", token.symbol)
                .variant(ButtonVariant::Outline)
                .rounded_full()
                .leading(token_icon(token.symbol, px(20.0)))
                .trailing(icon(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground));
    
            let focus = search.read(cx).focus_handle(cx);
            let balance = format!("Balance {} {}", format_amount(token.balance, token.decimals, 4), token.symbol);
            let dialog = Dialog::new("token-picker", self.open)
                .trigger(trigger)
                .title("Select a token")
                .on_open_change(cx.listener(move |this, open: &bool, window, cx| {
                    this.open = *open;
                    if *open {
                        focus_when_mounted(focus.clone(), window);
                    }
                    cx.notify();
                }))
                .child(
                    InputGroup::new(search.clone())
                        .leading(icon(SEARCH).size(px(16.0)).text_color(theme.muted_foreground)),
                )
                .child(div().flex().flex_wrap().gap_2().children(chips))
                .child(div().h_px().bg(theme.border))
                .child(
                    ScrollArea::new("token-list").h(px(240.0)).child(
                        // Right padding keeps rows clear of the overlay scrollbar.
                        div()
                            .flex()
                            .flex_col()
                            .gap_0p5()
                            .pr_3()
                            .children(rows)
                            .children(unlisted)
                            .when(empty, |this| {
                                this.child(
                                    div()
                                        .py_8()
                                        .text_center()
                                        .text_sm()
                                        .text_color(theme.muted_foreground)
                                        .child("No tokens found."),
                                )
                            }),
                    ),
                )
                .child(div().text_xs().text_color(theme.muted_foreground).child("Sample token list and balances."));
    
            div()
                .flex()
                .flex_col()
                .items_center()
                .gap_2()
                .child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Pay with"))
                .child(dialog)
                .child(div().text_xs().text_color(theme.muted_foreground).child(balance))
        }
    }
    
    /// A token's stand-in logo: its first letter on a round, muted tile.
    pub fn token_icon(symbol: &str, size: gpui::Pixels) -> Avatar {
        Avatar::new(SharedString::from(symbol.chars().next().map(String::from).unwrap_or_default()))
            .size(AvatarSize::Custom(size))
    }