A lending position's health factor on a meter marked at the liquidation line, over a summary of what is supplied and borrowed. Drag the slider to borrow more and watch the factor fall. All values are integer cents and basis points.
Loading GPUI…
use gpui::{div, prelude::*, px, relative, Context, FontWeight, Hsla, SharedString, Window};
use crate::icons::{icon, TRIANGLE_ALERT};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::badge::{Badge, BadgeVariant};
use crate::ui::onchain::{
format_amount, format_bps, format_health_factor, format_usd_cents, health, health_factor_bps, mul_div, usd_cents,
Health, BPS,
};
use crate::ui::slider::Slider;
struct Position {
symbol: &'static str,
decimals: u8,
amount: u128,
price_e8: u128,
/// Supplied assets: the share of value counted before liquidation, and the share that can be
/// borrowed against. Zero for borrowed assets.
liquidation_threshold_bps: u128,
max_ltv_bps: u128,
}
/// Sample position.
const SUPPLIED: [Position; 2] = [
Position { symbol: "ETH", decimals: 18, amount: 5_000_000_000_000_000_000, price_e8: 300_000_000_000, liquidation_threshold_bps: 8_250, max_ltv_bps: 8_000 },
Position { symbol: "WBTC", decimals: 8, amount: 10_000_000, price_e8: 6_000_000_000_000, liquidation_threshold_bps: 7_500, max_ltv_bps: 7_000 },
];
const BORROWED: Position = Position { symbol: "USDC", decimals: 6, amount: 8_000_000_000, price_e8: 100_000_000, liquidation_threshold_bps: 0, max_ltv_bps: 0 };
/// The meter's right end: health factors above 3.00 fill it.
const METER_MAX_BPS: u128 = 30_000;
/// Extra borrowing the slider adds, in whole dollars.
const EXTRA_MAX_USD: f32 = 9_000.0;
#[derive(Default)]
pub struct HealthFactorPattern {
/// Extra USDC borrowed through the slider, in whole dollars.
extra_usd: u32,
}
impl Render for HealthFactorPattern {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme().clone();
let value = |p: &Position| usd_cents(p.amount, p.decimals, p.price_e8).unwrap_or(0);
let collateral: u128 = SUPPLIED.iter().map(value).sum();
// Each asset counts at its own threshold, so weight before summing.
let weighted: u128 = SUPPLIED.iter().filter_map(|p| mul_div(value(p), p.liquidation_threshold_bps, BPS)).sum();
let borrow_limit: u128 = SUPPLIED.iter().filter_map(|p| mul_div(value(p), p.max_ltv_bps, BPS)).sum();
let debt = value(&BORROWED) + self.extra_usd as u128 * 100;
let hf = health_factor_bps(weighted, BPS, debt);
let state = health(hf);
let used_bps = mul_div(debt, BPS, borrow_limit).unwrap_or(BPS);
let (label, color): (SharedString, Hsla) = match state {
Health::Safe => ("No debt".into(), theme.foreground),
Health::Healthy => ("Healthy".into(), theme.foreground),
Health::Moderate => ("Moderate".into(), theme.foreground),
Health::AtRisk => ("At risk".into(), theme.destructive),
Health::Liquidatable => ("Liquidatable".into(), theme.destructive),
};
let fill = hf.map_or(1.0, |hf| hf.min(METER_MAX_BPS) as f32 / METER_MAX_BPS as f32);
let mark = |bps: u128| BPS.min(bps) as f32 / METER_MAX_BPS as f32;
let meter = div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.relative()
.h(px(10.0))
.rounded_full()
.bg(theme.muted)
.child(div().h_full().w(relative(fill)).rounded_full().bg(color))
// The liquidation line at 1.00.
.child(div().absolute().top(px(-3.0)).bottom(px(-3.0)).left(relative(mark(BPS))).w(px(2.0)).bg(theme.destructive)),
)
.child(
div()
.relative()
.h(px(14.0))
.text_xs()
.text_color(theme.muted_foreground)
.child(div().absolute().left(relative(mark(BPS))).ml(px(-10.0)).child("1.00"))
.child(div().absolute().right_0().child("3.00+")),
);
let row = |p: &Position, sub: String| {
div()
.flex()
.items_center()
.gap_3()
.py_1p5()
.child(Avatar::new(SharedString::from(p.symbol[..1].to_string())).size(AvatarSize::Custom(px(28.0))))
.child(
div()
.flex_1()
.flex()
.flex_col()
.child(div().text_sm().font_weight(FontWeight::MEDIUM).child(p.symbol))
.child(div().text_xs().text_color(theme.muted_foreground).child(sub)),
)
};
let section = |title: &'static str, total: u128| {
div()
.flex()
.justify_between()
.text_xs()
.font_weight(FontWeight::MEDIUM)
.text_color(theme.muted_foreground)
.child(title)
.child(format_usd_cents(total))
};
let supplied_rows = SUPPLIED.iter().map(|p| {
row(p, format!("Liquidation at {} of value", format_bps(p.liquidation_threshold_bps))).child(
div()
.flex()
.flex_col()
.items_end()
.child(div().text_sm().child(format!("{} {}", format_amount(p.amount, p.decimals, 4), p.symbol)))
.child(div().text_xs().text_color(theme.muted_foreground).child(format_usd_cents(value(p)))),
)
});
let borrowed_amount = BORROWED.amount + self.extra_usd as u128 * 1_000_000;
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_end()
.justify_between()
.child(
div()
.flex()
.flex_col()
.child(div().text_xs().text_color(theme.muted_foreground).child("Health factor"))
.child(div().text_3xl().font_weight(FontWeight::SEMIBOLD).text_color(color).child(format_health_factor(hf))),
)
.child(match state {
Health::AtRisk | Health::Liquidatable => Badge::new(label).variant(BadgeVariant::Destructive),
_ => Badge::new(label).variant(BadgeVariant::Secondary),
}),
)
.child(meter)
.when(matches!(state, Health::AtRisk | Health::Liquidatable), |this| {
this.child(
div()
.flex()
.items_center()
.gap_2()
.text_xs()
.text_color(theme.destructive)
.child(icon(TRIANGLE_ALERT).size(px(14.0)).text_color(theme.destructive))
.child("Below 1.00 your collateral can be liquidated. Repay or supply more."),
)
})
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(section("Supplied", collateral))
.children(supplied_rows)
.child(div().h_px().my_2().bg(theme.border))
.child(section("Borrowed", debt))
.child(
row(&BORROWED, format!("{} of borrow limit used", format_bps(used_bps.min(BPS * 10)))).child(
div().text_sm().child(format!("{} USDC", format_amount(borrowed_amount, BORROWED.decimals, 2))),
),
),
)
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.flex()
.justify_between()
.text_xs()
.child(div().text_color(theme.muted_foreground).child("Borrow more (preview)"))
.child(format!("+{}", format_usd_cents(self.extra_usd as u128 * 100))),
)
.child(
Slider::new("extra", self.extra_usd as f32)
.min(0.0)
.max(EXTRA_MAX_USD)
.step(250.0)
.on_change(cx.listener(|this, value: &f32, _, cx| {
this.extra_usd = value.round().max(0.0) as u32;
cx.notify();
})),
),
)
.child(div().text_xs().text_color(theme.muted_foreground).child("Sample position and prices."))
}
}Installation
Add the components
$ cargo hyuskui add avatar badge onchain slider 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/health_factor.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/health_factor.rs use gpui::{div, prelude::*, px, relative, Context, FontWeight, Hsla, SharedString, Window}; use crate::icons::{icon, TRIANGLE_ALERT}; use crate::theme::ActiveTheme; use crate::ui::avatar::{Avatar, AvatarSize}; use crate::ui::badge::{Badge, BadgeVariant}; use crate::ui::onchain::{ format_amount, format_bps, format_health_factor, format_usd_cents, health, health_factor_bps, mul_div, usd_cents, Health, BPS, }; use crate::ui::slider::Slider; struct Position { symbol: &'static str, decimals: u8, amount: u128, price_e8: u128, /// Supplied assets: the share of value counted before liquidation, and the share that can be /// borrowed against. Zero for borrowed assets. liquidation_threshold_bps: u128, max_ltv_bps: u128, } /// Sample position. const SUPPLIED: [Position; 2] = [ Position { symbol: "ETH", decimals: 18, amount: 5_000_000_000_000_000_000, price_e8: 300_000_000_000, liquidation_threshold_bps: 8_250, max_ltv_bps: 8_000 }, Position { symbol: "WBTC", decimals: 8, amount: 10_000_000, price_e8: 6_000_000_000_000, liquidation_threshold_bps: 7_500, max_ltv_bps: 7_000 }, ]; const BORROWED: Position = Position { symbol: "USDC", decimals: 6, amount: 8_000_000_000, price_e8: 100_000_000, liquidation_threshold_bps: 0, max_ltv_bps: 0 }; /// The meter's right end: health factors above 3.00 fill it. const METER_MAX_BPS: u128 = 30_000; /// Extra borrowing the slider adds, in whole dollars. const EXTRA_MAX_USD: f32 = 9_000.0; #[derive(Default)] pub struct HealthFactorPattern { /// Extra USDC borrowed through the slider, in whole dollars. extra_usd: u32, } impl Render for HealthFactorPattern { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let theme = cx.theme().clone(); let value = |p: &Position| usd_cents(p.amount, p.decimals, p.price_e8).unwrap_or(0); let collateral: u128 = SUPPLIED.iter().map(value).sum(); // Each asset counts at its own threshold, so weight before summing. let weighted: u128 = SUPPLIED.iter().filter_map(|p| mul_div(value(p), p.liquidation_threshold_bps, BPS)).sum(); let borrow_limit: u128 = SUPPLIED.iter().filter_map(|p| mul_div(value(p), p.max_ltv_bps, BPS)).sum(); let debt = value(&BORROWED) + self.extra_usd as u128 * 100; let hf = health_factor_bps(weighted, BPS, debt); let state = health(hf); let used_bps = mul_div(debt, BPS, borrow_limit).unwrap_or(BPS); let (label, color): (SharedString, Hsla) = match state { Health::Safe => ("No debt".into(), theme.foreground), Health::Healthy => ("Healthy".into(), theme.foreground), Health::Moderate => ("Moderate".into(), theme.foreground), Health::AtRisk => ("At risk".into(), theme.destructive), Health::Liquidatable => ("Liquidatable".into(), theme.destructive), }; let fill = hf.map_or(1.0, |hf| hf.min(METER_MAX_BPS) as f32 / METER_MAX_BPS as f32); let mark = |bps: u128| BPS.min(bps) as f32 / METER_MAX_BPS as f32; let meter = div() .flex() .flex_col() .gap_1() .child( div() .relative() .h(px(10.0)) .rounded_full() .bg(theme.muted) .child(div().h_full().w(relative(fill)).rounded_full().bg(color)) // The liquidation line at 1.00. .child(div().absolute().top(px(-3.0)).bottom(px(-3.0)).left(relative(mark(BPS))).w(px(2.0)).bg(theme.destructive)), ) .child( div() .relative() .h(px(14.0)) .text_xs() .text_color(theme.muted_foreground) .child(div().absolute().left(relative(mark(BPS))).ml(px(-10.0)).child("1.00")) .child(div().absolute().right_0().child("3.00+")), ); let row = |p: &Position, sub: String| { div() .flex() .items_center() .gap_3() .py_1p5() .child(Avatar::new(SharedString::from(p.symbol[..1].to_string())).size(AvatarSize::Custom(px(28.0)))) .child( div() .flex_1() .flex() .flex_col() .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(p.symbol)) .child(div().text_xs().text_color(theme.muted_foreground).child(sub)), ) }; let section = |title: &'static str, total: u128| { div() .flex() .justify_between() .text_xs() .font_weight(FontWeight::MEDIUM) .text_color(theme.muted_foreground) .child(title) .child(format_usd_cents(total)) }; let supplied_rows = SUPPLIED.iter().map(|p| { row(p, format!("Liquidation at {} of value", format_bps(p.liquidation_threshold_bps))).child( div() .flex() .flex_col() .items_end() .child(div().text_sm().child(format!("{} {}", format_amount(p.amount, p.decimals, 4), p.symbol))) .child(div().text_xs().text_color(theme.muted_foreground).child(format_usd_cents(value(p)))), ) }); let borrowed_amount = BORROWED.amount + self.extra_usd as u128 * 1_000_000; 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_end() .justify_between() .child( div() .flex() .flex_col() .child(div().text_xs().text_color(theme.muted_foreground).child("Health factor")) .child(div().text_3xl().font_weight(FontWeight::SEMIBOLD).text_color(color).child(format_health_factor(hf))), ) .child(match state { Health::AtRisk | Health::Liquidatable => Badge::new(label).variant(BadgeVariant::Destructive), _ => Badge::new(label).variant(BadgeVariant::Secondary), }), ) .child(meter) .when(matches!(state, Health::AtRisk | Health::Liquidatable), |this| { this.child( div() .flex() .items_center() .gap_2() .text_xs() .text_color(theme.destructive) .child(icon(TRIANGLE_ALERT).size(px(14.0)).text_color(theme.destructive)) .child("Below 1.00 your collateral can be liquidated. Repay or supply more."), ) }) .child( div() .flex() .flex_col() .gap_1() .child(section("Supplied", collateral)) .children(supplied_rows) .child(div().h_px().my_2().bg(theme.border)) .child(section("Borrowed", debt)) .child( row(&BORROWED, format!("{} of borrow limit used", format_bps(used_bps.min(BPS * 10)))).child( div().text_sm().child(format!("{} USDC", format_amount(borrowed_amount, BORROWED.decimals, 2))), ), ), ) .child( div() .flex() .flex_col() .gap_2() .child( div() .flex() .justify_between() .text_xs() .child(div().text_color(theme.muted_foreground).child("Borrow more (preview)")) .child(format!("+{}", format_usd_cents(self.extra_usd as u128 * 100))), ) .child( Slider::new("extra", self.extra_usd as f32) .min(0.0) .max(EXTRA_MAX_USD) .step(250.0) .on_change(cx.listener(|this, value: &f32, _, cx| { this.extra_usd = value.round().max(0.0) as u32; cx.notify(); })), ), ) .child(div().text_xs().text_color(theme.muted_foreground).child("Sample position and prices.")) } }