hyuskui

Bridge Card

Moves a token between networks: from and to chains with a swap button, an amount validated with Form, and the route's estimated time, fee and the amount that arrives, all in integer base units.

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

use crate::icons::{icon, ARROW_RIGHT};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::form::{field, Form, FormExt, Mode, Schema};
use crate::ui::input_group::InputGroup;
use crate::ui::onchain::{format_amount, format_bps, format_units, mul_div, parse_units, AmountError, BPS};
use crate::ui::select::{Select, SelectOption};
use crate::ui::toast::{toast, Toast, ToastKind, Toaster};

/// Sample networks with generic names, and how long a transfer to each takes.
const CHAINS: [(&str, &str); 4] =
    [("Mainnet", "~15 min"), ("Rollup One", "~2 min"), ("Rollup Two", "~2 min"), ("Testnet", "~1 min")];

/// Bridging sample USDC (6 decimals).
const DECIMALS: u8 = 6;
const BALANCE: u128 = 2_500_120_000;
/// The sample route charges a flat relayer fee plus a share of the amount.
const FLAT_FEE: u128 = 500_000;
const FEE_BPS: u128 = 5;

#[derive(Clone, Default, Debug, PartialEq)]
struct BridgeForm {
    amount: String,
}

fn fee(units: u128) -> Option<u128> {
    FLAT_FEE.checked_add(mul_div(units, FEE_BPS, BPS)?)
}

fn schema() -> Schema<BridgeForm> {
    let parsed = |v: &BridgeForm| parse_units(&v.amount, DECIMALS);
    Schema::<BridgeForm>::new()
        .refine("amount", move |v| !matches!(parsed(v), Err(AmountError::Empty) | Ok(0)), "Enter an amount.")
        .refine("amount", move |v| parsed(v) != Err(AmountError::Invalid), "Use digits and one decimal point.")
        .refine("amount", move |v| !matches!(parsed(v), Err(AmountError::TooManyDecimals { .. })), "USDC has 6 decimal places.")
        .refine("amount", move |v| parsed(v) != Err(AmountError::Overflow), "Amount is too large.")
        .refine("amount", move |v| parsed(v).map_or(true, |u| u <= BALANCE), "More than your balance.")
        .refine("amount", move |v| parsed(v).map_or(true, |u| fee(u).is_some_and(|f| u > f)), "Amount must cover the fee.")
}

pub struct BridgeCardPattern {
    from: usize,
    to: usize,
    open: Option<bool>,
}

impl Default for BridgeCardPattern {
    fn default() -> Self {
        Self { from: 0, to: 1, open: None }
    }
}

impl BridgeCardPattern {
    fn set_chain(&mut self, from_side: bool, name: &SharedString, cx: &mut Context<Self>) {
        let Some(ix) = CHAINS.iter().position(|(chain, _)| *chain == name.as_ref()) else {
            return;
        };
        let other = if from_side { self.to } else { self.from };
        // Choosing the other side's chain swaps them, so a route never starts and ends in one place.
        if ix == other {
            std::mem::swap(&mut self.from, &mut self.to);
        } else if from_side {
            self.from = ix;
        } else {
            self.to = ix;
        }
        cx.notify();
    }
}

impl Render for BridgeCardPattern {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let form = window.use_keyed_state("bridge-form", cx, |_, _| {
            Form::new(BridgeForm::default()).schema(schema()).mode(Mode::OnChange)
        });
        let input = form.input(field!(amount), window, cx, |input| input.placeholder("0.00").bare());
        let theme = cx.theme().clone();

        let chain_select = |id: &'static str, from_side: bool, current: usize, cx: &mut Context<Self>| {
            CHAINS
                .iter()
                .fold(
                    Select::new(id, Some(SharedString::from(CHAINS[current].0)), self.open == Some(from_side))
                        .width(px(170.0)),
                    |select, (name, _)| select.option(SelectOption::new(*name, *name)),
                )
                .on_change(cx.listener(move |this, value: &SharedString, _, cx| this.set_chain(from_side, value, cx)))
                .on_open_change(cx.listener(move |this, open: &bool, _, cx| {
                    this.open = open.then_some(from_side);
                    cx.notify();
                }))
        };
        let from_select = chain_select("from-chain", true, self.from, cx);
        let to_select = chain_select("to-chain", false, self.to, cx);
        let f = form.read(cx);
        let units = parse_units(&f.values().amount, DECIMALS).ok().filter(|&u| u > 0);
        let route_fee = units.and_then(fee);
        let arrives = units.zip(route_fee).and_then(|(u, f)| u.checked_sub(f));
        let label = |text: &'static str| div().text_xs().font_weight(FontWeight::MEDIUM).text_color(theme.muted_foreground).child(text);
        let row = |name: SharedString, value: String| {
            div()
                .flex()
                .justify_between()
                .text_sm()
                .child(div().text_color(theme.muted_foreground).child(name))
                .child(value)
        };
        let usdc = |units: Option<u128>| units.map_or("\u{2014}".into(), |u| format!("{} USDC", format_amount(u, DECIMALS, 2)));

        let max = {
            let form = form.clone();
            move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut gpui::App| {
                let amount = format_units(BALANCE, DECIMALS);
                form.update(cx, |form, cx| form.set_value(&field!(amount), amount, window, cx));
            }
        };
        let (from_name, to_name) = (CHAINS[self.from].0, CHAINS[self.to].0);

        div()
            .w(px(420.0))
            .flex()
            .flex_col()
            .gap_4()
            .p_5()
            .rounded(theme.radius * 1.5)
            .border_1()
            .border_color(theme.border)
            .bg(theme.card)
            .child(
                div()
                    .flex()
                    .flex_col()
                    .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Bridge"))
                    .child(div().text_xs().text_color(theme.muted_foreground).child("Move USDC between networks. Sample route.")),
            )
            .child(
                div()
                    .flex()
                    .items_end()
                    .gap_2()
                    .child(div().flex().flex_col().gap_1p5().child(label("From")).child(from_select))
                    .child(
                        Button::new("swap-chains", "")
                            .variant(ButtonVariant::Ghost)
                            .icon_only()
                            .leading(icon(ARROW_RIGHT).size(px(16.0)).text_color(theme.foreground))
                            .on_click(cx.listener(|this, _, _, cx| {
                                std::mem::swap(&mut this.from, &mut this.to);
                                cx.notify();
                            })),
                    )
                    .child(div().flex().flex_col().gap_1p5().child(label("To")).child(to_select)),
            )
            .child(
                f.field("amount").label("Amount").child(
                    InputGroup::new(input)
                        .trailing(Button::new("max", "Max").variant(ButtonVariant::Secondary).size(ButtonSize::Xs).on_click(max))
                        .trailing(div().text_sm().text_color(theme.muted_foreground).child("USDC")),
                ),
            )
            .child(
                div()
                    .flex()
                    .flex_col()
                    .gap_2()
                    .child(row(format!("Balance on {from_name}").into(), format!("{} USDC", format_amount(BALANCE, DECIMALS, 2))))
                    .child(row("Estimated time".into(), CHAINS[self.to].1.to_string()))
                    .child(row("Bridge fee".into(), format!("{} ({} + 0.50 USDC)", usdc(route_fee), format_bps(FEE_BPS))))
                    .child(
                        div()
                            .flex()
                            .justify_between()
                            .pt_2()
                            .border_t_1()
                            .border_color(theme.border)
                            .text_sm()
                            .font_weight(FontWeight::MEDIUM)
                            .child(format!("You receive on {to_name}"))
                            .child(usdc(arrives)),
                    ),
            )
            .child(
                div().flex().flex_col().child(
                    Button::new("bridge", format!("Bridge to {to_name}")).size(ButtonSize::Lg).on_click(form.handle_submit_with(
                        move |values, _, cx| {
                            if let Ok(units) = parse_units(&values.amount, DECIMALS) {
                                // The host builds the bridge transaction from `units`.
                                toast(
                                    Toast::new("Bridge submitted")
                                        .kind(ToastKind::Success)
                                        .description(format!("{} USDC from {from_name} to {to_name}", format_units(units, DECIMALS))),
                                    cx,
                                );
                            }
                        },
                        |_, _, _| {},
                    )),
                ),
            )
            .child(Toaster::new())
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add button form input-group onchain select toast icons

    Uses Button, Form, Input Group, Onchain, Select 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/bridge_card.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/bridge_card.rs
    use gpui::{div, prelude::*, px, Context, FontWeight, SharedString, Window};
    
    use crate::icons::{icon, ARROW_RIGHT};
    use crate::theme::ActiveTheme;
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::form::{field, Form, FormExt, Mode, Schema};
    use crate::ui::input_group::InputGroup;
    use crate::ui::onchain::{format_amount, format_bps, format_units, mul_div, parse_units, AmountError, BPS};
    use crate::ui::select::{Select, SelectOption};
    use crate::ui::toast::{toast, Toast, ToastKind, Toaster};
    
    /// Sample networks with generic names, and how long a transfer to each takes.
    const CHAINS: [(&str, &str); 4] =
        [("Mainnet", "~15 min"), ("Rollup One", "~2 min"), ("Rollup Two", "~2 min"), ("Testnet", "~1 min")];
    
    /// Bridging sample USDC (6 decimals).
    const DECIMALS: u8 = 6;
    const BALANCE: u128 = 2_500_120_000;
    /// The sample route charges a flat relayer fee plus a share of the amount.
    const FLAT_FEE: u128 = 500_000;
    const FEE_BPS: u128 = 5;
    
    #[derive(Clone, Default, Debug, PartialEq)]
    struct BridgeForm {
        amount: String,
    }
    
    fn fee(units: u128) -> Option<u128> {
        FLAT_FEE.checked_add(mul_div(units, FEE_BPS, BPS)?)
    }
    
    fn schema() -> Schema<BridgeForm> {
        let parsed = |v: &BridgeForm| parse_units(&v.amount, DECIMALS);
        Schema::<BridgeForm>::new()
            .refine("amount", move |v| !matches!(parsed(v), Err(AmountError::Empty) | Ok(0)), "Enter an amount.")
            .refine("amount", move |v| parsed(v) != Err(AmountError::Invalid), "Use digits and one decimal point.")
            .refine("amount", move |v| !matches!(parsed(v), Err(AmountError::TooManyDecimals { .. })), "USDC has 6 decimal places.")
            .refine("amount", move |v| parsed(v) != Err(AmountError::Overflow), "Amount is too large.")
            .refine("amount", move |v| parsed(v).map_or(true, |u| u <= BALANCE), "More than your balance.")
            .refine("amount", move |v| parsed(v).map_or(true, |u| fee(u).is_some_and(|f| u > f)), "Amount must cover the fee.")
    }
    
    pub struct BridgeCardPattern {
        from: usize,
        to: usize,
        open: Option<bool>,
    }
    
    impl Default for BridgeCardPattern {
        fn default() -> Self {
            Self { from: 0, to: 1, open: None }
        }
    }
    
    impl BridgeCardPattern {
        fn set_chain(&mut self, from_side: bool, name: &SharedString, cx: &mut Context<Self>) {
            let Some(ix) = CHAINS.iter().position(|(chain, _)| *chain == name.as_ref()) else {
                return;
            };
            let other = if from_side { self.to } else { self.from };
            // Choosing the other side's chain swaps them, so a route never starts and ends in one place.
            if ix == other {
                std::mem::swap(&mut self.from, &mut self.to);
            } else if from_side {
                self.from = ix;
            } else {
                self.to = ix;
            }
            cx.notify();
        }
    }
    
    impl Render for BridgeCardPattern {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let form = window.use_keyed_state("bridge-form", cx, |_, _| {
                Form::new(BridgeForm::default()).schema(schema()).mode(Mode::OnChange)
            });
            let input = form.input(field!(amount), window, cx, |input| input.placeholder("0.00").bare());
            let theme = cx.theme().clone();
    
            let chain_select = |id: &'static str, from_side: bool, current: usize, cx: &mut Context<Self>| {
                CHAINS
                    .iter()
                    .fold(
                        Select::new(id, Some(SharedString::from(CHAINS[current].0)), self.open == Some(from_side))
                            .width(px(170.0)),
                        |select, (name, _)| select.option(SelectOption::new(*name, *name)),
                    )
                    .on_change(cx.listener(move |this, value: &SharedString, _, cx| this.set_chain(from_side, value, cx)))
                    .on_open_change(cx.listener(move |this, open: &bool, _, cx| {
                        this.open = open.then_some(from_side);
                        cx.notify();
                    }))
            };
            let from_select = chain_select("from-chain", true, self.from, cx);
            let to_select = chain_select("to-chain", false, self.to, cx);
            let f = form.read(cx);
            let units = parse_units(&f.values().amount, DECIMALS).ok().filter(|&u| u > 0);
            let route_fee = units.and_then(fee);
            let arrives = units.zip(route_fee).and_then(|(u, f)| u.checked_sub(f));
            let label = |text: &'static str| div().text_xs().font_weight(FontWeight::MEDIUM).text_color(theme.muted_foreground).child(text);
            let row = |name: SharedString, value: String| {
                div()
                    .flex()
                    .justify_between()
                    .text_sm()
                    .child(div().text_color(theme.muted_foreground).child(name))
                    .child(value)
            };
            let usdc = |units: Option<u128>| units.map_or("\u{2014}".into(), |u| format!("{} USDC", format_amount(u, DECIMALS, 2)));
    
            let max = {
                let form = form.clone();
                move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut gpui::App| {
                    let amount = format_units(BALANCE, DECIMALS);
                    form.update(cx, |form, cx| form.set_value(&field!(amount), amount, window, cx));
                }
            };
            let (from_name, to_name) = (CHAINS[self.from].0, CHAINS[self.to].0);
    
            div()
                .w(px(420.0))
                .flex()
                .flex_col()
                .gap_4()
                .p_5()
                .rounded(theme.radius * 1.5)
                .border_1()
                .border_color(theme.border)
                .bg(theme.card)
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Bridge"))
                        .child(div().text_xs().text_color(theme.muted_foreground).child("Move USDC between networks. Sample route.")),
                )
                .child(
                    div()
                        .flex()
                        .items_end()
                        .gap_2()
                        .child(div().flex().flex_col().gap_1p5().child(label("From")).child(from_select))
                        .child(
                            Button::new("swap-chains", "")
                                .variant(ButtonVariant::Ghost)
                                .icon_only()
                                .leading(icon(ARROW_RIGHT).size(px(16.0)).text_color(theme.foreground))
                                .on_click(cx.listener(|this, _, _, cx| {
                                    std::mem::swap(&mut this.from, &mut this.to);
                                    cx.notify();
                                })),
                        )
                        .child(div().flex().flex_col().gap_1p5().child(label("To")).child(to_select)),
                )
                .child(
                    f.field("amount").label("Amount").child(
                        InputGroup::new(input)
                            .trailing(Button::new("max", "Max").variant(ButtonVariant::Secondary).size(ButtonSize::Xs).on_click(max))
                            .trailing(div().text_sm().text_color(theme.muted_foreground).child("USDC")),
                    ),
                )
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .gap_2()
                        .child(row(format!("Balance on {from_name}").into(), format!("{} USDC", format_amount(BALANCE, DECIMALS, 2))))
                        .child(row("Estimated time".into(), CHAINS[self.to].1.to_string()))
                        .child(row("Bridge fee".into(), format!("{} ({} + 0.50 USDC)", usdc(route_fee), format_bps(FEE_BPS))))
                        .child(
                            div()
                                .flex()
                                .justify_between()
                                .pt_2()
                                .border_t_1()
                                .border_color(theme.border)
                                .text_sm()
                                .font_weight(FontWeight::MEDIUM)
                                .child(format!("You receive on {to_name}"))
                                .child(usdc(arrives)),
                        ),
                )
                .child(
                    div().flex().flex_col().child(
                        Button::new("bridge", format!("Bridge to {to_name}")).size(ButtonSize::Lg).on_click(form.handle_submit_with(
                            move |values, _, cx| {
                                if let Ok(units) = parse_units(&values.amount, DECIMALS) {
                                    // The host builds the bridge transaction from `units`.
                                    toast(
                                        Toast::new("Bridge submitted")
                                            .kind(ToastKind::Success)
                                            .description(format!("{} USDC from {from_name} to {to_name}", format_units(units, DECIMALS))),
                                        cx,
                                    );
                                }
                            },
                            |_, _, _| {},
                        )),
                    ),
                )
                .child(Toaster::new())
        }
    }