diff --git a/src/action.rs b/src/action.rs index 79cc9f2..af25bd6 100644 --- a/src/action.rs +++ b/src/action.rs @@ -56,6 +56,7 @@ pub enum Action { BondValidatorFrom([u8; 32], u128), PayoutStakers([u8; 32], [u8; 32], u32), SetSessionKeys([u8; 32], String), + ValidateFrom([u8; 32], u32), EventLog(String, ActionLevel, ActionTarget), NewBestBlock(u32), diff --git a/src/components/validator/mod.rs b/src/components/validator/mod.rs index 39761fb..b936046 100644 --- a/src/components/validator/mod.rs +++ b/src/components/validator/mod.rs @@ -24,6 +24,7 @@ mod reward_details; mod bond_popup; mod payout_popup; mod rotate_popup; +mod validate_popup; use stash_details::StashDetails; use staking_details::StakingDetails; @@ -38,6 +39,7 @@ use withdrawals::Withdrawals; use bond_popup::BondPopup; use payout_popup::PayoutPopup; use rotate_popup::RotatePopup; +use validate_popup::ValidatePopup; #[derive(Debug, Copy, Clone, PartialEq)] pub enum CurrentTab { @@ -52,6 +54,7 @@ pub enum CurrentTab { BondPopup, PayoutPopup, RotatePopup, + ValidatePopup, } pub trait PartialComponent: Component { @@ -85,6 +88,7 @@ impl Default for Validator { Box::new(BondPopup::default()), Box::new(PayoutPopup::default()), Box::new(RotatePopup::default()), + Box::new(ValidatePopup::default()), ], } } @@ -145,6 +149,7 @@ impl Component for Validator { match self.current_tab { CurrentTab::BondPopup | CurrentTab::RotatePopup | + CurrentTab::ValidatePopup | CurrentTab::PayoutPopup => match key.code { KeyCode::Esc => { self.current_tab = self.previous_tab; @@ -186,6 +191,13 @@ impl Component for Validator { component.set_active(self.current_tab.clone()); } }, + KeyCode::Char('V') => { + self.previous_tab = self.current_tab; + self.current_tab = CurrentTab::ValidatePopup; + for component in self.components.iter_mut() { + component.set_active(self.current_tab.clone()); + } + }, KeyCode::Char('B') => { self.previous_tab = self.current_tab; self.current_tab = CurrentTab::BondPopup; diff --git a/src/components/validator/validate_popup.rs b/src/components/validator/validate_popup.rs new file mode 100644 index 0000000..381d02f --- /dev/null +++ b/src/components/validator/validate_popup.rs @@ -0,0 +1,173 @@ +use crossterm::event::{KeyCode, KeyEvent, KeyEventKind}; +use color_eyre::Result; +use ratatui::{ + layout::{Position, Alignment, Constraint, Flex, Layout, Rect}, + widgets::{Block, Clear, Paragraph}, + Frame +}; +use tokio::sync::mpsc::UnboundedSender; +use std::sync::mpsc::Sender; + +use super::{Component, PartialComponent, CurrentTab}; +use crate::{ + action::Action, + config::Config, + palette::StylePalette, + types::{ActionLevel, ActionTarget}, + widgets::{Input, InputRequest}, +}; + +#[derive(Debug)] +pub struct ValidatePopup { + is_active: bool, + action_tx: Option>, + network_tx: Option>, + secret_seed: [u8; 32], + amount: Input, + palette: StylePalette +} + +impl Default for ValidatePopup { + fn default() -> Self { + Self::new() + } +} + +impl ValidatePopup { + pub fn new() -> Self { + Self { + is_active: false, + secret_seed: [0u8; 32], + action_tx: None, + network_tx: None, + amount: Input::new(String::new()), + palette: StylePalette::default(), + } + } +} + +impl ValidatePopup { + fn log_event(&mut self, message: String, level: ActionLevel) { + if let Some(action_tx) = &self.action_tx { + let _ = action_tx.send( + Action::EventLog(message, level, ActionTarget::ValidatorLog)); + } + } + + fn submit_message(&mut self) { + if let Some(network_tx) = &self.network_tx { + match self.amount.value().parse::() { + Ok(value) => { + let amount = (value * 1_000_000_000.0).round() as u32; + let _ = network_tx.send(Action::ValidateFrom(self.secret_seed, amount)); + if let Some(action_tx) = &self.action_tx { + let _ = action_tx.send(Action::ClosePopup); + } + }, + Err(err) => self.log_event( + format!("invalid amount, error: {err}"), ActionLevel::Error), + } + } + } + + fn enter_char(&mut self, new_char: char) { + let is_separator_needed = !self.amount.value().contains('.') && new_char == '.'; + if new_char.is_digit(10) || is_separator_needed { + let _ = self.amount.handle(InputRequest::InsertChar(new_char)); + } + } + + fn delete_char(&mut self) { + let _ = self.amount.handle(InputRequest::DeletePrevChar); + } + + fn move_cursor_right(&mut self) { + let _ = self.amount.handle(InputRequest::GoToNextChar); + } + + fn move_cursor_left(&mut self) { + let _ = self.amount.handle(InputRequest::GoToPrevChar); + } +} + +impl PartialComponent for ValidatePopup { + fn set_active(&mut self, current_tab: CurrentTab) { + match current_tab { + CurrentTab::ValidatePopup => self.is_active = true, + _ => { + self.is_active = false; + self.amount = Input::new(String::new()); + } + }; + } +} + +impl Component for ValidatePopup { + fn register_network_handler(&mut self, tx: Sender) -> Result<()> { + self.network_tx = Some(tx); + Ok(()) + } + + fn register_action_handler(&mut self, tx: UnboundedSender) -> 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::Wallet) { + self.palette.with_normal_style(style.get("normal_style").copied()); + self.palette.with_normal_border_style(style.get("normal_border_style").copied()); + self.palette.with_normal_title_style(style.get("normal_title_style").copied()); + self.palette.with_popup_style(style.get("popup_style").copied()); + self.palette.with_popup_title_style(style.get("popup_title_style").copied()); + } + Ok(()) + } + fn handle_key_event(&mut self, key: KeyEvent) -> Result> { + if self.is_active && key.kind == KeyEventKind::Press { + match key.code { + KeyCode::Enter => self.submit_message(), + KeyCode::Char(to_insert) => self.enter_char(to_insert), + KeyCode::Backspace => self.delete_char(), + KeyCode::Left => self.move_cursor_left(), + KeyCode::Right => self.move_cursor_right(), + KeyCode::Esc => self.is_active = false, + _ => {}, + }; + } + Ok(None) + } + + fn update(&mut self, action: Action) -> Result> { + match action { + Action::SetStashSecret(secret_seed) => self.secret_seed = secret_seed, + _ => {} + }; + Ok(None) + } + + fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> { + if self.is_active { + let (border_style, border_type) = self.palette.create_popup_style(); + let input = Paragraph::new(self.amount.value()) + .block(Block::bordered() + .border_style(border_style) + .border_type(border_type) + .title_style(self.palette.create_popup_title_style()) + .title_alignment(Alignment::Right) + .title(format!("Commission for nominators"))); + let v = Layout::vertical([Constraint::Max(3)]).flex(Flex::Center); + let h = Layout::horizontal([Constraint::Max(50)]).flex(Flex::Center); + let [area] = v.areas(area); + let [area] = h.areas(area); + + frame.render_widget(Clear, area); + frame.render_widget(input, area); + frame.set_cursor_position(Position::new( + area.x + self.amount.cursor() as u16 + 1, + area.y + 1 + )); + } + Ok(()) + } +} diff --git a/src/network/mod.rs b/src/network/mod.rs index 31d2172..2fbcb49 100644 --- a/src/network/mod.rs +++ b/src/network/mod.rs @@ -331,6 +331,24 @@ impl Network { } Ok(()) } + Action::ValidateFrom(sender, percent) => { + let sender_str = hex::encode(sender); + let maybe_nonce = self.senders.get_mut(&sender_str); + if let Ok(tx_progress) = predefined_txs::validate( + &self.action_tx, + &self.online_client_api, + &sender, + percent, + maybe_nonce, + ).await { + self.transactions_to_watch.push(TxToWatch { + tx_progress, + sender: sender_str, + target: ActionTarget::ValidatorLog, + }); + } + Ok(()) + } _ => Ok(()) } } diff --git a/src/network/predefined_txs.rs b/src/network/predefined_txs.rs index fbb7d0a..fa761f8 100644 --- a/src/network/predefined_txs.rs +++ b/src/network/predefined_txs.rs @@ -1,13 +1,16 @@ use color_eyre::Result; use subxt::{ - ext::sp_core::{Pair as PairT, sr25519::Pair}, + ext::sp_core::{sr25519::Pair, Pair as PairT}, tx::{PairSigner, TxProgress}, OnlineClient, }; use tokio::sync::mpsc::UnboundedSender; use crate::{ - action::Action, casper::{CasperConfig, CasperExtrinsicParamsBuilder}, casper_network::{self, runtime_types}, types::{ActionLevel, ActionTarget} + action::Action, + casper::{CasperConfig, CasperExtrinsicParamsBuilder}, + casper_network::{self, runtime_types}, + types::{ActionLevel, ActionTarget}, }; pub async fn transfer_balance( @@ -265,3 +268,53 @@ pub async fn set_keys( } } } + +pub async fn validate( + action_tx: &UnboundedSender, + api: &OnlineClient, + sender: &[u8; 32], + percent: u32, + mut maybe_nonce: Option<&mut u32>, +) -> Result>> { + let validator_prefs = casper_network::runtime_types::pallet_staking::ValidatorPrefs { + commission: runtime_types::sp_arithmetic::per_things::Perbill(percent), + blocked: percent >= 1_000_000_000u32, + }; + + let transfer_tx = casper_network::tx() + .staking() + .validate(validator_prefs); + + let tx_params = match maybe_nonce { + Some(ref mut nonce) => { + **nonce = nonce.saturating_add(1); + CasperExtrinsicParamsBuilder::new() + .nonce(nonce.saturating_sub(1) as u64) + .build() + }, + None => CasperExtrinsicParamsBuilder::new().build(), + }; + + let pair = Pair::from_seed(sender); + let signer = PairSigner::::new(pair); + + match api + .tx() + .sign_and_submit_then_watch(&transfer_tx, &signer, tx_params) + .await { + Ok(tx_progress) => { + action_tx.send(Action::EventLog( + format!("set keys {} sent", tx_progress.extrinsic_hash()), + ActionLevel::Info, + ActionTarget::ValidatorLog))?; + Ok(tx_progress) + }, + Err(err) => { + action_tx.send(Action::EventLog( + format!("error during set keys: {err}"), + ActionLevel::Error, + ActionTarget::ValidatorLog))?; + Err(err.into()) + } + } +}