hyuskui

Approve Then Swap

The two transactions a token swap can need, as numbered steps: approve the router to spend exactly the amount (or, by choice, an unlimited allowance), then swap. A step waits on the wallet, then on the network, before the next one unlocks. Enough allowance skips step one.

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

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

use crate::icons::{icon, CHECK, TRIANGLE_ALERT};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::onchain::{format_amount, Address};
use crate::ui::spinner::{Spinner, SpinnerSize};
use crate::ui::switch::Switch;

/// Sample swap: 500 USDC (6 decimals) through a fake router address.
const AMOUNT: u128 = 500_000_000;
const DECIMALS: u8 = 6;
const SYMBOL: &str = "USDC";
const ROUTER: &str = "0x000000000000000000000000000000000000c0DE";
/// What the router may already spend, in base units. Less than `AMOUNT`, so approval is needed.
const CURRENT_ALLOWANCE: u128 = 120_000_000;

/// How long the demo's wallet prompt and block take. A real app waits on each.
const WALLET: Duration = Duration::from_millis(900);
const BLOCK: Duration = Duration::from_millis(1300);

#[derive(Clone, Copy, Default, PartialEq)]
enum Step {
    #[default]
    Ready,
    /// The wallet is showing the request.
    InWallet,
    /// Sent; waiting for it to be mined.
    Pending,
    Done,
}

#[derive(Default)]
pub struct ApproveSwapPattern {
    approve: Step,
    swap: Step,
    unlimited: bool,
    task: Option<Task<()>>,
}

impl ApproveSwapPattern {
    fn needs_approval(&self) -> bool {
        CURRENT_ALLOWANCE < AMOUNT
    }

    /// Runs one step through the wallet and the network. The host sends the transaction where
    /// the demo waits, and moves on from the wallet's answer and the receipt.
    fn run(&mut self, approve: bool, cx: &mut Context<Self>) {
        self.set(approve, Step::InWallet);
        self.task = Some(cx.spawn(async move |this, cx| {
            cx.background_executor().timer(WALLET).await;
            if this.update(cx, |this, cx| { this.set(approve, Step::Pending); cx.notify(); }).is_err() {
                return;
            }
            cx.background_executor().timer(BLOCK).await;
            this.update(cx, |this, cx| {
                this.set(approve, Step::Done);
                cx.notify();
            })
            .ok();
        }));
        cx.notify();
    }

    fn set(&mut self, approve: bool, step: Step) {
        if approve {
            self.approve = step;
        } else {
            self.swap = step;
        }
    }
}

impl Render for ApproveSwapPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme().clone();
        let (router, spender) = Address::parse(ROUTER)
            .map(|a| (a.short(), a.to_string()))
            .unwrap_or_default();
        let amount = format!("{} {SYMBOL}", format_amount(AMOUNT, DECIMALS, 2));
        let approved = !self.needs_approval() || self.approve == Step::Done;
        let busy = matches!(self.approve, Step::InWallet | Step::Pending) || matches!(self.swap, Step::InWallet | Step::Pending);

        let marker = |number: usize, step: Step, active: bool| -> AnyElement {
            let base = div().flex_none().size(px(28.0)).rounded_full().flex().items_center().justify_center();
            match step {
                Step::Done => base
                    .bg(theme.primary)
                    .child(icon(CHECK).size(px(14.0)).text_color(theme.primary_foreground))
                    .into_any_element(),
                Step::InWallet | Step::Pending => {
                    base.border_1().border_color(theme.border).child(Spinner::new().size(SpinnerSize::Sm)).into_any_element()
                }
                Step::Ready => base
                    .border_1()
                    .border_color(if active { theme.foreground } else { theme.border })
                    .text_xs()
                    .font_weight(FontWeight::SEMIBOLD)
                    .text_color(if active { theme.foreground } else { theme.muted_foreground })
                    .child(number.to_string())
                    .into_any_element(),
            }
        };
        let status = |step: Step, ready: &'static str, done: SharedString| -> SharedString {
            match step {
                Step::Ready => ready.into(),
                Step::InWallet => "Confirm in your wallet\u{2026}".into(),
                Step::Pending => "Waiting for the network\u{2026}".into(),
                Step::Done => done,
            }
        };

        let approve_limit = if self.unlimited {
            format!("Unlimited {SYMBOL}")
        } else {
            amount.clone()
        };
        let step_one = div()
            .flex()
            .gap_3()
            .child(marker(1, self.approve, !approved))
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .flex()
                    .flex_col()
                    .gap_1()
                    .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(format!("Approve {SYMBOL}")))
                    .child(div().text_xs().text_color(theme.muted_foreground).child(status(
                        self.approve,
                        "Lets the router spend your tokens for this swap.",
                        format!("Approved {approve_limit} for {router}").into(),
                    )))
                    .when(self.approve == Step::Ready, |this| {
                        this.child(
                            div()
                                .flex()
                                .flex_col()
                                .gap_2()
                                .pt_2()
                                .child(
                                    div()
                                        .flex()
                                        .justify_between()
                                        .text_xs()
                                        .child(div().text_color(theme.muted_foreground).child("Current allowance"))
                                        .child(format!("{} {SYMBOL}", format_amount(CURRENT_ALLOWANCE, DECIMALS, 2))),
                                )
                                // The user is deciding whom to trust, so the spender shows in full.
                                .child(
                                    div()
                                        .flex()
                                        .flex_col()
                                        .gap_0p5()
                                        .text_xs()
                                        .child(div().text_color(theme.muted_foreground).child("Spender (router)"))
                                        .child(div().font_family("Geist Mono").child(spender.clone())),
                                )
                                .child(
                                    div().w_full().child(Switch::new("unlimited", self.unlimited)
                                        .label("Unlimited approval")
                                        .description("Skips this step next time, but the router can spend any amount.")
                                        .on_toggle(cx.listener(|this, on: &bool, _, cx| {
                                            this.unlimited = *on;
                                            cx.notify();
                                        }))),
                                )
                                .when(self.unlimited, |this| {
                                    this.child(
                                        div()
                                            .flex()
                                            .items_center()
                                            .gap_1p5()
                                            .text_xs()
                                            .text_color(theme.destructive)
                                            .child(icon(TRIANGLE_ALERT).size(px(12.0)).text_color(theme.destructive))
                                            .child("Only approve unlimited for contracts you trust."),
                                    )
                                })
                                .child(
                                    div().pt_1().flex().child(
                                        Button::new("approve", format!("Approve {approve_limit}"))
                                            .disabled(busy)
                                            .on_click(cx.listener(|this, _, _, cx| this.run(true, cx))),
                                    ),
                                ),
                        )
                    }),
            );

        let step_two = div()
            .flex()
            .gap_3()
            .child(marker(2, self.swap, approved))
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .flex()
                    .flex_col()
                    .gap_1()
                    .when(!approved, |this| this.opacity(0.5))
                    .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(format!("Swap {amount} for ETH")))
                    .child(div().text_xs().text_color(theme.muted_foreground).child(status(
                        self.swap,
                        if approved { "Ready to swap." } else { "Unlocks after the approval confirms." },
                        "Swapped. The ETH is in your wallet.".into(),
                    )))
                    .when(self.swap == Step::Ready, |this| {
                        this.child(
                            div().pt_2().flex().child(
                                Button::new("swap", "Swap")
                                    .disabled(!approved || busy)
                                    .on_click(cx.listener(|this, _, _, cx| this.run(false, cx))),
                            ),
                        )
                    }),
            );

        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()
                    .items_center()
                    .justify_between()
                    .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Swap in two steps"))
                    .when(self.swap == Step::Done, |this| {
                        this.child(
                            Button::new("reset", "Start over")
                                .variant(ButtonVariant::Ghost)
                                .on_click(cx.listener(|this, _, _, cx| {
                                    *this = Self::default();
                                    cx.notify();
                                })),
                        )
                    }),
            )
            .child(step_one)
            .child(div().ml(px(13.5)).w_px().h(px(12.0)).bg(theme.border))
            .child(step_two)
            .child(div().text_xs().text_color(theme.muted_foreground).child("Sample amounts and a fake router address."))
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add button onchain spinner switch icons

    Uses Button, Onchain, Spinner and Switch.

  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/approve_swap.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/approve_swap.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, AnyElement, Context, FontWeight, SharedString, Task, Window};
    
    use crate::icons::{icon, CHECK, TRIANGLE_ALERT};
    use crate::theme::ActiveTheme;
    use crate::ui::button::{Button, ButtonVariant};
    use crate::ui::onchain::{format_amount, Address};
    use crate::ui::spinner::{Spinner, SpinnerSize};
    use crate::ui::switch::Switch;
    
    /// Sample swap: 500 USDC (6 decimals) through a fake router address.
    const AMOUNT: u128 = 500_000_000;
    const DECIMALS: u8 = 6;
    const SYMBOL: &str = "USDC";
    const ROUTER: &str = "0x000000000000000000000000000000000000c0DE";
    /// What the router may already spend, in base units. Less than `AMOUNT`, so approval is needed.
    const CURRENT_ALLOWANCE: u128 = 120_000_000;
    
    /// How long the demo's wallet prompt and block take. A real app waits on each.
    const WALLET: Duration = Duration::from_millis(900);
    const BLOCK: Duration = Duration::from_millis(1300);
    
    #[derive(Clone, Copy, Default, PartialEq)]
    enum Step {
        #[default]
        Ready,
        /// The wallet is showing the request.
        InWallet,
        /// Sent; waiting for it to be mined.
        Pending,
        Done,
    }
    
    #[derive(Default)]
    pub struct ApproveSwapPattern {
        approve: Step,
        swap: Step,
        unlimited: bool,
        task: Option<Task<()>>,
    }
    
    impl ApproveSwapPattern {
        fn needs_approval(&self) -> bool {
            CURRENT_ALLOWANCE < AMOUNT
        }
    
        /// Runs one step through the wallet and the network. The host sends the transaction where
        /// the demo waits, and moves on from the wallet's answer and the receipt.
        fn run(&mut self, approve: bool, cx: &mut Context<Self>) {
            self.set(approve, Step::InWallet);
            self.task = Some(cx.spawn(async move |this, cx| {
                cx.background_executor().timer(WALLET).await;
                if this.update(cx, |this, cx| { this.set(approve, Step::Pending); cx.notify(); }).is_err() {
                    return;
                }
                cx.background_executor().timer(BLOCK).await;
                this.update(cx, |this, cx| {
                    this.set(approve, Step::Done);
                    cx.notify();
                })
                .ok();
            }));
            cx.notify();
        }
    
        fn set(&mut self, approve: bool, step: Step) {
            if approve {
                self.approve = step;
            } else {
                self.swap = step;
            }
        }
    }
    
    impl Render for ApproveSwapPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme().clone();
            let (router, spender) = Address::parse(ROUTER)
                .map(|a| (a.short(), a.to_string()))
                .unwrap_or_default();
            let amount = format!("{} {SYMBOL}", format_amount(AMOUNT, DECIMALS, 2));
            let approved = !self.needs_approval() || self.approve == Step::Done;
            let busy = matches!(self.approve, Step::InWallet | Step::Pending) || matches!(self.swap, Step::InWallet | Step::Pending);
    
            let marker = |number: usize, step: Step, active: bool| -> AnyElement {
                let base = div().flex_none().size(px(28.0)).rounded_full().flex().items_center().justify_center();
                match step {
                    Step::Done => base
                        .bg(theme.primary)
                        .child(icon(CHECK).size(px(14.0)).text_color(theme.primary_foreground))
                        .into_any_element(),
                    Step::InWallet | Step::Pending => {
                        base.border_1().border_color(theme.border).child(Spinner::new().size(SpinnerSize::Sm)).into_any_element()
                    }
                    Step::Ready => base
                        .border_1()
                        .border_color(if active { theme.foreground } else { theme.border })
                        .text_xs()
                        .font_weight(FontWeight::SEMIBOLD)
                        .text_color(if active { theme.foreground } else { theme.muted_foreground })
                        .child(number.to_string())
                        .into_any_element(),
                }
            };
            let status = |step: Step, ready: &'static str, done: SharedString| -> SharedString {
                match step {
                    Step::Ready => ready.into(),
                    Step::InWallet => "Confirm in your wallet\u{2026}".into(),
                    Step::Pending => "Waiting for the network\u{2026}".into(),
                    Step::Done => done,
                }
            };
    
            let approve_limit = if self.unlimited {
                format!("Unlimited {SYMBOL}")
            } else {
                amount.clone()
            };
            let step_one = div()
                .flex()
                .gap_3()
                .child(marker(1, self.approve, !approved))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .gap_1()
                        .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(format!("Approve {SYMBOL}")))
                        .child(div().text_xs().text_color(theme.muted_foreground).child(status(
                            self.approve,
                            "Lets the router spend your tokens for this swap.",
                            format!("Approved {approve_limit} for {router}").into(),
                        )))
                        .when(self.approve == Step::Ready, |this| {
                            this.child(
                                div()
                                    .flex()
                                    .flex_col()
                                    .gap_2()
                                    .pt_2()
                                    .child(
                                        div()
                                            .flex()
                                            .justify_between()
                                            .text_xs()
                                            .child(div().text_color(theme.muted_foreground).child("Current allowance"))
                                            .child(format!("{} {SYMBOL}", format_amount(CURRENT_ALLOWANCE, DECIMALS, 2))),
                                    )
                                    // The user is deciding whom to trust, so the spender shows in full.
                                    .child(
                                        div()
                                            .flex()
                                            .flex_col()
                                            .gap_0p5()
                                            .text_xs()
                                            .child(div().text_color(theme.muted_foreground).child("Spender (router)"))
                                            .child(div().font_family("Geist Mono").child(spender.clone())),
                                    )
                                    .child(
                                        div().w_full().child(Switch::new("unlimited", self.unlimited)
                                            .label("Unlimited approval")
                                            .description("Skips this step next time, but the router can spend any amount.")
                                            .on_toggle(cx.listener(|this, on: &bool, _, cx| {
                                                this.unlimited = *on;
                                                cx.notify();
                                            }))),
                                    )
                                    .when(self.unlimited, |this| {
                                        this.child(
                                            div()
                                                .flex()
                                                .items_center()
                                                .gap_1p5()
                                                .text_xs()
                                                .text_color(theme.destructive)
                                                .child(icon(TRIANGLE_ALERT).size(px(12.0)).text_color(theme.destructive))
                                                .child("Only approve unlimited for contracts you trust."),
                                        )
                                    })
                                    .child(
                                        div().pt_1().flex().child(
                                            Button::new("approve", format!("Approve {approve_limit}"))
                                                .disabled(busy)
                                                .on_click(cx.listener(|this, _, _, cx| this.run(true, cx))),
                                        ),
                                    ),
                            )
                        }),
                );
    
            let step_two = div()
                .flex()
                .gap_3()
                .child(marker(2, self.swap, approved))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .gap_1()
                        .when(!approved, |this| this.opacity(0.5))
                        .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(format!("Swap {amount} for ETH")))
                        .child(div().text_xs().text_color(theme.muted_foreground).child(status(
                            self.swap,
                            if approved { "Ready to swap." } else { "Unlocks after the approval confirms." },
                            "Swapped. The ETH is in your wallet.".into(),
                        )))
                        .when(self.swap == Step::Ready, |this| {
                            this.child(
                                div().pt_2().flex().child(
                                    Button::new("swap", "Swap")
                                        .disabled(!approved || busy)
                                        .on_click(cx.listener(|this, _, _, cx| this.run(false, cx))),
                                ),
                            )
                        }),
                );
    
            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()
                        .items_center()
                        .justify_between()
                        .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Swap in two steps"))
                        .when(self.swap == Step::Done, |this| {
                            this.child(
                                Button::new("reset", "Start over")
                                    .variant(ButtonVariant::Ghost)
                                    .on_click(cx.listener(|this, _, _, cx| {
                                        *this = Self::default();
                                        cx.notify();
                                    })),
                            )
                        }),
                )
                .child(step_one)
                .child(div().ml(px(13.5)).w_px().h(px(12.0)).bg(theme.border))
                .child(step_two)
                .child(div().text_xs().text_color(theme.muted_foreground).child("Sample amounts and a fake router address."))
        }
    }