hyuskui

LP Position Range

A concentrated-liquidity range: min and max price over a histogram of the pool's liquidity, with the current price marked. The position earns fees only while the price is inside its range, so the card says when it is in range and when it isn't.

Loading GPUI…
use gpui::{div, prelude::*, px, relative, Context, FontWeight, Window};

use crate::icons::{icon, MINUS, PLUS};
use crate::theme::ActiveTheme;
use crate::ui::badge::{Badge, BadgeVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::onchain::{format_bps, format_usd_cents};
use crate::ui::slider::Slider;

/// Prices are USD cents per ETH in steps of $50, from $2,000 to $4,000: integers, so a bucket
/// edge is exact.
const LOW_CENTS: u128 = 200_000;
const STEP_CENTS: u128 = 5_000;
const BUCKETS: usize = 40;

/// Sample liquidity per bucket, highest near the price the pool has traded at most.
const LIQUIDITY: [u32; BUCKETS] = [
    4, 5, 6, 6, 8, 9, 11, 13, 16, 18, 22, 27, 33, 41, 52, 64, 78, 90, 97, 100, 96, 88, 76, 63, 51, 42, 34, 28, 23,
    19, 15, 13, 11, 9, 8, 7, 6, 5, 4, 4,
];

/// The sample pool's price moves between these to show both states.
const PRICES_CENTS: [u128; 2] = [300_000, 372_500];
const FEE_TIER_BPS: u128 = 30;

pub struct LpRangePattern {
    /// Bucket edges, 0..=BUCKETS.
    min: usize,
    max: usize,
    price: usize,
}

impl Default for LpRangePattern {
    fn default() -> Self {
        Self { min: 12, max: 28, price: 0 }
    }
}

fn edge_cents(edge: usize) -> u128 {
    LOW_CENTS + STEP_CENTS * edge as u128
}

impl Render for LpRangePattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme().clone();
        let (min_cents, max_cents) = (edge_cents(self.min), edge_cents(self.max));
        let price = PRICES_CENTS[self.price];
        // Inclusive of the lower bound, exclusive of the upper, like a tick range.
        let in_range = price >= min_cents && price < max_cents;
        let price_fraction = (price - LOW_CENTS) as f32 / (STEP_CENTS * BUCKETS as u128) as f32;
        let tallest = LIQUIDITY.iter().copied().max().unwrap_or(1).max(1) as f32;

        let bars = LIQUIDITY.iter().enumerate().map(|(ix, &liquidity)| {
            let inside = ix >= self.min && ix < self.max;
            div()
                .flex_1()
                .h(relative(liquidity as f32 / tallest))
                .rounded_t(px(2.0))
                .bg(if inside { theme.foreground.opacity(0.75) } else { theme.muted_foreground.opacity(0.3) })
        });

        let histogram = div()
            .relative()
            .h(px(140.0))
            .flex()
            .items_end()
            .gap(px(2.0))
            .children(bars)
            .child(
                div()
                    .absolute()
                    .top_0()
                    .bottom_0()
                    .left(relative(price_fraction))
                    .w(px(2.0))
                    .bg(if in_range { theme.ring } else { theme.destructive }),
            );

        let stepper = |id: &'static str, label: &'static str, cents: u128, edge: usize, is_min: bool| {
            let (lo, hi) = if is_min { (0, self.max - 1) } else { (self.min + 1, BUCKETS) };
            div()
                .flex_1()
                .flex()
                .flex_col()
                .items_center()
                .gap_1()
                .p_3()
                .rounded(theme.radius)
                .border_1()
                .border_color(theme.border)
                .child(div().text_xs().text_color(theme.muted_foreground).child(label))
                .child(
                    div()
                        .flex()
                        .items_center()
                        .gap_2()
                        .child(
                            Button::new((id, 0usize), "")
                                .variant(ButtonVariant::Outline)
                                .size(ButtonSize::Xs)
                                .icon_only()
                                .disabled(edge <= lo)
                                .leading(icon(MINUS).size(px(12.0)).text_color(theme.foreground))
                                .on_click(cx.listener(move |this, _, _, cx| {
                                    let edge = if is_min { &mut this.min } else { &mut this.max };
                                    *edge = edge.saturating_sub(1).max(lo);
                                    cx.notify();
                                })),
                        )
                        .child(div().w(px(84.0)).text_center().text_base().font_weight(FontWeight::SEMIBOLD).child(format_usd_cents(cents)))
                        .child(
                            Button::new((id, 1usize), "")
                                .variant(ButtonVariant::Outline)
                                .size(ButtonSize::Xs)
                                .icon_only()
                                .disabled(edge >= hi)
                                .leading(icon(PLUS).size(px(12.0)).text_color(theme.foreground))
                                .on_click(cx.listener(move |this, _, _, cx| {
                                    let edge = if is_min { &mut this.min } else { &mut this.max };
                                    *edge = (*edge + 1).min(hi);
                                    cx.notify();
                                })),
                        ),
                )
                .child(div().text_xs().text_color(theme.muted_foreground).child("USDC per ETH"))
        };

        div()
            .w(px(440.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()
                            .flex()
                            .flex_col()
                            .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("ETH / USDC"))
                            .child(div().text_xs().text_color(theme.muted_foreground).child(format!(
                                "{} fee tier \u{00b7} sample pool",
                                format_bps(FEE_TIER_BPS)
                            ))),
                    )
                    .child(if in_range {
                        Badge::new("In range").variant(BadgeVariant::Secondary)
                    } else {
                        Badge::new("Out of range").variant(BadgeVariant::Destructive)
                    }),
            )
            .child(
                div()
                    .flex()
                    .justify_between()
                    .text_xs()
                    .child(div().text_color(theme.muted_foreground).child("Current price"))
                    .child(div().font_weight(FontWeight::MEDIUM).child(format!("{} USDC per ETH", format_usd_cents(price)))),
            )
            .child(histogram)
            .child(
                Slider::new("range", self.min as f32)
                    .values([self.min as f32, self.max as f32])
                    .min(0.0)
                    .max(BUCKETS as f32)
                    .step(1.0)
                    .on_values_change(cx.listener(|this, values: &Vec<f32>, _, cx| {
                        if let [min, max] = values[..] {
                            // Keep at least one bucket between the bounds.
                            let (min, max) = (min.round() as usize, max.round() as usize);
                            if min < max {
                                this.min = min;
                                this.max = max.min(BUCKETS);
                                cx.notify();
                            }
                        }
                    })),
            )
            .child(
                div()
                    .flex()
                    .gap_3()
                    .child(stepper("min", "Min price", min_cents, self.min, true))
                    .child(stepper("max", "Max price", max_cents, self.max, false)),
            )
            .child(
                div()
                    .flex()
                    .items_center()
                    .justify_between()
                    .text_xs()
                    .text_color(theme.muted_foreground)
                    .child(if in_range {
                        "Earning fees while the price stays in range."
                    } else {
                        "Not earning fees: the price is outside the range."
                    })
                    .child(
                        Button::new("move", if self.price == 0 { "Move price" } else { "Reset price" })
                            .variant(ButtonVariant::Ghost)
                            .size(ButtonSize::Xs)
                            .on_click(cx.listener(|this, _, _, cx| {
                                this.price = 1 - this.price;
                                cx.notify();
                            })),
                    ),
            )
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add badge button onchain slider icons

    Uses Badge, Button, Onchain and Slider.

  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/lp_range.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/lp_range.rs
    use gpui::{div, prelude::*, px, relative, Context, FontWeight, Window};
    
    use crate::icons::{icon, MINUS, PLUS};
    use crate::theme::ActiveTheme;
    use crate::ui::badge::{Badge, BadgeVariant};
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::onchain::{format_bps, format_usd_cents};
    use crate::ui::slider::Slider;
    
    /// Prices are USD cents per ETH in steps of $50, from $2,000 to $4,000: integers, so a bucket
    /// edge is exact.
    const LOW_CENTS: u128 = 200_000;
    const STEP_CENTS: u128 = 5_000;
    const BUCKETS: usize = 40;
    
    /// Sample liquidity per bucket, highest near the price the pool has traded at most.
    const LIQUIDITY: [u32; BUCKETS] = [
        4, 5, 6, 6, 8, 9, 11, 13, 16, 18, 22, 27, 33, 41, 52, 64, 78, 90, 97, 100, 96, 88, 76, 63, 51, 42, 34, 28, 23,
        19, 15, 13, 11, 9, 8, 7, 6, 5, 4, 4,
    ];
    
    /// The sample pool's price moves between these to show both states.
    const PRICES_CENTS: [u128; 2] = [300_000, 372_500];
    const FEE_TIER_BPS: u128 = 30;
    
    pub struct LpRangePattern {
        /// Bucket edges, 0..=BUCKETS.
        min: usize,
        max: usize,
        price: usize,
    }
    
    impl Default for LpRangePattern {
        fn default() -> Self {
            Self { min: 12, max: 28, price: 0 }
        }
    }
    
    fn edge_cents(edge: usize) -> u128 {
        LOW_CENTS + STEP_CENTS * edge as u128
    }
    
    impl Render for LpRangePattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme().clone();
            let (min_cents, max_cents) = (edge_cents(self.min), edge_cents(self.max));
            let price = PRICES_CENTS[self.price];
            // Inclusive of the lower bound, exclusive of the upper, like a tick range.
            let in_range = price >= min_cents && price < max_cents;
            let price_fraction = (price - LOW_CENTS) as f32 / (STEP_CENTS * BUCKETS as u128) as f32;
            let tallest = LIQUIDITY.iter().copied().max().unwrap_or(1).max(1) as f32;
    
            let bars = LIQUIDITY.iter().enumerate().map(|(ix, &liquidity)| {
                let inside = ix >= self.min && ix < self.max;
                div()
                    .flex_1()
                    .h(relative(liquidity as f32 / tallest))
                    .rounded_t(px(2.0))
                    .bg(if inside { theme.foreground.opacity(0.75) } else { theme.muted_foreground.opacity(0.3) })
            });
    
            let histogram = div()
                .relative()
                .h(px(140.0))
                .flex()
                .items_end()
                .gap(px(2.0))
                .children(bars)
                .child(
                    div()
                        .absolute()
                        .top_0()
                        .bottom_0()
                        .left(relative(price_fraction))
                        .w(px(2.0))
                        .bg(if in_range { theme.ring } else { theme.destructive }),
                );
    
            let stepper = |id: &'static str, label: &'static str, cents: u128, edge: usize, is_min: bool| {
                let (lo, hi) = if is_min { (0, self.max - 1) } else { (self.min + 1, BUCKETS) };
                div()
                    .flex_1()
                    .flex()
                    .flex_col()
                    .items_center()
                    .gap_1()
                    .p_3()
                    .rounded(theme.radius)
                    .border_1()
                    .border_color(theme.border)
                    .child(div().text_xs().text_color(theme.muted_foreground).child(label))
                    .child(
                        div()
                            .flex()
                            .items_center()
                            .gap_2()
                            .child(
                                Button::new((id, 0usize), "")
                                    .variant(ButtonVariant::Outline)
                                    .size(ButtonSize::Xs)
                                    .icon_only()
                                    .disabled(edge <= lo)
                                    .leading(icon(MINUS).size(px(12.0)).text_color(theme.foreground))
                                    .on_click(cx.listener(move |this, _, _, cx| {
                                        let edge = if is_min { &mut this.min } else { &mut this.max };
                                        *edge = edge.saturating_sub(1).max(lo);
                                        cx.notify();
                                    })),
                            )
                            .child(div().w(px(84.0)).text_center().text_base().font_weight(FontWeight::SEMIBOLD).child(format_usd_cents(cents)))
                            .child(
                                Button::new((id, 1usize), "")
                                    .variant(ButtonVariant::Outline)
                                    .size(ButtonSize::Xs)
                                    .icon_only()
                                    .disabled(edge >= hi)
                                    .leading(icon(PLUS).size(px(12.0)).text_color(theme.foreground))
                                    .on_click(cx.listener(move |this, _, _, cx| {
                                        let edge = if is_min { &mut this.min } else { &mut this.max };
                                        *edge = (*edge + 1).min(hi);
                                        cx.notify();
                                    })),
                            ),
                    )
                    .child(div().text_xs().text_color(theme.muted_foreground).child("USDC per ETH"))
            };
    
            div()
                .w(px(440.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()
                                .flex()
                                .flex_col()
                                .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("ETH / USDC"))
                                .child(div().text_xs().text_color(theme.muted_foreground).child(format!(
                                    "{} fee tier \u{00b7} sample pool",
                                    format_bps(FEE_TIER_BPS)
                                ))),
                        )
                        .child(if in_range {
                            Badge::new("In range").variant(BadgeVariant::Secondary)
                        } else {
                            Badge::new("Out of range").variant(BadgeVariant::Destructive)
                        }),
                )
                .child(
                    div()
                        .flex()
                        .justify_between()
                        .text_xs()
                        .child(div().text_color(theme.muted_foreground).child("Current price"))
                        .child(div().font_weight(FontWeight::MEDIUM).child(format!("{} USDC per ETH", format_usd_cents(price)))),
                )
                .child(histogram)
                .child(
                    Slider::new("range", self.min as f32)
                        .values([self.min as f32, self.max as f32])
                        .min(0.0)
                        .max(BUCKETS as f32)
                        .step(1.0)
                        .on_values_change(cx.listener(|this, values: &Vec<f32>, _, cx| {
                            if let [min, max] = values[..] {
                                // Keep at least one bucket between the bounds.
                                let (min, max) = (min.round() as usize, max.round() as usize);
                                if min < max {
                                    this.min = min;
                                    this.max = max.min(BUCKETS);
                                    cx.notify();
                                }
                            }
                        })),
                )
                .child(
                    div()
                        .flex()
                        .gap_3()
                        .child(stepper("min", "Min price", min_cents, self.min, true))
                        .child(stepper("max", "Max price", max_cents, self.max, false)),
                )
                .child(
                    div()
                        .flex()
                        .items_center()
                        .justify_between()
                        .text_xs()
                        .text_color(theme.muted_foreground)
                        .child(if in_range {
                            "Earning fees while the price stays in range."
                        } else {
                            "Not earning fees: the price is outside the range."
                        })
                        .child(
                            Button::new("move", if self.price == 0 { "Move price" } else { "Reset price" })
                                .variant(ButtonVariant::Ghost)
                                .size(ButtonSize::Xs)
                                .on_click(cx.listener(|this, _, _, cx| {
                                    this.price = 1 - this.price;
                                    cx.notify();
                                })),
                        ),
                )
        }
    }