hyuskui

Vault Deposit

A staking or vault card: APY, deposit and withdraw tabs, an amount checked against the wallet or the position, and a preview of the shares minted or assets returned, rounded down the way ERC-4626 vaults round.

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

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

use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::badge::{Badge, BadgeVariant};
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, format_usd_cents, parse_units, preview_deposit, preview_redeem,
    preview_withdraw, usd_cents, AmountError,
};
use crate::ui::tabs::Tabs;
use crate::ui::toast::{toast, Toast, ToastKind, Toaster};

/// Sample vault state. ETH has 18 decimals and so do the vault's shares.
const DECIMALS: u8 = 18;
const ETH_PRICE_E8: u128 = 300_000_000_000;
const APY_BPS: u128 = 420;
const TOTAL_ASSETS: u128 = 1_250_000_000_000_000_000_000;
const TOTAL_SHARES: u128 = 1_200_000_000_000_000_000_000;
const WALLET_BALANCE: u128 = 1_234_567_890_123_456_789;
const USER_SHARES: u128 = 2_000_000_000_000_000_000;

const DEPOSIT: usize = 0;

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

/// What the amount is checked against: the wallet when depositing, the position's assets when
/// withdrawing.
fn limit(tab: usize) -> u128 {
    if tab == DEPOSIT {
        WALLET_BALANCE
    } else {
        preview_redeem(USER_SHARES, TOTAL_ASSETS, TOTAL_SHARES).unwrap_or(0)
    }
}

fn schema(tab: Rc<Cell<usize>>) -> Schema<AmountForm> {
    let rule = move |test: fn(Result<u128, AmountError>, u128) -> bool| {
        let tab = tab.clone();
        move |v: &AmountForm| test(parse_units(&v.amount, DECIMALS), limit(tab.get()))
    };
    Schema::<AmountForm>::new()
        .refine("amount", rule(|p, _| p != Err(AmountError::Empty) && p != Ok(0)), "Enter an amount.")
        .refine("amount", rule(|p, _| p != Err(AmountError::Invalid)), "Use digits and one decimal point.")
        .refine("amount", rule(|p, _| !matches!(p, Err(AmountError::TooManyDecimals { .. }))), "ETH has 18 decimal places.")
        .refine("amount", rule(|p, _| p != Err(AmountError::Overflow)), "Amount is too large.")
        .refine("amount", rule(|p, limit| p.map_or(true, |units| units <= limit)), "More than you have.")
}

pub struct VaultDepositPattern {
    tab: usize,
    tab_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<AmountForm>>>,
}

impl Default for VaultDepositPattern {
    fn default() -> Self {
        Self { tab: DEPOSIT, tab_cell: Rc::new(Cell::new(DEPOSIT)), amount_form: None }
    }
}

impl VaultDepositPattern {
    fn form(&self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Form<AmountForm>> {
        let tab = self.tab_cell.clone();
        window.use_keyed_state("vault-form", cx, |_, _| {
            Form::new(AmountForm::default()).schema(schema(tab)).mode(Mode::OnChange)
        })
    }
}

impl Render for VaultDepositPattern {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.tab_cell.set(self.tab);
        let form = self.form(window, cx);
        self.amount_form = Some(form.clone());
        let input = form.input(field!(amount), window, cx, |input| input.placeholder("0.0").bare());
        let theme = cx.theme().clone();
        let f = form.read(cx);
        let depositing = self.tab == DEPOSIT;
        let units = parse_units(&f.values().amount, DECIMALS).ok().filter(|&u| u > 0);
        let limit = limit(self.tab);

        // Deposit previews shares minted, rounded down; withdraw previews shares burned, rounded up.
        let shares = units.and_then(|u| {
            if depositing {
                preview_deposit(u, TOTAL_ASSETS, TOTAL_SHARES)
            } else {
                preview_withdraw(u, TOTAL_ASSETS, TOTAL_SHARES)
            }
        });
        let one_share = preview_redeem(10u128.pow(DECIMALS as u32), TOTAL_ASSETS, TOTAL_SHARES).unwrap_or(0);
        let position = preview_redeem(USER_SHARES, TOTAL_ASSETS, TOTAL_SHARES).unwrap_or(0);
        let yearly = units.and_then(|u| u.checked_mul(APY_BPS)).map(|u| u / 10_000);

        let stat = |label: &'static str, value: String| {
            div()
                .flex_1()
                .flex()
                .flex_col()
                .gap_0p5()
                .child(div().text_xs().text_color(theme.muted_foreground).child(label))
                .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child(value))
        };
        let row = |label: &'static str, value: String| {
            div()
                .flex()
                .justify_between()
                .text_sm()
                .child(div().text_color(theme.muted_foreground).child(label))
                .child(value)
        };
        let max = {
            let form = form.clone();
            move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut gpui::App| {
                // The exact limit, so the amount parses back to it.
                let amount = format_units(limit, DECIMALS);
                form.update(cx, |form, cx| form.set_value(&field!(amount), amount, window, cx));
            }
        };
        let action: SharedString = if depositing { "Deposit".into() } else { "Withdraw".into() };

        div()
            .w(px(400.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()
                    .items_center()
                    .gap_3()
                    .child(Avatar::new("E").size(AvatarSize::Lg))
                    .child(
                        div()
                            .flex_1()
                            .flex()
                            .flex_col()
                            .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Sample ETH Vault"))
                            .child(div().text_xs().text_color(theme.muted_foreground).child("Sample data. Shares: vSMPL")),
                    )
                    .child(Badge::new(format!("{} APY", format_bps(APY_BPS))).variant(BadgeVariant::Secondary)),
            )
            .child(
                div()
                    .flex()
                    .gap_4()
                    .child(stat("Total deposited", format!("{} ETH", format_amount(TOTAL_ASSETS, DECIMALS, 0))))
                    .child(stat("Your position", format!("{} ETH", format_amount(position, DECIMALS, 4)))),
            )
            .child(
                Tabs::new("vault-tab", self.tab).tab("Deposit").tab("Withdraw").on_select(cx.listener(
                    |this, ix: &usize, window, cx| {
                        this.tab = *ix;
                        this.tab_cell.set(*ix);
                        if let Some(form) = this.amount_form.clone() {
                            form.update(cx, |form, cx| form.reset(window, cx));
                        }
                        cx.notify();
                    },
                )),
            )
            .child(
                f.field("amount").label(if depositing { "Amount to deposit" } else { "Amount to withdraw" }).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("ETH")),
                ),
            )
            .child(
                div()
                    .flex()
                    .flex_col()
                    .gap_2()
                    .child(row(
                        if depositing { "Wallet balance" } else { "Withdrawable" },
                        format!("{} ETH", format_amount(limit, DECIMALS, 4)),
                    ))
                    .child(row(
                        if depositing { "You receive" } else { "Shares burned" },
                        format!("{} vSMPL", shares.map_or("0".into(), |s| format_amount(s, DECIMALS, 6))),
                    ))
                    .child(row("Share price", format!("1 vSMPL = {} ETH", format_amount(one_share, DECIMALS, 6))))
                    .when(depositing, |this| {
                        this.child(row(
                            "Est. yearly yield",
                            yearly.map_or("$0.00".into(), |y| {
                                format!(
                                    "{} ETH ({})",
                                    format_amount(y, DECIMALS, 4),
                                    format_usd_cents(usd_cents(y, DECIMALS, ETH_PRICE_E8).unwrap_or(0))
                                )
                            }),
                        ))
                    }),
            )
            .child(
                div().flex().flex_col().child(
                    Button::new("vault-submit", action.clone()).size(ButtonSize::Lg).on_click(form.handle_submit_with(
                        move |values, _, cx| {
                            if let Ok(units) = parse_units(&values.amount, DECIMALS) {
                                // The host calls the vault's deposit or withdraw with `units`.
                                toast(
                                    Toast::new(format!("{action} submitted"))
                                        .kind(ToastKind::Success)
                                        .description(format!("{} ETH", format_units(units, DECIMALS))),
                                    cx,
                                );
                            }
                        },
                        |_, _, _| {},
                    )),
                ),
            )
            .child(Toaster::new())
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add avatar badge button form input-group onchain tabs toast

    Uses Avatar, Badge, Button, Form, Input Group, Onchain, Tabs 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/vault_deposit.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/vault_deposit.rs
    use std::{cell::Cell, rc::Rc};
    
    use gpui::{div, prelude::*, px, Context, Entity, FontWeight, SharedString, Window};
    
    use crate::theme::ActiveTheme;
    use crate::ui::avatar::{Avatar, AvatarSize};
    use crate::ui::badge::{Badge, BadgeVariant};
    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, format_usd_cents, parse_units, preview_deposit, preview_redeem,
        preview_withdraw, usd_cents, AmountError,
    };
    use crate::ui::tabs::Tabs;
    use crate::ui::toast::{toast, Toast, ToastKind, Toaster};
    
    /// Sample vault state. ETH has 18 decimals and so do the vault's shares.
    const DECIMALS: u8 = 18;
    const ETH_PRICE_E8: u128 = 300_000_000_000;
    const APY_BPS: u128 = 420;
    const TOTAL_ASSETS: u128 = 1_250_000_000_000_000_000_000;
    const TOTAL_SHARES: u128 = 1_200_000_000_000_000_000_000;
    const WALLET_BALANCE: u128 = 1_234_567_890_123_456_789;
    const USER_SHARES: u128 = 2_000_000_000_000_000_000;
    
    const DEPOSIT: usize = 0;
    
    #[derive(Clone, Default, Debug, PartialEq)]
    struct AmountForm {
        amount: String,
    }
    
    /// What the amount is checked against: the wallet when depositing, the position's assets when
    /// withdrawing.
    fn limit(tab: usize) -> u128 {
        if tab == DEPOSIT {
            WALLET_BALANCE
        } else {
            preview_redeem(USER_SHARES, TOTAL_ASSETS, TOTAL_SHARES).unwrap_or(0)
        }
    }
    
    fn schema(tab: Rc<Cell<usize>>) -> Schema<AmountForm> {
        let rule = move |test: fn(Result<u128, AmountError>, u128) -> bool| {
            let tab = tab.clone();
            move |v: &AmountForm| test(parse_units(&v.amount, DECIMALS), limit(tab.get()))
        };
        Schema::<AmountForm>::new()
            .refine("amount", rule(|p, _| p != Err(AmountError::Empty) && p != Ok(0)), "Enter an amount.")
            .refine("amount", rule(|p, _| p != Err(AmountError::Invalid)), "Use digits and one decimal point.")
            .refine("amount", rule(|p, _| !matches!(p, Err(AmountError::TooManyDecimals { .. }))), "ETH has 18 decimal places.")
            .refine("amount", rule(|p, _| p != Err(AmountError::Overflow)), "Amount is too large.")
            .refine("amount", rule(|p, limit| p.map_or(true, |units| units <= limit)), "More than you have.")
    }
    
    pub struct VaultDepositPattern {
        tab: usize,
        tab_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<AmountForm>>>,
    }
    
    impl Default for VaultDepositPattern {
        fn default() -> Self {
            Self { tab: DEPOSIT, tab_cell: Rc::new(Cell::new(DEPOSIT)), amount_form: None }
        }
    }
    
    impl VaultDepositPattern {
        fn form(&self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Form<AmountForm>> {
            let tab = self.tab_cell.clone();
            window.use_keyed_state("vault-form", cx, |_, _| {
                Form::new(AmountForm::default()).schema(schema(tab)).mode(Mode::OnChange)
            })
        }
    }
    
    impl Render for VaultDepositPattern {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            self.tab_cell.set(self.tab);
            let form = self.form(window, cx);
            self.amount_form = Some(form.clone());
            let input = form.input(field!(amount), window, cx, |input| input.placeholder("0.0").bare());
            let theme = cx.theme().clone();
            let f = form.read(cx);
            let depositing = self.tab == DEPOSIT;
            let units = parse_units(&f.values().amount, DECIMALS).ok().filter(|&u| u > 0);
            let limit = limit(self.tab);
    
            // Deposit previews shares minted, rounded down; withdraw previews shares burned, rounded up.
            let shares = units.and_then(|u| {
                if depositing {
                    preview_deposit(u, TOTAL_ASSETS, TOTAL_SHARES)
                } else {
                    preview_withdraw(u, TOTAL_ASSETS, TOTAL_SHARES)
                }
            });
            let one_share = preview_redeem(10u128.pow(DECIMALS as u32), TOTAL_ASSETS, TOTAL_SHARES).unwrap_or(0);
            let position = preview_redeem(USER_SHARES, TOTAL_ASSETS, TOTAL_SHARES).unwrap_or(0);
            let yearly = units.and_then(|u| u.checked_mul(APY_BPS)).map(|u| u / 10_000);
    
            let stat = |label: &'static str, value: String| {
                div()
                    .flex_1()
                    .flex()
                    .flex_col()
                    .gap_0p5()
                    .child(div().text_xs().text_color(theme.muted_foreground).child(label))
                    .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child(value))
            };
            let row = |label: &'static str, value: String| {
                div()
                    .flex()
                    .justify_between()
                    .text_sm()
                    .child(div().text_color(theme.muted_foreground).child(label))
                    .child(value)
            };
            let max = {
                let form = form.clone();
                move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut gpui::App| {
                    // The exact limit, so the amount parses back to it.
                    let amount = format_units(limit, DECIMALS);
                    form.update(cx, |form, cx| form.set_value(&field!(amount), amount, window, cx));
                }
            };
            let action: SharedString = if depositing { "Deposit".into() } else { "Withdraw".into() };
    
            div()
                .w(px(400.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()
                        .items_center()
                        .gap_3()
                        .child(Avatar::new("E").size(AvatarSize::Lg))
                        .child(
                            div()
                                .flex_1()
                                .flex()
                                .flex_col()
                                .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Sample ETH Vault"))
                                .child(div().text_xs().text_color(theme.muted_foreground).child("Sample data. Shares: vSMPL")),
                        )
                        .child(Badge::new(format!("{} APY", format_bps(APY_BPS))).variant(BadgeVariant::Secondary)),
                )
                .child(
                    div()
                        .flex()
                        .gap_4()
                        .child(stat("Total deposited", format!("{} ETH", format_amount(TOTAL_ASSETS, DECIMALS, 0))))
                        .child(stat("Your position", format!("{} ETH", format_amount(position, DECIMALS, 4)))),
                )
                .child(
                    Tabs::new("vault-tab", self.tab).tab("Deposit").tab("Withdraw").on_select(cx.listener(
                        |this, ix: &usize, window, cx| {
                            this.tab = *ix;
                            this.tab_cell.set(*ix);
                            if let Some(form) = this.amount_form.clone() {
                                form.update(cx, |form, cx| form.reset(window, cx));
                            }
                            cx.notify();
                        },
                    )),
                )
                .child(
                    f.field("amount").label(if depositing { "Amount to deposit" } else { "Amount to withdraw" }).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("ETH")),
                    ),
                )
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .gap_2()
                        .child(row(
                            if depositing { "Wallet balance" } else { "Withdrawable" },
                            format!("{} ETH", format_amount(limit, DECIMALS, 4)),
                        ))
                        .child(row(
                            if depositing { "You receive" } else { "Shares burned" },
                            format!("{} vSMPL", shares.map_or("0".into(), |s| format_amount(s, DECIMALS, 6))),
                        ))
                        .child(row("Share price", format!("1 vSMPL = {} ETH", format_amount(one_share, DECIMALS, 6))))
                        .when(depositing, |this| {
                            this.child(row(
                                "Est. yearly yield",
                                yearly.map_or("$0.00".into(), |y| {
                                    format!(
                                        "{} ETH ({})",
                                        format_amount(y, DECIMALS, 4),
                                        format_usd_cents(usd_cents(y, DECIMALS, ETH_PRICE_E8).unwrap_or(0))
                                    )
                                }),
                            ))
                        }),
                )
                .child(
                    div().flex().flex_col().child(
                        Button::new("vault-submit", action.clone()).size(ButtonSize::Lg).on_click(form.handle_submit_with(
                            move |values, _, cx| {
                                if let Ok(units) = parse_units(&values.amount, DECIMALS) {
                                    // The host calls the vault's deposit or withdraw with `units`.
                                    toast(
                                        Toast::new(format!("{action} submitted"))
                                            .kind(ToastKind::Success)
                                            .description(format!("{} ETH", format_units(units, DECIMALS))),
                                        cx,
                                    );
                                }
                            },
                            |_, _, _| {},
                        )),
                    ),
                )
                .child(Toaster::new())
        }
    }