hyuskui

Swap Card

Two token amounts with a flip button between them, the quote's rate, price impact and minimum received, and slippage settings in a popover. The amount is validated with Form against the token's decimals and balance; the button says what is wrong until it can swap.

Loading GPUI…
use std::{cell::Cell, rc::Rc};

use gpui::{div, prelude::*, px, ClickEvent, Context, Entity, FontWeight, Hsla, SharedString, Window};

use crate::icons::{icon, ARROW_UP_DOWN, CHEVRON_DOWN, SETTINGS_2};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::form::{field, Form, FormExt, Mode, Schema};
use crate::ui::onchain::{
    constant_product_out, convert, format_amount, format_bps, format_units, format_usd_cents, min_received,
    mul_div, parse_units, pow10, price_impact_bps, usd_cents, AmountError,
};
use crate::ui::popover::{Align, Popover};
use crate::ui::toast::{toast, Toast, Toaster};
use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};

pub struct Token {
    pub symbol: &'static str,
    pub decimals: u8,
    /// Sample USD price, 8 decimals.
    pub price_e8: u128,
    /// Sample balance in base units.
    pub balance: u128,
}

/// Sample tokens with their real decimals; prices and balances are made up.
pub const TOKENS: [Token; 4] = [
    Token { symbol: "ETH", decimals: 18, price_e8: 300_000_000_000, balance: 1_234_567_890_123_456_789 },
    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: "DAI", decimals: 18, price_e8: 100_000_000, balance: 820_500_000_000_000_000_000 },
];

/// Each sample pool holds $2M a side, so a large trade shows real price impact.
const POOL_SIDE_USD_E8: u128 = 2_000_000 * 100_000_000;
const POOL_FEE_BPS: u128 = 30;
/// Above this, the impact row turns destructive.
const HIGH_IMPACT_BPS: u128 = 300;
const SLIPPAGE_PRESETS: [u128; 3] = [10, 50, 100];

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

/// What the quote shows for an input amount.
pub struct Quote {
    pub amount_out: u128,
    pub impact_bps: u128,
    pub min_out: u128,
}

/// Quotes a sample constant-product pool. A real app asks its router and shows that answer.
pub fn quote(amount_in: u128, from: &Token, to: &Token, slippage_bps: u128) -> Option<Quote> {
    let reserve_in = mul_div(POOL_SIDE_USD_E8, pow10(from.decimals)?, from.price_e8)?;
    let reserve_out = mul_div(POOL_SIDE_USD_E8, pow10(to.decimals)?, to.price_e8)?;
    let amount_out = constant_product_out(amount_in, reserve_in, reserve_out, POOL_FEE_BPS)?;
    // Impact is measured without the fee, so it reflects pool depth alone.
    let no_fee_out = constant_product_out(amount_in, reserve_in, reserve_out, 0)?;
    Some(Quote {
        amount_out,
        impact_bps: price_impact_bps(amount_in, no_fee_out, reserve_in, reserve_out)?,
        min_out: min_received(amount_out, slippage_bps)?,
    })
}

pub struct SwapCardPattern {
    from: usize,
    /// The sold token, shared with the form's rules so they check the right decimals and balance.
    from_cell: Rc<Cell<usize>>,
    /// The form, kept from the last render: keyed state can only be read while rendering, and
    /// event handlers need it too.
    amount_form: Option<Entity<Form<SwapForm>>>,
    to: usize,
    slippage_bps: u128,
    settings_open: bool,
    menu_open: Option<Side>,
}

#[derive(Clone, Copy, PartialEq)]
enum Side {
    From,
    To,
}

impl Default for SwapCardPattern {
    fn default() -> Self {
        Self {
            from: 0,
            from_cell: Rc::new(Cell::new(0)),
            amount_form: None,
            to: 1,
            slippage_bps: 50,
            settings_open: false,
            menu_open: None,
        }
    }
}

fn amount_schema(from: Rc<Cell<usize>>) -> Schema<SwapForm> {
    let rule = move |test: fn(Result<u128, AmountError>, u128) -> bool| {
        let from = from.clone();
        move |v: &SwapForm| {
            let token = &TOKENS[from.get()];
            test(parse_units(&v.amount, token.decimals), token.balance)
        }
    };
    Schema::<SwapForm>::new()
        .refine("amount", rule(|p, _| p != Err(AmountError::Empty) && p != Ok(0)), "Enter an amount")
        .refine("amount", rule(|p, _| p != Err(AmountError::Invalid)), "Enter a valid amount")
        .refine("amount", rule(|p, _| !matches!(p, Err(AmountError::TooManyDecimals { .. }))), "Too many decimal places")
        .refine("amount", rule(|p, _| p != Err(AmountError::Overflow)), "Amount too large")
        .refine("amount", rule(|p, balance| p.map_or(true, |units| units <= balance)), "Insufficient balance")
}

impl SwapCardPattern {
    fn form(&self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Form<SwapForm>> {
        let from = self.from_cell.clone();
        window.use_keyed_state("swap-form", cx, |_, _| {
            Form::new(SwapForm::default()).schema(amount_schema(from)).mode(Mode::OnChange)
        })
    }

    /// The same text can be valid for one token and not another, so check again after a change.
    fn revalidate(&self, cx: &mut Context<Self>) {
        self.from_cell.set(self.from);
        let Some(form) = self.amount_form.clone() else {
            return;
        };
        form.update(cx, |form, cx| {
            if !form.values().amount.is_empty() {
                let _ = form.trigger("amount", cx);
            }
        });
    }

    fn pick(&mut self, side: Side, ix: usize, cx: &mut Context<Self>) {
        let (this_side, other) = match side {
            Side::From => (&mut self.from, self.to),
            Side::To => (&mut self.to, self.from),
        };
        // Picking the token on the other side swaps them rather than pairing a token with itself.
        if ix == other {
            std::mem::swap(&mut self.from, &mut self.to);
        } else {
            *this_side = ix;
        }
        self.menu_open = None;
        self.revalidate(cx);
        cx.notify();
    }
}

impl Render for SwapCardPattern {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.from_cell.set(self.from);
        let form = self.form(window, cx);
        self.amount_form = Some(form.clone());
        let input = form.input(field!(amount), window, cx, |input| input.placeholder("0").bare().font_size(px(24.0)));
        let theme = cx.theme().clone();
        let (from, to) = (&TOKENS[self.from], &TOKENS[self.to]);

        let f = form.read(cx);
        let parsed = parse_units(&f.values().amount, from.decimals);
        let amount_in = parsed.unwrap_or(0);
        let quote = (amount_in > 0).then(|| quote(amount_in, from, to, self.slippage_bps)).flatten();
        // The form shows errors only after the user typed; the button needs them before that too.
        let problem: Option<SharedString> = match parsed {
            Err(AmountError::Empty) | Ok(0) => Some("Enter an amount".into()),
            Ok(units) if units > from.balance => Some(format!("Insufficient {} balance", from.symbol).into()),
            _ => f.error("amount").or_else(|| quote.is_none().then(|| "No quote for this amount".into())),
        };

        let settings = Popover::new("swap-settings", self.settings_open)
            .align(Align::End)
            .width(px(260.0))
            .trigger(
                Button::new("settings", "")
                    .variant(ButtonVariant::Ghost)
                    .size(ButtonSize::Sm)
                    .icon_only()
                    .leading(icon(SETTINGS_2).size(px(16.0)).text_color(theme.muted_foreground)),
            )
            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                this.settings_open = *open;
                cx.notify();
            }))
            .child(
                div()
                    .flex()
                    .flex_col()
                    .gap_3()
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .gap_1()
                            .child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Max slippage"))
                            .child(div().text_xs().text_color(theme.muted_foreground).child(
                                "The swap reverts if the price moves against you by more than this.",
                            )),
                    )
                    .child(
                        SLIPPAGE_PRESETS.iter().fold(
                            ToggleGroup::new("slippage", ToggleGroupMode::Single)
                                .selected(SLIPPAGE_PRESETS.iter().position(|&bps| bps == self.slippage_bps))
                                .on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
                                    // Pressing the active preset would clear it; keep the last choice instead.
                                    if let Some(&ix) = selected.first() {
                                        this.slippage_bps = SLIPPAGE_PRESETS[ix];
                                        cx.notify();
                                    }
                                })),
                            |group, &bps| group.item(format_bps(bps)),
                        ),
                    ),
            );

        let header = div()
            .flex()
            .items_center()
            .justify_between()
            .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Swap"))
            .child(settings);

        let pay_value = usd_cents(amount_in, from.decimals, from.price_e8).unwrap_or(0);
        let max = {
            let form = form.clone();
            let (balance, decimals) = (from.balance, from.decimals);
            move |_: &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 pay = panel(
            "You pay",
            div().flex_1().min_w_0().child(input).into_any_element(),
            self.token_menu(Side::From, cx),
            format_usd_cents(pay_value),
            div()
                .flex()
                .items_center()
                .gap_1()
                .child(format!("{} {}", format_amount(from.balance, from.decimals, 4), from.symbol))
                .child(
                    Button::new("max", "Max").variant(ButtonVariant::Ghost).size(ButtonSize::Xs).on_click(max),
                )
                .into_any_element(),
            theme.muted,
            theme.muted_foreground,
        );

        let out = quote.as_ref().map_or(0, |q| q.amount_out);
        let receive_value = usd_cents(out, to.decimals, to.price_e8).unwrap_or(0);
        let receive = panel(
            "You receive",
            div()
                .flex_1()
                .min_w_0()
                .text_2xl()
                .truncate()
                .text_color(if out == 0 { theme.muted_foreground } else { theme.foreground })
                .child(format_amount(out, to.decimals, 6))
                .into_any_element(),
            self.token_menu(Side::To, cx),
            format_usd_cents(receive_value),
            div()
                .child(format!("{} {}", format_amount(to.balance, to.decimals, 4), to.symbol))
                .into_any_element(),
            theme.muted,
            theme.muted_foreground,
        );

        let flip = div().h_0().flex().justify_center().relative().child(
            div()
                .id("flip")
                .absolute()
                .top(px(-20.0))
                .size(px(40.0))
                .flex()
                .items_center()
                .justify_center()
                .rounded(theme.radius)
                .border_4()
                .border_color(theme.card)
                .bg(theme.muted)
                .cursor_pointer()
                .hover(|style| style.bg(theme.accent))
                .on_click(cx.listener(|this, _, _, cx| {
                    std::mem::swap(&mut this.from, &mut this.to);
                    this.revalidate(cx);
                    cx.notify();
                }))
                .child(icon(ARROW_UP_DOWN).size(px(16.0)).text_color(theme.foreground)),
        );

        let row = |label: &'static str, value: String, color: Hsla| {
            div()
                .flex()
                .justify_between()
                .text_xs()
                .child(div().text_color(theme.muted_foreground).child(label))
                .child(div().text_color(color).child(value))
        };
        let details = quote.as_ref().map(|q| {
            let rate = rate(from, to);
            let impact = if q.impact_bps == 0 { "<0.01%".to_string() } else { format_bps(q.impact_bps) };
            let impact_color = if q.impact_bps > HIGH_IMPACT_BPS { theme.destructive } else { theme.foreground };
            div()
                .flex()
                .flex_col()
                .gap_1p5()
                .px_1()
                .child(row("Rate", rate, theme.foreground))
                .child(row("Price impact", impact, impact_color))
                .child(row(
                    "Minimum received",
                    format!("{} {}", format_amount(q.min_out, to.decimals, 6), to.symbol),
                    theme.foreground,
                ))
                .child(row("Max slippage", format_bps(self.slippage_bps), theme.foreground))
        });

        let swap = Button::new("swap", problem.clone().unwrap_or_else(|| "Swap".into()))
            .size(ButtonSize::Lg)
            .disabled(problem.is_some())
            .on_click({
                let (from_symbol, to_symbol) = (from.symbol, to.symbol);
                let summary = quote.as_ref().map(|q| {
                    format!(
                        "{} {from_symbol} for at least {} {to_symbol}",
                        format_units(amount_in, from.decimals),
                        format_units(q.min_out, to.decimals)
                    )
                });
                move |_, _, cx| {
                    // The host sends the swap with `amount_in` and `min_out` in base units.
                    if let Some(summary) = &summary {
                        toast(Toast::new("Swap submitted").description(summary.clone()), cx);
                    }
                }
            });

        div()
            .w(px(400.0))
            .flex()
            .flex_col()
            .gap_3()
            .p_4()
            .rounded(theme.radius * 2.0)
            .border_1()
            .border_color(theme.border)
            .bg(theme.card)
            .child(header)
            .child(div().flex().flex_col().gap_1().child(pay).child(flip).child(receive))
            .children(details)
            .child(div().w_full().flex().flex_col().child(swap))
            .child(Toaster::new())
    }
}

impl SwapCardPattern {
    fn token_menu(&self, side: Side, cx: &mut Context<Self>) -> gpui::AnyElement {
        let theme = cx.theme();
        let current = match side {
            Side::From => self.from,
            Side::To => self.to,
        };
        let token = &TOKENS[current];
        let id = match side {
            Side::From => "from-token",
            Side::To => "to-token",
        };
        TOKENS
            .iter()
            .enumerate()
            .fold(
                DropdownMenu::new(id, self.menu_open == Some(side))
                    .align(Align::End)
                    .trigger(
                        Button::new((id, 0usize), 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)),
                    )
                    .on_open_change(cx.listener(move |this, open: &bool, _, cx| {
                        this.menu_open = open.then_some(side);
                        cx.notify();
                    })),
                |menu, (ix, token)| {
                    menu.item(
                        MenuItem::new(token.symbol)
                            .radio(ix == current)
                            .on_select(cx.listener(move |this, _: &ClickEvent, _, cx| this.pick(side, ix, cx))),
                    )
                },
            )
            .into_any_element()
    }
}

/// `1 ETH = 3,000 USDC`, from the sample prices.
fn rate(from: &Token, to: &Token) -> String {
    let one = pow10(from.decimals).unwrap_or(1);
    let out = convert(one, from.decimals, from.price_e8, to.decimals, to.price_e8).unwrap_or(0);
    format!("1 {} = {} {}", from.symbol, format_amount(out, to.decimals, 6), to.symbol)
}

/// One side of the swap: a label, the amount, the token, and a line of value and balance.
fn panel(
    label: &'static str,
    amount: gpui::AnyElement,
    token: gpui::AnyElement,
    value: String,
    balance: gpui::AnyElement,
    bg: Hsla,
    muted: Hsla,
) -> impl IntoElement {
    div()
        .flex()
        .flex_col()
        .gap_1()
        .p_4()
        .rounded_lg()
        .bg(bg)
        .child(div().text_xs().text_color(muted).child(label))
        .child(div().flex().items_center().gap_3().h(px(40.0)).child(amount).child(token))
        .child(div().flex().items_center().justify_between().text_xs().text_color(muted).child(value).child(balance))
}

/// A token's stand-in logo: its first letter on a round tile.
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 button dropdown-menu form onchain popover toast toggle-group icons

    Uses Avatar, Button, Dropdown Menu, Form, Onchain, Popover, Toast and Toggle Group.

  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/swap_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/swap_card.rs
    use std::{cell::Cell, rc::Rc};
    
    use gpui::{div, prelude::*, px, ClickEvent, Context, Entity, FontWeight, Hsla, SharedString, Window};
    
    use crate::icons::{icon, ARROW_UP_DOWN, CHEVRON_DOWN, SETTINGS_2};
    use crate::theme::ActiveTheme;
    use crate::ui::avatar::{Avatar, AvatarSize};
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
    use crate::ui::form::{field, Form, FormExt, Mode, Schema};
    use crate::ui::onchain::{
        constant_product_out, convert, format_amount, format_bps, format_units, format_usd_cents, min_received,
        mul_div, parse_units, pow10, price_impact_bps, usd_cents, AmountError,
    };
    use crate::ui::popover::{Align, Popover};
    use crate::ui::toast::{toast, Toast, Toaster};
    use crate::ui::toggle_group::{ToggleGroup, ToggleGroupMode};
    
    pub struct Token {
        pub symbol: &'static str,
        pub decimals: u8,
        /// Sample USD price, 8 decimals.
        pub price_e8: u128,
        /// Sample balance in base units.
        pub balance: u128,
    }
    
    /// Sample tokens with their real decimals; prices and balances are made up.
    pub const TOKENS: [Token; 4] = [
        Token { symbol: "ETH", decimals: 18, price_e8: 300_000_000_000, balance: 1_234_567_890_123_456_789 },
        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: "DAI", decimals: 18, price_e8: 100_000_000, balance: 820_500_000_000_000_000_000 },
    ];
    
    /// Each sample pool holds $2M a side, so a large trade shows real price impact.
    const POOL_SIDE_USD_E8: u128 = 2_000_000 * 100_000_000;
    const POOL_FEE_BPS: u128 = 30;
    /// Above this, the impact row turns destructive.
    const HIGH_IMPACT_BPS: u128 = 300;
    const SLIPPAGE_PRESETS: [u128; 3] = [10, 50, 100];
    
    #[derive(Clone, Default, Debug, PartialEq)]
    struct SwapForm {
        amount: String,
    }
    
    /// What the quote shows for an input amount.
    pub struct Quote {
        pub amount_out: u128,
        pub impact_bps: u128,
        pub min_out: u128,
    }
    
    /// Quotes a sample constant-product pool. A real app asks its router and shows that answer.
    pub fn quote(amount_in: u128, from: &Token, to: &Token, slippage_bps: u128) -> Option<Quote> {
        let reserve_in = mul_div(POOL_SIDE_USD_E8, pow10(from.decimals)?, from.price_e8)?;
        let reserve_out = mul_div(POOL_SIDE_USD_E8, pow10(to.decimals)?, to.price_e8)?;
        let amount_out = constant_product_out(amount_in, reserve_in, reserve_out, POOL_FEE_BPS)?;
        // Impact is measured without the fee, so it reflects pool depth alone.
        let no_fee_out = constant_product_out(amount_in, reserve_in, reserve_out, 0)?;
        Some(Quote {
            amount_out,
            impact_bps: price_impact_bps(amount_in, no_fee_out, reserve_in, reserve_out)?,
            min_out: min_received(amount_out, slippage_bps)?,
        })
    }
    
    pub struct SwapCardPattern {
        from: usize,
        /// The sold token, shared with the form's rules so they check the right decimals and balance.
        from_cell: Rc<Cell<usize>>,
        /// The form, kept from the last render: keyed state can only be read while rendering, and
        /// event handlers need it too.
        amount_form: Option<Entity<Form<SwapForm>>>,
        to: usize,
        slippage_bps: u128,
        settings_open: bool,
        menu_open: Option<Side>,
    }
    
    #[derive(Clone, Copy, PartialEq)]
    enum Side {
        From,
        To,
    }
    
    impl Default for SwapCardPattern {
        fn default() -> Self {
            Self {
                from: 0,
                from_cell: Rc::new(Cell::new(0)),
                amount_form: None,
                to: 1,
                slippage_bps: 50,
                settings_open: false,
                menu_open: None,
            }
        }
    }
    
    fn amount_schema(from: Rc<Cell<usize>>) -> Schema<SwapForm> {
        let rule = move |test: fn(Result<u128, AmountError>, u128) -> bool| {
            let from = from.clone();
            move |v: &SwapForm| {
                let token = &TOKENS[from.get()];
                test(parse_units(&v.amount, token.decimals), token.balance)
            }
        };
        Schema::<SwapForm>::new()
            .refine("amount", rule(|p, _| p != Err(AmountError::Empty) && p != Ok(0)), "Enter an amount")
            .refine("amount", rule(|p, _| p != Err(AmountError::Invalid)), "Enter a valid amount")
            .refine("amount", rule(|p, _| !matches!(p, Err(AmountError::TooManyDecimals { .. }))), "Too many decimal places")
            .refine("amount", rule(|p, _| p != Err(AmountError::Overflow)), "Amount too large")
            .refine("amount", rule(|p, balance| p.map_or(true, |units| units <= balance)), "Insufficient balance")
    }
    
    impl SwapCardPattern {
        fn form(&self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Form<SwapForm>> {
            let from = self.from_cell.clone();
            window.use_keyed_state("swap-form", cx, |_, _| {
                Form::new(SwapForm::default()).schema(amount_schema(from)).mode(Mode::OnChange)
            })
        }
    
        /// The same text can be valid for one token and not another, so check again after a change.
        fn revalidate(&self, cx: &mut Context<Self>) {
            self.from_cell.set(self.from);
            let Some(form) = self.amount_form.clone() else {
                return;
            };
            form.update(cx, |form, cx| {
                if !form.values().amount.is_empty() {
                    let _ = form.trigger("amount", cx);
                }
            });
        }
    
        fn pick(&mut self, side: Side, ix: usize, cx: &mut Context<Self>) {
            let (this_side, other) = match side {
                Side::From => (&mut self.from, self.to),
                Side::To => (&mut self.to, self.from),
            };
            // Picking the token on the other side swaps them rather than pairing a token with itself.
            if ix == other {
                std::mem::swap(&mut self.from, &mut self.to);
            } else {
                *this_side = ix;
            }
            self.menu_open = None;
            self.revalidate(cx);
            cx.notify();
        }
    }
    
    impl Render for SwapCardPattern {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            self.from_cell.set(self.from);
            let form = self.form(window, cx);
            self.amount_form = Some(form.clone());
            let input = form.input(field!(amount), window, cx, |input| input.placeholder("0").bare().font_size(px(24.0)));
            let theme = cx.theme().clone();
            let (from, to) = (&TOKENS[self.from], &TOKENS[self.to]);
    
            let f = form.read(cx);
            let parsed = parse_units(&f.values().amount, from.decimals);
            let amount_in = parsed.unwrap_or(0);
            let quote = (amount_in > 0).then(|| quote(amount_in, from, to, self.slippage_bps)).flatten();
            // The form shows errors only after the user typed; the button needs them before that too.
            let problem: Option<SharedString> = match parsed {
                Err(AmountError::Empty) | Ok(0) => Some("Enter an amount".into()),
                Ok(units) if units > from.balance => Some(format!("Insufficient {} balance", from.symbol).into()),
                _ => f.error("amount").or_else(|| quote.is_none().then(|| "No quote for this amount".into())),
            };
    
            let settings = Popover::new("swap-settings", self.settings_open)
                .align(Align::End)
                .width(px(260.0))
                .trigger(
                    Button::new("settings", "")
                        .variant(ButtonVariant::Ghost)
                        .size(ButtonSize::Sm)
                        .icon_only()
                        .leading(icon(SETTINGS_2).size(px(16.0)).text_color(theme.muted_foreground)),
                )
                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                    this.settings_open = *open;
                    cx.notify();
                }))
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .gap_3()
                        .child(
                            div()
                                .flex()
                                .flex_col()
                                .gap_1()
                                .child(div().text_sm().font_weight(FontWeight::MEDIUM).child("Max slippage"))
                                .child(div().text_xs().text_color(theme.muted_foreground).child(
                                    "The swap reverts if the price moves against you by more than this.",
                                )),
                        )
                        .child(
                            SLIPPAGE_PRESETS.iter().fold(
                                ToggleGroup::new("slippage", ToggleGroupMode::Single)
                                    .selected(SLIPPAGE_PRESETS.iter().position(|&bps| bps == self.slippage_bps))
                                    .on_change(cx.listener(|this, selected: &Vec<usize>, _, cx| {
                                        // Pressing the active preset would clear it; keep the last choice instead.
                                        if let Some(&ix) = selected.first() {
                                            this.slippage_bps = SLIPPAGE_PRESETS[ix];
                                            cx.notify();
                                        }
                                    })),
                                |group, &bps| group.item(format_bps(bps)),
                            ),
                        ),
                );
    
            let header = div()
                .flex()
                .items_center()
                .justify_between()
                .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Swap"))
                .child(settings);
    
            let pay_value = usd_cents(amount_in, from.decimals, from.price_e8).unwrap_or(0);
            let max = {
                let form = form.clone();
                let (balance, decimals) = (from.balance, from.decimals);
                move |_: &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 pay = panel(
                "You pay",
                div().flex_1().min_w_0().child(input).into_any_element(),
                self.token_menu(Side::From, cx),
                format_usd_cents(pay_value),
                div()
                    .flex()
                    .items_center()
                    .gap_1()
                    .child(format!("{} {}", format_amount(from.balance, from.decimals, 4), from.symbol))
                    .child(
                        Button::new("max", "Max").variant(ButtonVariant::Ghost).size(ButtonSize::Xs).on_click(max),
                    )
                    .into_any_element(),
                theme.muted,
                theme.muted_foreground,
            );
    
            let out = quote.as_ref().map_or(0, |q| q.amount_out);
            let receive_value = usd_cents(out, to.decimals, to.price_e8).unwrap_or(0);
            let receive = panel(
                "You receive",
                div()
                    .flex_1()
                    .min_w_0()
                    .text_2xl()
                    .truncate()
                    .text_color(if out == 0 { theme.muted_foreground } else { theme.foreground })
                    .child(format_amount(out, to.decimals, 6))
                    .into_any_element(),
                self.token_menu(Side::To, cx),
                format_usd_cents(receive_value),
                div()
                    .child(format!("{} {}", format_amount(to.balance, to.decimals, 4), to.symbol))
                    .into_any_element(),
                theme.muted,
                theme.muted_foreground,
            );
    
            let flip = div().h_0().flex().justify_center().relative().child(
                div()
                    .id("flip")
                    .absolute()
                    .top(px(-20.0))
                    .size(px(40.0))
                    .flex()
                    .items_center()
                    .justify_center()
                    .rounded(theme.radius)
                    .border_4()
                    .border_color(theme.card)
                    .bg(theme.muted)
                    .cursor_pointer()
                    .hover(|style| style.bg(theme.accent))
                    .on_click(cx.listener(|this, _, _, cx| {
                        std::mem::swap(&mut this.from, &mut this.to);
                        this.revalidate(cx);
                        cx.notify();
                    }))
                    .child(icon(ARROW_UP_DOWN).size(px(16.0)).text_color(theme.foreground)),
            );
    
            let row = |label: &'static str, value: String, color: Hsla| {
                div()
                    .flex()
                    .justify_between()
                    .text_xs()
                    .child(div().text_color(theme.muted_foreground).child(label))
                    .child(div().text_color(color).child(value))
            };
            let details = quote.as_ref().map(|q| {
                let rate = rate(from, to);
                let impact = if q.impact_bps == 0 { "<0.01%".to_string() } else { format_bps(q.impact_bps) };
                let impact_color = if q.impact_bps > HIGH_IMPACT_BPS { theme.destructive } else { theme.foreground };
                div()
                    .flex()
                    .flex_col()
                    .gap_1p5()
                    .px_1()
                    .child(row("Rate", rate, theme.foreground))
                    .child(row("Price impact", impact, impact_color))
                    .child(row(
                        "Minimum received",
                        format!("{} {}", format_amount(q.min_out, to.decimals, 6), to.symbol),
                        theme.foreground,
                    ))
                    .child(row("Max slippage", format_bps(self.slippage_bps), theme.foreground))
            });
    
            let swap = Button::new("swap", problem.clone().unwrap_or_else(|| "Swap".into()))
                .size(ButtonSize::Lg)
                .disabled(problem.is_some())
                .on_click({
                    let (from_symbol, to_symbol) = (from.symbol, to.symbol);
                    let summary = quote.as_ref().map(|q| {
                        format!(
                            "{} {from_symbol} for at least {} {to_symbol}",
                            format_units(amount_in, from.decimals),
                            format_units(q.min_out, to.decimals)
                        )
                    });
                    move |_, _, cx| {
                        // The host sends the swap with `amount_in` and `min_out` in base units.
                        if let Some(summary) = &summary {
                            toast(Toast::new("Swap submitted").description(summary.clone()), cx);
                        }
                    }
                });
    
            div()
                .w(px(400.0))
                .flex()
                .flex_col()
                .gap_3()
                .p_4()
                .rounded(theme.radius * 2.0)
                .border_1()
                .border_color(theme.border)
                .bg(theme.card)
                .child(header)
                .child(div().flex().flex_col().gap_1().child(pay).child(flip).child(receive))
                .children(details)
                .child(div().w_full().flex().flex_col().child(swap))
                .child(Toaster::new())
        }
    }
    
    impl SwapCardPattern {
        fn token_menu(&self, side: Side, cx: &mut Context<Self>) -> gpui::AnyElement {
            let theme = cx.theme();
            let current = match side {
                Side::From => self.from,
                Side::To => self.to,
            };
            let token = &TOKENS[current];
            let id = match side {
                Side::From => "from-token",
                Side::To => "to-token",
            };
            TOKENS
                .iter()
                .enumerate()
                .fold(
                    DropdownMenu::new(id, self.menu_open == Some(side))
                        .align(Align::End)
                        .trigger(
                            Button::new((id, 0usize), 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)),
                        )
                        .on_open_change(cx.listener(move |this, open: &bool, _, cx| {
                            this.menu_open = open.then_some(side);
                            cx.notify();
                        })),
                    |menu, (ix, token)| {
                        menu.item(
                            MenuItem::new(token.symbol)
                                .radio(ix == current)
                                .on_select(cx.listener(move |this, _: &ClickEvent, _, cx| this.pick(side, ix, cx))),
                        )
                    },
                )
                .into_any_element()
        }
    }
    
    /// `1 ETH = 3,000 USDC`, from the sample prices.
    fn rate(from: &Token, to: &Token) -> String {
        let one = pow10(from.decimals).unwrap_or(1);
        let out = convert(one, from.decimals, from.price_e8, to.decimals, to.price_e8).unwrap_or(0);
        format!("1 {} = {} {}", from.symbol, format_amount(out, to.decimals, 6), to.symbol)
    }
    
    /// One side of the swap: a label, the amount, the token, and a line of value and balance.
    fn panel(
        label: &'static str,
        amount: gpui::AnyElement,
        token: gpui::AnyElement,
        value: String,
        balance: gpui::AnyElement,
        bg: Hsla,
        muted: Hsla,
    ) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .gap_1()
            .p_4()
            .rounded_lg()
            .bg(bg)
            .child(div().text_xs().text_color(muted).child(label))
            .child(div().flex().items_center().gap_3().h(px(40.0)).child(amount).child(token))
            .child(div().flex().items_center().justify_between().text_xs().text_color(muted).child(value).child(balance))
    }
    
    /// A token's stand-in logo: its first letter on a round tile.
    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))
    }