ghost-eye/src/components/validator/withdrawals.rs
Uncle Stretch 0a28acede7
reverse logic for ready to be triggered withdrawal
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-09-29 20:44:22 +03:00

258 lines
8.6 KiB
Rust

use color_eyre::Result;
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::layout::{Constraint, Margin};
use ratatui::style::{Modifier, Stylize};
use ratatui::{
text::Text,
layout::{Alignment, Rect},
widgets::{
Block, Cell, Row, Table, TableState, Scrollbar,
ScrollbarOrientation, ScrollbarState,
},
Frame
};
use tokio::sync::mpsc::UnboundedSender;
use super::{PartialComponent, Component, CurrentTab};
use crate::types::{ActionTarget, ActionLevel, UnlockChunk};
use crate::{
action::Action,
config::Config,
palette::StylePalette,
};
pub struct Withdrawals {
is_active: bool,
action_tx: Option<UnboundedSender<Action>>,
palette: StylePalette,
scroll_state: ScrollbarState,
table_state: TableState,
unlockings: Vec<UnlockChunk>,
stash_account: [u8; 32],
current_era: u32,
}
impl Default for Withdrawals {
fn default() -> Self {
Self::new()
}
}
impl Withdrawals {
const TICKER: &str = " CSPR";
const DECIMALS: usize = 5;
pub fn new() -> Self {
Self {
is_active: false,
action_tx: None,
scroll_state: ScrollbarState::new(0),
table_state: TableState::new(),
palette: StylePalette::default(),
unlockings: Vec::new(),
stash_account: [0u8; 32],
current_era: 0,
}
}
fn try_open_popup(&mut self) {
if let Some(action_tx) = &self.action_tx {
if let Some(index) = self.table_state.selected() {
if index == 0 && self.unlockings[0].era < self.current_era {
let _ = action_tx.send(Action::WithdrawValidatorPopup);
} else {
let _ = action_tx.send(Action::EventLog(
"Nothing to be witdrawn yet on the selected unlocking".to_string(),
ActionLevel::Info,
ActionTarget::ValidatorLog));
}
}
}
}
fn first_row(&mut self) {
if self.unlockings.len() > 0 {
self.table_state.select(Some(0));
self.scroll_state = self.scroll_state.position(0);
}
}
fn next_row(&mut self) {
let i = match self.table_state.selected() {
Some(i) => {
if i >= self.unlockings.len() - 1 {
i
} else {
i + 1
}
},
None => 0,
};
self.table_state.select(Some(i));
self.scroll_state = self.scroll_state.position(i);
}
fn last_row(&mut self) {
if self.unlockings.len() > 0 {
let last = self.unlockings.len() - 1;
self.table_state.select(Some(last));
self.scroll_state = self.scroll_state.position(last);
}
}
fn previous_row(&mut self) {
let i = match self.table_state.selected() {
Some(i) => {
if i == 0 {
0
} else {
i - 1
}
},
None => 0
};
self.table_state.select(Some(i));
self.scroll_state = self.scroll_state.position(i);
}
fn add_new_unlocking(&mut self, unlockings: Vec<UnlockChunk>) {
let mut updated_unlockings = Vec::new();
for chunk in unlockings {
if chunk.era > self.current_era {
updated_unlockings.push(chunk);
} else {
match updated_unlockings.get_mut(0) {
Some(stored_chunk) => (*stored_chunk).value += chunk.value,
None => updated_unlockings.push(chunk),
}
}
}
self.unlockings = updated_unlockings;
self.scroll_state = self.scroll_state
.content_length(self.unlockings.len());
}
fn prepare_u128(&self, value: u128) -> String {
let value = value as f64 / 10f64.powi(18);
let after = Self::DECIMALS;
format!("{:.after$}{}", value, Self::TICKER)
}
fn estimate_time(&self, era_index: u32) -> String {
if era_index > self.current_era {
format!("{} eras", era_index - self.current_era)
} else {
String::from("ready")
}
}
}
impl PartialComponent for Withdrawals {
fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab {
CurrentTab::Withdrawals => self.is_active = true,
_ => {
self.is_active = false;
self.table_state.select(None);
self.scroll_state = self.scroll_state.position(0);
}
}
}
}
impl Component for Withdrawals {
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
self.action_tx = Some(tx);
Ok(())
}
fn register_config_handler(&mut self, config: Config) -> Result<()> {
if let Some(style) = config.styles.get(&crate::app::Mode::Validator) {
self.palette.with_normal_style(style.get("normal_style").copied());
self.palette.with_hover_style(style.get("hover_style").copied());
self.palette.with_normal_border_style(style.get("normal_border_style").copied());
self.palette.with_hover_border_style(style.get("hover_border_style").copied());
self.palette.with_normal_title_style(style.get("normal_title_style").copied());
self.palette.with_hover_title_style(style.get("hover_title_style").copied());
self.palette.with_highlight_style(style.get("highlight_style").copied());
self.palette.with_scrollbar_style(style.get("scrollbar_style").copied());
}
Ok(())
}
fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::SetStashAccount(account_id) => self.stash_account = account_id,
Action::SetActiveEra(era_info) => self.current_era = era_info.index,
Action::SetValidatorEraUnlocking(unlockings, account_id) if self.stash_account == account_id =>
self.add_new_unlocking(unlockings),
_ => {}
};
Ok(None)
}
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if self.is_active {
match key.code {
KeyCode::Up | KeyCode::Char('k') => self.previous_row(),
KeyCode::Down | KeyCode::Char('j') => self.next_row(),
KeyCode::Char('g') => self.first_row(),
KeyCode::Char('G') => self.last_row(),
KeyCode::Enter => self.try_open_popup(),
_ => {},
};
}
Ok(None)
}
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
let [_, _, place] = super::validator_statistics_layout(area);
let (border_style, border_type) = self.palette.create_border_style(self.is_active);
let table = Table::new(
self.unlockings
.iter()
.map(|unlock| {
let mut est_era_text = Text::from(self.estimate_time(unlock.era)).alignment(Alignment::Center);
let mut value_text = Text::from(self.prepare_u128(unlock.value)).alignment(Alignment::Right);
if unlock.era > self.current_era {
est_era_text = est_era_text.add_modifier(Modifier::CROSSED_OUT);
value_text = value_text.add_modifier(Modifier::CROSSED_OUT);
}
Row::new(vec![
Cell::from(est_era_text),
Cell::from(value_text),
])
}),
[
Constraint::Length(7),
Constraint::Min(0),
],
)
.highlight_style(self.palette.create_highlight_style())
.column_spacing(1)
.block(Block::bordered()
.border_style(border_style)
.border_type(border_type)
.title_alignment(Alignment::Right)
.title_style(self.palette.create_title_style(false))
.title("Withdrawals"));
let scrollbar = Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(None)
.end_symbol(None)
.style(self.palette.create_scrollbar_style());
frame.render_stateful_widget(table, place, &mut self.table_state);
frame.render_stateful_widget(
scrollbar,
place.inner(Margin { vertical: 1, horizontal: 1 }),
&mut self.scroll_state,
);
Ok(())
}
}