hyuskui

Address

An account shown as its name when it has one, the address truncated to 0x1234…abcd, and an identicon drawn from the address hash. Copy puts the full checksummed address on the clipboard.

Loading GPUI…
use std::{sync::Arc, time::Duration};

use gpui::{
    div, prelude::*, px, App, ClipboardItem, Context, ElementId, FontWeight, SharedString, Task, Window,
};

use crate::icons::{icon, CHECK, COPY};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::onchain::{keccak256, Address};
use crate::ui::tooltip::Tooltip;

const MONO: &str = "Geist Mono";
const COPIED_FOR: Duration = Duration::from_secs(2);

/// Sample accounts: fake addresses, valid EIP-55, that belong to no one.
const ACCOUNTS: [(&str, Option<&str>); 3] = [
    ("0x00000000000000000000000000000000000A11cE", Some("alice.eth")),
    ("0x0000000000000000000000000000000000000B0b", Some("bob.eth")),
    ("0x000000000000000000000000000000000000c0DE", None),
];

/// The address card list: each row is an [`AddressView`].
#[derive(Default)]
pub struct AddressPattern;

impl Render for AddressPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme();
        div()
            .w(px(360.0))
            .flex()
            .flex_col()
            .rounded(theme.radius * 1.5)
            .border_1()
            .border_color(theme.border)
            .bg(theme.card)
            .children(ACCOUNTS.iter().enumerate().filter_map(|(ix, (address, name))| {
                let address = Address::parse(address).ok()?;
                Some(
                    div()
                        .px_4()
                        .py_3()
                        .when(ix > 0, |this| this.border_t_1().border_color(theme.border))
                        .child(AddressView::new(("account", ix), address).name(*name)),
                )
            }))
            .child(
                div()
                    .px_4()
                    .py_2()
                    .border_t_1()
                    .border_color(theme.border)
                    .text_xs()
                    .text_color(theme.muted_foreground)
                    .child("Sample data. These addresses belong to no one."),
            )
    }
}

/// An account: identicon, name or truncated address, and a copy button.
#[derive(IntoElement)]
pub struct AddressView {
    id: ElementId,
    address: Address,
    name: Option<SharedString>,
}

impl AddressView {
    pub fn new(id: impl Into<ElementId>, address: Address) -> Self {
        Self { id: id.into(), address, name: None }
    }

    /// A name the host resolved for this address. The address still shows underneath.
    pub fn name(mut self, name: Option<impl Into<SharedString>>) -> Self {
        self.name = name.map(Into::into);
        self
    }
}

/// The copied check is a moment of feedback the app has no reason to own, so it lives here.
#[derive(Default)]
struct CopyState {
    copied: bool,
    reset: Option<Task<()>>,
}

impl RenderOnce for AddressView {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = window.use_keyed_state(self.id.clone(), cx, |_, _| CopyState::default());
        let copied = state.read(cx).copied;
        let theme = cx.theme();
        let full = self.address.to_string();
        let short = self.address.short();

        let title = self.name.clone().unwrap_or_else(|| short.clone().into());
        let child = |name: &'static str| ElementId::NamedChild(Arc::new(self.id.clone()), name.into());
        let copy = Button::new(child("copy"), "")
            .variant(ButtonVariant::Ghost)
            .size(ButtonSize::Sm)
            .icon_only()
            .leading(icon(if copied { CHECK } else { COPY }).size(px(14.0)).text_color(theme.muted_foreground))
            .on_click({
                let full = full.clone();
                move |_, _, cx| {
                    // Always the full checksummed address: a truncated one can't be pasted anywhere.
                    cx.write_to_clipboard(ClipboardItem::new_string(full.clone()));
                    state.update(cx, |state, cx| {
                        state.copied = true;
                        cx.notify();
                        state.reset = Some(cx.spawn(async move |this, cx| {
                            cx.background_executor().timer(COPIED_FOR).await;
                            this.update(cx, |state, cx| {
                                state.copied = false;
                                cx.notify();
                            })
                            .ok();
                        }));
                    });
                }
            });

        div()
            .flex()
            .items_center()
            .gap_3()
            .child(identicon(&self.address, px(36.0), cx))
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .flex()
                    .flex_col()
                    .child(
                        div()
                            .text_sm()
                            .font_weight(FontWeight::MEDIUM)
                            .truncate()
                            .when(self.name.is_none(), |this| this.font_family(MONO))
                            .child(title),
                    )
                    .child(
                        Tooltip::new(child("full"), full).trigger(
                            div()
                                .text_xs()
                                .when(self.name.is_some(), |this| this.font_family(MONO))
                                .text_color(theme.muted_foreground)
                                .child(if self.name.is_some() { short } else { "No name".into() }),
                        ),
                    ),
            )
            .child(Tooltip::new(child("copy-tip"), if copied { "Copied" } else { "Copy address" }).trigger(copy))
    }
}

/// A 5x5 mirrored grid from the address hash, in theme colors, so the same account always has
/// the same face and lookalike addresses look different.
fn identicon(address: &Address, size: gpui::Pixels, cx: &App) -> impl IntoElement {
    let theme = cx.theme();
    let hash = keccak256(&address.0);
    let cell = size / 5.0;
    div()
        .flex_none()
        .size(size)
        .rounded(theme.radius)
        .overflow_hidden()
        .bg(theme.muted)
        .flex()
        .flex_col()
        .children((0..5).map(|row| {
            div().flex().children((0..5).map(move |col| {
                // Columns 3 and 4 mirror 1 and 0.
                let source = if col > 2 { 4 - col } else { col };
                let on = hash[row * 3 + source] & 1 == 1;
                div().size(cell).when(on, |this| this.bg(theme.foreground.opacity(0.8)))
            }))
        }))
}

Installation

  1. Add the components

    $ cargo hyuskui add button onchain tooltip icons

    Uses Button, Onchain and Tooltip.

  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/address.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/address.rs
    use std::{sync::Arc, time::Duration};
    
    use gpui::{
        div, prelude::*, px, App, ClipboardItem, Context, ElementId, FontWeight, SharedString, Task, Window,
    };
    
    use crate::icons::{icon, CHECK, COPY};
    use crate::theme::ActiveTheme;
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::onchain::{keccak256, Address};
    use crate::ui::tooltip::Tooltip;
    
    const MONO: &str = "Geist Mono";
    const COPIED_FOR: Duration = Duration::from_secs(2);
    
    /// Sample accounts: fake addresses, valid EIP-55, that belong to no one.
    const ACCOUNTS: [(&str, Option<&str>); 3] = [
        ("0x00000000000000000000000000000000000A11cE", Some("alice.eth")),
        ("0x0000000000000000000000000000000000000B0b", Some("bob.eth")),
        ("0x000000000000000000000000000000000000c0DE", None),
    ];
    
    /// The address card list: each row is an [`AddressView`].
    #[derive(Default)]
    pub struct AddressPattern;
    
    impl Render for AddressPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme();
            div()
                .w(px(360.0))
                .flex()
                .flex_col()
                .rounded(theme.radius * 1.5)
                .border_1()
                .border_color(theme.border)
                .bg(theme.card)
                .children(ACCOUNTS.iter().enumerate().filter_map(|(ix, (address, name))| {
                    let address = Address::parse(address).ok()?;
                    Some(
                        div()
                            .px_4()
                            .py_3()
                            .when(ix > 0, |this| this.border_t_1().border_color(theme.border))
                            .child(AddressView::new(("account", ix), address).name(*name)),
                    )
                }))
                .child(
                    div()
                        .px_4()
                        .py_2()
                        .border_t_1()
                        .border_color(theme.border)
                        .text_xs()
                        .text_color(theme.muted_foreground)
                        .child("Sample data. These addresses belong to no one."),
                )
        }
    }
    
    /// An account: identicon, name or truncated address, and a copy button.
    #[derive(IntoElement)]
    pub struct AddressView {
        id: ElementId,
        address: Address,
        name: Option<SharedString>,
    }
    
    impl AddressView {
        pub fn new(id: impl Into<ElementId>, address: Address) -> Self {
            Self { id: id.into(), address, name: None }
        }
    
        /// A name the host resolved for this address. The address still shows underneath.
        pub fn name(mut self, name: Option<impl Into<SharedString>>) -> Self {
            self.name = name.map(Into::into);
            self
        }
    }
    
    /// The copied check is a moment of feedback the app has no reason to own, so it lives here.
    #[derive(Default)]
    struct CopyState {
        copied: bool,
        reset: Option<Task<()>>,
    }
    
    impl RenderOnce for AddressView {
        fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
            let state = window.use_keyed_state(self.id.clone(), cx, |_, _| CopyState::default());
            let copied = state.read(cx).copied;
            let theme = cx.theme();
            let full = self.address.to_string();
            let short = self.address.short();
    
            let title = self.name.clone().unwrap_or_else(|| short.clone().into());
            let child = |name: &'static str| ElementId::NamedChild(Arc::new(self.id.clone()), name.into());
            let copy = Button::new(child("copy"), "")
                .variant(ButtonVariant::Ghost)
                .size(ButtonSize::Sm)
                .icon_only()
                .leading(icon(if copied { CHECK } else { COPY }).size(px(14.0)).text_color(theme.muted_foreground))
                .on_click({
                    let full = full.clone();
                    move |_, _, cx| {
                        // Always the full checksummed address: a truncated one can't be pasted anywhere.
                        cx.write_to_clipboard(ClipboardItem::new_string(full.clone()));
                        state.update(cx, |state, cx| {
                            state.copied = true;
                            cx.notify();
                            state.reset = Some(cx.spawn(async move |this, cx| {
                                cx.background_executor().timer(COPIED_FOR).await;
                                this.update(cx, |state, cx| {
                                    state.copied = false;
                                    cx.notify();
                                })
                                .ok();
                            }));
                        });
                    }
                });
    
            div()
                .flex()
                .items_center()
                .gap_3()
                .child(identicon(&self.address, px(36.0), cx))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .child(
                            div()
                                .text_sm()
                                .font_weight(FontWeight::MEDIUM)
                                .truncate()
                                .when(self.name.is_none(), |this| this.font_family(MONO))
                                .child(title),
                        )
                        .child(
                            Tooltip::new(child("full"), full).trigger(
                                div()
                                    .text_xs()
                                    .when(self.name.is_some(), |this| this.font_family(MONO))
                                    .text_color(theme.muted_foreground)
                                    .child(if self.name.is_some() { short } else { "No name".into() }),
                            ),
                        ),
                )
                .child(Tooltip::new(child("copy-tip"), if copied { "Copied" } else { "Copy address" }).trigger(copy))
        }
    }
    
    /// A 5x5 mirrored grid from the address hash, in theme colors, so the same account always has
    /// the same face and lookalike addresses look different.
    fn identicon(address: &Address, size: gpui::Pixels, cx: &App) -> impl IntoElement {
        let theme = cx.theme();
        let hash = keccak256(&address.0);
        let cell = size / 5.0;
        div()
            .flex_none()
            .size(size)
            .rounded(theme.radius)
            .overflow_hidden()
            .bg(theme.muted)
            .flex()
            .flex_col()
            .children((0..5).map(|row| {
                div().flex().children((0..5).map(move |col| {
                    // Columns 3 and 4 mirror 1 and 0.
                    let source = if col > 2 { 4 - col } else { col };
                    let on = hash[row * 3 + source] & 1 == 1;
                    div().size(cell).when(on, |this| this.bg(theme.foreground.opacity(0.8)))
                }))
            }))
    }