hyuskui

Wallet Connect

A connect button that opens a wallet-choice dialog, waits while the wallet asks the user to approve, and then becomes an account menu with the truncated address and balance.

Loading GPUI…
use std::time::Duration;

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

use crate::icons::{icon, APP_WINDOW, CHEVRON_DOWN, CHEVRON_RIGHT, QR_CODE, USB, WALLET};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dialog::Dialog;
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::onchain::{format_amount, Address};
use crate::ui::spinner::{Spinner, SpinnerSize};
use crate::ui::toast::{toast, Toast, Toaster};

/// How long the demo pretends the wallet takes to approve. A real app waits on the wallet.
const APPROVAL: Duration = Duration::from_millis(1400);

/// Sample account: a fake address that belongs to no one, and 1.2345 ETH in wei.
const SAMPLE_ACCOUNT: &str = "0x00000000000000000000000000000000000A11cE";
const SAMPLE_BALANCE_WEI: u128 = 1_234_500_000_000_000_000;

struct WalletOption {
    name: &'static str,
    description: &'static str,
    icon: &'static [u8],
}

const WALLETS: [WalletOption; 3] = [
    WalletOption { name: "Browser wallet", description: "An extension in this browser", icon: APP_WINDOW },
    WalletOption { name: "WalletConnect-style QR", description: "Scan with a wallet on your phone", icon: QR_CODE },
    WalletOption { name: "Hardware wallet", description: "Plug in and unlock your device", icon: USB },
];

#[derive(Clone, Copy, Default, PartialEq)]
enum Connection {
    #[default]
    Disconnected,
    /// Waiting on the wallet at this index.
    Connecting(usize),
    Connected { wallet: usize },
}

#[derive(Default)]
pub struct WalletConnectPattern {
    connection: Connection,
    dialog_open: bool,
    menu_open: bool,
    pending: Option<Task<()>>,
}

impl WalletConnectPattern {
    /// The user picked a wallet. A real app asks that wallet to connect here and calls
    /// `connected` when it answers; the demo answers after a delay.
    fn connect(&mut self, wallet: usize, cx: &mut Context<Self>) {
        self.connection = Connection::Connecting(wallet);
        self.pending = Some(cx.spawn(async move |this, cx| {
            cx.background_executor().timer(APPROVAL).await;
            this.update(cx, |this, cx| this.connected(wallet, cx)).ok();
        }));
        cx.notify();
    }

    fn connected(&mut self, wallet: usize, cx: &mut Context<Self>) {
        self.connection = Connection::Connected { wallet };
        self.dialog_open = false;
        cx.notify();
    }

    /// Closing the dialog while waiting abandons the request.
    fn cancel(&mut self, cx: &mut Context<Self>) {
        self.pending = None;
        self.connection = Connection::Disconnected;
        self.dialog_open = false;
        cx.notify();
    }
}

impl Render for WalletConnectPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme().clone();
        let account = Address::parse(SAMPLE_ACCOUNT).ok();

        let trigger = match (self.connection, account) {
            (Connection::Connected { wallet }, Some(account)) => DropdownMenu::new("account-menu", self.menu_open)
                .width(px(280.0))
                .trigger(
                    Button::new("account", account.short())
                        .variant(ButtonVariant::Outline)
                        .leading(
                            div()
                                .size(px(8.0))
                                .rounded_full()
                                .bg(theme.foreground)
                                .opacity(0.8),
                        )
                        .trailing(icon(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground)),
                )
                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                    this.menu_open = *open;
                    cx.notify();
                }))
                .label(format!(
                    "{} ETH \u{00b7} {}",
                    format_amount(SAMPLE_BALANCE_WEI, 18, 4),
                    WALLETS[wallet].name
                ))
                .separator()
                .item(MenuItem::new("Copy address").on_select(move |_, _, cx| {
                    // Always the full checksummed address: a truncated one can't be pasted anywhere.
                    cx.write_to_clipboard(ClipboardItem::new_string(account.to_string()));
                }))
                .item(MenuItem::new("View on explorer").on_select(move |_, _, cx| open_explorer(account, cx)))
                .separator()
                .item(MenuItem::new("Disconnect").destructive(true).on_select(cx.listener(
                    |this, _: &ClickEvent, _, cx| {
                        this.connection = Connection::Disconnected;
                        cx.notify();
                    },
                )))
                .into_any_element(),
            _ => {
                let connecting = matches!(self.connection, Connection::Connecting(_));
                Button::new("connect", if connecting { "Connecting\u{2026}" } else { "Connect wallet" })
                    .disabled(connecting)
                    .leading(if connecting {
                        Spinner::new().size(SpinnerSize::Sm).color(theme.primary_foreground).into_any_element()
                    } else {
                        icon(WALLET).size(px(16.0)).text_color(theme.primary_foreground).into_any_element()
                    })
                    .on_click(cx.listener(|this, _, _, cx| {
                        this.dialog_open = true;
                        cx.notify();
                    }))
                    .into_any_element()
            }
        };

        let waiting = match self.connection {
            Connection::Connecting(ix) => Some(ix),
            _ => None,
        };
        let rows = WALLETS.iter().enumerate().map(|(ix, wallet)| {
            let busy = waiting == Some(ix);
            let other_busy = waiting.is_some() && !busy;
            div()
                .id(("wallet", ix))
                .flex()
                .items_center()
                .gap_3()
                .px_3()
                .py(px(10.0))
                .rounded(theme.radius)
                .border_1()
                .border_color(if busy { theme.ring } else { theme.border })
                .when(other_busy, |this| this.opacity(0.5).cursor_not_allowed())
                .when(waiting.is_none(), |this| {
                    this.cursor_pointer()
                        .hover(|style| style.bg(theme.accent))
                        .on_click(cx.listener(move |this, _, _, cx| this.connect(ix, cx)))
                })
                .child(
                    div()
                        .flex_none()
                        .size(px(36.0))
                        .rounded(theme.radius)
                        .bg(theme.muted)
                        .flex()
                        .items_center()
                        .justify_center()
                        .child(icon(wallet.icon).size(px(18.0)).text_color(theme.foreground)),
                )
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(wallet.name))
                        .child(div().text_xs().text_color(theme.muted_foreground).child(if busy {
                            "Approve the request in your wallet\u{2026}"
                        } else {
                            wallet.description
                        })),
                )
                .child(if busy {
                    Spinner::new().size(SpinnerSize::Sm).into_any_element()
                } else {
                    icon(CHEVRON_RIGHT).size(px(16.0)).text_color(theme.muted_foreground).into_any_element()
                })
        });

        let dialog = Dialog::new("wallets", self.dialog_open)
            .title("Connect a wallet")
            .description("Choose how to connect. You approve the connection in your wallet.")
            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                if *open {
                    this.dialog_open = true;
                    cx.notify();
                } else {
                    this.cancel(cx);
                }
            }))
            .child(div().flex().flex_col().gap_2().children(rows))
            .child(
                div()
                    .text_xs()
                    .text_color(theme.muted_foreground)
                    .child("Connecting shares your address. It never moves funds or reveals keys."),
            );

        div()
            .size_full()
            .flex()
            .flex_col()
            .items_center()
            .justify_center()
            .gap_3()
            .child(trigger)
            .child(div().text_xs().text_color(theme.muted_foreground).child(match self.connection {
                Connection::Disconnected => "Not connected",
                Connection::Connecting(_) => "Waiting for the wallet",
                Connection::Connected { .. } => "Connected \u{00b7} sample account",
            }))
            .child(dialog)
            .child(Toaster::new())
    }
}

/// The host opens its block explorer at the account. The demo has no explorer, so it says
/// which address it would open.
fn open_explorer(account: Address, cx: &mut App) {
    toast(Toast::new("Open in explorer").description(account.to_string()), cx);
}

Installation

  1. Add the components

    $ cargo hyuskui add button dialog dropdown-menu onchain spinner toast icons

    Uses Button, Dialog, Dropdown Menu, Onchain, Spinner and Toast.

  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/wallet_connect.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/wallet_connect.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, App, ClickEvent, ClipboardItem, Context, FontWeight, Task, Window};
    
    use crate::icons::{icon, APP_WINDOW, CHEVRON_DOWN, CHEVRON_RIGHT, QR_CODE, USB, WALLET};
    use crate::theme::ActiveTheme;
    use crate::ui::button::{Button, ButtonVariant};
    use crate::ui::dialog::Dialog;
    use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
    use crate::ui::onchain::{format_amount, Address};
    use crate::ui::spinner::{Spinner, SpinnerSize};
    use crate::ui::toast::{toast, Toast, Toaster};
    
    /// How long the demo pretends the wallet takes to approve. A real app waits on the wallet.
    const APPROVAL: Duration = Duration::from_millis(1400);
    
    /// Sample account: a fake address that belongs to no one, and 1.2345 ETH in wei.
    const SAMPLE_ACCOUNT: &str = "0x00000000000000000000000000000000000A11cE";
    const SAMPLE_BALANCE_WEI: u128 = 1_234_500_000_000_000_000;
    
    struct WalletOption {
        name: &'static str,
        description: &'static str,
        icon: &'static [u8],
    }
    
    const WALLETS: [WalletOption; 3] = [
        WalletOption { name: "Browser wallet", description: "An extension in this browser", icon: APP_WINDOW },
        WalletOption { name: "WalletConnect-style QR", description: "Scan with a wallet on your phone", icon: QR_CODE },
        WalletOption { name: "Hardware wallet", description: "Plug in and unlock your device", icon: USB },
    ];
    
    #[derive(Clone, Copy, Default, PartialEq)]
    enum Connection {
        #[default]
        Disconnected,
        /// Waiting on the wallet at this index.
        Connecting(usize),
        Connected { wallet: usize },
    }
    
    #[derive(Default)]
    pub struct WalletConnectPattern {
        connection: Connection,
        dialog_open: bool,
        menu_open: bool,
        pending: Option<Task<()>>,
    }
    
    impl WalletConnectPattern {
        /// The user picked a wallet. A real app asks that wallet to connect here and calls
        /// `connected` when it answers; the demo answers after a delay.
        fn connect(&mut self, wallet: usize, cx: &mut Context<Self>) {
            self.connection = Connection::Connecting(wallet);
            self.pending = Some(cx.spawn(async move |this, cx| {
                cx.background_executor().timer(APPROVAL).await;
                this.update(cx, |this, cx| this.connected(wallet, cx)).ok();
            }));
            cx.notify();
        }
    
        fn connected(&mut self, wallet: usize, cx: &mut Context<Self>) {
            self.connection = Connection::Connected { wallet };
            self.dialog_open = false;
            cx.notify();
        }
    
        /// Closing the dialog while waiting abandons the request.
        fn cancel(&mut self, cx: &mut Context<Self>) {
            self.pending = None;
            self.connection = Connection::Disconnected;
            self.dialog_open = false;
            cx.notify();
        }
    }
    
    impl Render for WalletConnectPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme().clone();
            let account = Address::parse(SAMPLE_ACCOUNT).ok();
    
            let trigger = match (self.connection, account) {
                (Connection::Connected { wallet }, Some(account)) => DropdownMenu::new("account-menu", self.menu_open)
                    .width(px(280.0))
                    .trigger(
                        Button::new("account", account.short())
                            .variant(ButtonVariant::Outline)
                            .leading(
                                div()
                                    .size(px(8.0))
                                    .rounded_full()
                                    .bg(theme.foreground)
                                    .opacity(0.8),
                            )
                            .trailing(icon(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground)),
                    )
                    .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                        this.menu_open = *open;
                        cx.notify();
                    }))
                    .label(format!(
                        "{} ETH \u{00b7} {}",
                        format_amount(SAMPLE_BALANCE_WEI, 18, 4),
                        WALLETS[wallet].name
                    ))
                    .separator()
                    .item(MenuItem::new("Copy address").on_select(move |_, _, cx| {
                        // Always the full checksummed address: a truncated one can't be pasted anywhere.
                        cx.write_to_clipboard(ClipboardItem::new_string(account.to_string()));
                    }))
                    .item(MenuItem::new("View on explorer").on_select(move |_, _, cx| open_explorer(account, cx)))
                    .separator()
                    .item(MenuItem::new("Disconnect").destructive(true).on_select(cx.listener(
                        |this, _: &ClickEvent, _, cx| {
                            this.connection = Connection::Disconnected;
                            cx.notify();
                        },
                    )))
                    .into_any_element(),
                _ => {
                    let connecting = matches!(self.connection, Connection::Connecting(_));
                    Button::new("connect", if connecting { "Connecting\u{2026}" } else { "Connect wallet" })
                        .disabled(connecting)
                        .leading(if connecting {
                            Spinner::new().size(SpinnerSize::Sm).color(theme.primary_foreground).into_any_element()
                        } else {
                            icon(WALLET).size(px(16.0)).text_color(theme.primary_foreground).into_any_element()
                        })
                        .on_click(cx.listener(|this, _, _, cx| {
                            this.dialog_open = true;
                            cx.notify();
                        }))
                        .into_any_element()
                }
            };
    
            let waiting = match self.connection {
                Connection::Connecting(ix) => Some(ix),
                _ => None,
            };
            let rows = WALLETS.iter().enumerate().map(|(ix, wallet)| {
                let busy = waiting == Some(ix);
                let other_busy = waiting.is_some() && !busy;
                div()
                    .id(("wallet", ix))
                    .flex()
                    .items_center()
                    .gap_3()
                    .px_3()
                    .py(px(10.0))
                    .rounded(theme.radius)
                    .border_1()
                    .border_color(if busy { theme.ring } else { theme.border })
                    .when(other_busy, |this| this.opacity(0.5).cursor_not_allowed())
                    .when(waiting.is_none(), |this| {
                        this.cursor_pointer()
                            .hover(|style| style.bg(theme.accent))
                            .on_click(cx.listener(move |this, _, _, cx| this.connect(ix, cx)))
                    })
                    .child(
                        div()
                            .flex_none()
                            .size(px(36.0))
                            .rounded(theme.radius)
                            .bg(theme.muted)
                            .flex()
                            .items_center()
                            .justify_center()
                            .child(icon(wallet.icon).size(px(18.0)).text_color(theme.foreground)),
                    )
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .flex()
                            .flex_col()
                            .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(wallet.name))
                            .child(div().text_xs().text_color(theme.muted_foreground).child(if busy {
                                "Approve the request in your wallet\u{2026}"
                            } else {
                                wallet.description
                            })),
                    )
                    .child(if busy {
                        Spinner::new().size(SpinnerSize::Sm).into_any_element()
                    } else {
                        icon(CHEVRON_RIGHT).size(px(16.0)).text_color(theme.muted_foreground).into_any_element()
                    })
            });
    
            let dialog = Dialog::new("wallets", self.dialog_open)
                .title("Connect a wallet")
                .description("Choose how to connect. You approve the connection in your wallet.")
                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                    if *open {
                        this.dialog_open = true;
                        cx.notify();
                    } else {
                        this.cancel(cx);
                    }
                }))
                .child(div().flex().flex_col().gap_2().children(rows))
                .child(
                    div()
                        .text_xs()
                        .text_color(theme.muted_foreground)
                        .child("Connecting shares your address. It never moves funds or reveals keys."),
                );
    
            div()
                .size_full()
                .flex()
                .flex_col()
                .items_center()
                .justify_center()
                .gap_3()
                .child(trigger)
                .child(div().text_xs().text_color(theme.muted_foreground).child(match self.connection {
                    Connection::Disconnected => "Not connected",
                    Connection::Connecting(_) => "Waiting for the wallet",
                    Connection::Connected { .. } => "Connected \u{00b7} sample account",
                }))
                .child(dialog)
                .child(Toaster::new())
        }
    }
    
    /// The host opens its block explorer at the account. The demo has no explorer, so it says
    /// which address it would open.
    fn open_explorer(account: Address, cx: &mut App) {
        toast(Toast::new("Open in explorer").description(account.to_string()), cx);
    }