A submitted transaction as pending, confirmed or failed, with its hash, confirmations and a block-explorer link, mirrored by a toast that turns from loading into success or error.
Loading GPUI…
use std::time::Duration;
use gpui::{div, prelude::*, px, AnyElement, App, Context, FontWeight, SharedString, Task, Window};
use crate::icons::{icon, ARROW_UP_RIGHT, CIRCLE_CHECK, CIRCLE_X};
use crate::theme::ActiveTheme;
use crate::ui::badge::{Badge, BadgeVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::onchain::{format_amount, truncate_middle};
use crate::ui::progress::Progress;
use crate::ui::spinner::{Spinner, SpinnerSize};
use crate::ui::toast::{toast, toast_promise, Toast, ToastKind, Toaster};
/// How long each sample confirmation takes. A real app counts blocks from its RPC node.
const BLOCK: Duration = Duration::from_millis(900);
/// Confirmations before the app treats the transaction as final.
const CONFIRMATIONS: u32 = 3;
/// Fake transaction hashes: obviously patterned, not real transactions.
const OK_HASH: &str = "0x00000000000000000000000000000000000000000000000000000000000a11ce";
const FAILED_HASH: &str = "0x0000000000000000000000000000000000000000000000000000000000000b0b";
/// The host opens its block explorer at the full hash. The demo has no explorer, so it says which
/// transaction it would open.
fn open_explorer(hash: &'static str, cx: &mut App) {
toast(Toast::new("Open in explorer").description(hash), cx);
}
#[derive(Clone, Copy, PartialEq)]
pub enum TxState {
/// In the mempool or mined with fewer than the required confirmations.
Pending { confirmations: u32 },
Confirmed { block: u128 },
Failed,
}
#[derive(Default)]
pub struct TransactionStatusPattern {
tx: Option<(TxState, &'static str, &'static str)>,
watch: Option<Task<()>>,
}
impl TransactionStatusPattern {
/// Plays a sample transaction. A real app gets the hash from the wallet and watches its
/// receipt; `fails` stands in for a receipt with status 0.
fn send(&mut self, fails: bool, cx: &mut Context<Self>) {
let (hash, label) = if fails { (FAILED_HASH, "Swap 2 ETH for USDC") } else { (OK_HASH, "Swap 1 ETH for USDC") };
self.tx = Some((TxState::Pending { confirmations: 0 }, hash, label));
let done = cx.background_executor().timer(if fails { BLOCK } else { BLOCK * (CONFIRMATIONS + 1) });
toast_promise(
Toast::new("Transaction pending").description(label),
async move {
done.await;
if fails {
Toast::new("Transaction failed")
.kind(ToastKind::Error)
.description("Reverted: price moved beyond your slippage.")
} else {
Toast::new("Transaction confirmed")
.kind(ToastKind::Success)
.description(label)
.action("View", move |_, _, cx| open_explorer(hash, cx))
}
},
cx,
);
self.watch = Some(cx.spawn(async move |this, cx| {
for confirmations in 1..=CONFIRMATIONS {
cx.background_executor().timer(BLOCK).await;
let still = this.update(cx, |this, cx| {
if let Some((state, ..)) = &mut this.tx {
*state = if fails && confirmations == 1 {
TxState::Failed
} else {
TxState::Pending { confirmations }
};
}
cx.notify();
!fails
});
if !matches!(still, Ok(true)) {
return;
}
}
cx.background_executor().timer(BLOCK).await;
this.update(cx, |this, cx| {
if let Some((state, ..)) = &mut this.tx {
*state = TxState::Confirmed { block: 1_048_576 };
}
cx.notify();
})
.ok();
}));
cx.notify();
}
}
impl Render for TransactionStatusPattern {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme().clone();
let busy = matches!(self.tx, Some((TxState::Pending { .. }, ..)));
let body: AnyElement = match self.tx {
None => div()
.py_6()
.text_center()
.text_sm()
.text_color(theme.muted_foreground)
.child("No transaction yet. Send a sample to watch it confirm.")
.into_any_element(),
Some((state, hash, label)) => {
let (status_icon, title, badge): (AnyElement, SharedString, Badge) = match state {
TxState::Pending { confirmations } => (
Spinner::new().size(SpinnerSize::Md).into_any_element(),
if confirmations == 0 { "Waiting to be included".into() } else { "Confirming".into() },
Badge::new(format!("{confirmations} of {CONFIRMATIONS}")).variant(BadgeVariant::Outline),
),
TxState::Confirmed { block } => (
icon(CIRCLE_CHECK).size(px(20.0)).text_color(theme.foreground).into_any_element(),
format!("Confirmed in block {}", format_amount(block, 0, 0)).into(),
Badge::new("Confirmed").variant(BadgeVariant::Secondary),
),
TxState::Failed => (
icon(CIRCLE_X).size(px(20.0)).text_color(theme.destructive).into_any_element(),
"Reverted: price moved beyond your slippage".into(),
Badge::new("Failed").variant(BadgeVariant::Destructive),
),
};
let progress = match state {
TxState::Pending { confirmations } => Some(confirmations as f32 / CONFIRMATIONS as f32 * 100.0),
_ => None,
};
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.flex()
.items_center()
.gap_3()
.child(div().flex_none().size(px(20.0)).flex().items_center().justify_center().child(status_icon))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(div().text_sm().font_weight(FontWeight::MEDIUM).child(label))
.child(div().text_xs().text_color(theme.muted_foreground).truncate().child(title)),
)
.child(badge),
)
.children(progress.map(|value| Progress::new(value).id("confirmations")))
.child(
div()
.flex()
.items_center()
.justify_between()
.pt_3()
.border_t_1()
.border_color(theme.border)
.child(
div()
.text_xs()
.font_family("Geist Mono")
.text_color(theme.muted_foreground)
.child(truncate_middle(hash, 10, 8)),
)
.child(
Button::new("explorer", "View on explorer")
.variant(ButtonVariant::Link)
.size(ButtonSize::Sm)
.trailing(icon(ARROW_UP_RIGHT).size(px(14.0)).text_color(theme.foreground))
.on_click(move |_, _, cx| open_explorer(hash, cx)),
),
)
.into_any_element()
}
};
div()
.w(px(420.0))
.flex()
.flex_col()
.gap_4()
.child(
div()
.p_4()
.rounded(theme.radius * 1.5)
.border_1()
.border_color(theme.border)
.bg(theme.card)
.child(body),
)
.child(
div()
.flex()
.justify_center()
.gap_2()
.child(
Button::new("send-ok", "Send sample")
.size(ButtonSize::Sm)
.disabled(busy)
.on_click(cx.listener(|this, _, _, cx| this.send(false, cx))),
)
.child(
Button::new("send-fail", "Send failing sample")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.disabled(busy)
.on_click(cx.listener(|this, _, _, cx| this.send(true, cx))),
),
)
.child(Toaster::new())
}
}Installation
Add the components
$ cargo hyuskui add badge button onchain progress spinner toast iconsAdd the crates
$ cargo add sha3@0.10onchain.rshashes addresses with Keccak-256 for their EIP-55 checksum.cargo hyuskui addruns this for you; you need it only when copying the files by hand.Copy the pattern
Paste the code into
src/crypto/transaction_status.rsand 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/transaction_status.rs use std::time::Duration; use gpui::{div, prelude::*, px, AnyElement, App, Context, FontWeight, SharedString, Task, Window}; use crate::icons::{icon, ARROW_UP_RIGHT, CIRCLE_CHECK, CIRCLE_X}; use crate::theme::ActiveTheme; use crate::ui::badge::{Badge, BadgeVariant}; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::onchain::{format_amount, truncate_middle}; use crate::ui::progress::Progress; use crate::ui::spinner::{Spinner, SpinnerSize}; use crate::ui::toast::{toast, toast_promise, Toast, ToastKind, Toaster}; /// How long each sample confirmation takes. A real app counts blocks from its RPC node. const BLOCK: Duration = Duration::from_millis(900); /// Confirmations before the app treats the transaction as final. const CONFIRMATIONS: u32 = 3; /// Fake transaction hashes: obviously patterned, not real transactions. const OK_HASH: &str = "0x00000000000000000000000000000000000000000000000000000000000a11ce"; const FAILED_HASH: &str = "0x0000000000000000000000000000000000000000000000000000000000000b0b"; /// The host opens its block explorer at the full hash. The demo has no explorer, so it says which /// transaction it would open. fn open_explorer(hash: &'static str, cx: &mut App) { toast(Toast::new("Open in explorer").description(hash), cx); } #[derive(Clone, Copy, PartialEq)] pub enum TxState { /// In the mempool or mined with fewer than the required confirmations. Pending { confirmations: u32 }, Confirmed { block: u128 }, Failed, } #[derive(Default)] pub struct TransactionStatusPattern { tx: Option<(TxState, &'static str, &'static str)>, watch: Option<Task<()>>, } impl TransactionStatusPattern { /// Plays a sample transaction. A real app gets the hash from the wallet and watches its /// receipt; `fails` stands in for a receipt with status 0. fn send(&mut self, fails: bool, cx: &mut Context<Self>) { let (hash, label) = if fails { (FAILED_HASH, "Swap 2 ETH for USDC") } else { (OK_HASH, "Swap 1 ETH for USDC") }; self.tx = Some((TxState::Pending { confirmations: 0 }, hash, label)); let done = cx.background_executor().timer(if fails { BLOCK } else { BLOCK * (CONFIRMATIONS + 1) }); toast_promise( Toast::new("Transaction pending").description(label), async move { done.await; if fails { Toast::new("Transaction failed") .kind(ToastKind::Error) .description("Reverted: price moved beyond your slippage.") } else { Toast::new("Transaction confirmed") .kind(ToastKind::Success) .description(label) .action("View", move |_, _, cx| open_explorer(hash, cx)) } }, cx, ); self.watch = Some(cx.spawn(async move |this, cx| { for confirmations in 1..=CONFIRMATIONS { cx.background_executor().timer(BLOCK).await; let still = this.update(cx, |this, cx| { if let Some((state, ..)) = &mut this.tx { *state = if fails && confirmations == 1 { TxState::Failed } else { TxState::Pending { confirmations } }; } cx.notify(); !fails }); if !matches!(still, Ok(true)) { return; } } cx.background_executor().timer(BLOCK).await; this.update(cx, |this, cx| { if let Some((state, ..)) = &mut this.tx { *state = TxState::Confirmed { block: 1_048_576 }; } cx.notify(); }) .ok(); })); cx.notify(); } } impl Render for TransactionStatusPattern { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let theme = cx.theme().clone(); let busy = matches!(self.tx, Some((TxState::Pending { .. }, ..))); let body: AnyElement = match self.tx { None => div() .py_6() .text_center() .text_sm() .text_color(theme.muted_foreground) .child("No transaction yet. Send a sample to watch it confirm.") .into_any_element(), Some((state, hash, label)) => { let (status_icon, title, badge): (AnyElement, SharedString, Badge) = match state { TxState::Pending { confirmations } => ( Spinner::new().size(SpinnerSize::Md).into_any_element(), if confirmations == 0 { "Waiting to be included".into() } else { "Confirming".into() }, Badge::new(format!("{confirmations} of {CONFIRMATIONS}")).variant(BadgeVariant::Outline), ), TxState::Confirmed { block } => ( icon(CIRCLE_CHECK).size(px(20.0)).text_color(theme.foreground).into_any_element(), format!("Confirmed in block {}", format_amount(block, 0, 0)).into(), Badge::new("Confirmed").variant(BadgeVariant::Secondary), ), TxState::Failed => ( icon(CIRCLE_X).size(px(20.0)).text_color(theme.destructive).into_any_element(), "Reverted: price moved beyond your slippage".into(), Badge::new("Failed").variant(BadgeVariant::Destructive), ), }; let progress = match state { TxState::Pending { confirmations } => Some(confirmations as f32 / CONFIRMATIONS as f32 * 100.0), _ => None, }; div() .flex() .flex_col() .gap_3() .child( div() .flex() .items_center() .gap_3() .child(div().flex_none().size(px(20.0)).flex().items_center().justify_center().child(status_icon)) .child( div() .flex_1() .min_w_0() .flex() .flex_col() .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(label)) .child(div().text_xs().text_color(theme.muted_foreground).truncate().child(title)), ) .child(badge), ) .children(progress.map(|value| Progress::new(value).id("confirmations"))) .child( div() .flex() .items_center() .justify_between() .pt_3() .border_t_1() .border_color(theme.border) .child( div() .text_xs() .font_family("Geist Mono") .text_color(theme.muted_foreground) .child(truncate_middle(hash, 10, 8)), ) .child( Button::new("explorer", "View on explorer") .variant(ButtonVariant::Link) .size(ButtonSize::Sm) .trailing(icon(ARROW_UP_RIGHT).size(px(14.0)).text_color(theme.foreground)) .on_click(move |_, _, cx| open_explorer(hash, cx)), ), ) .into_any_element() } }; div() .w(px(420.0)) .flex() .flex_col() .gap_4() .child( div() .p_4() .rounded(theme.radius * 1.5) .border_1() .border_color(theme.border) .bg(theme.card) .child(body), ) .child( div() .flex() .justify_center() .gap_2() .child( Button::new("send-ok", "Send sample") .size(ButtonSize::Sm) .disabled(busy) .on_click(cx.listener(|this, _, _, cx| this.send(false, cx))), ) .child( Button::new("send-fail", "Send failing sample") .variant(ButtonVariant::Outline) .size(ButtonSize::Sm) .disabled(busy) .on_click(cx.listener(|this, _, _, cx| this.send(true, cx))), ), ) .child(Toaster::new()) } }