Compare commits
	
		
			6 Commits
		
	
	
		
			dc20ba936a
			...
			be92585661
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| be92585661 | |||
| bbd96b4ea1 | |||
| 13a76f25a6 | |||
| ac14c36760 | |||
| 6255703bbb | |||
| 5bfd4e678a | 
| @ -1,6 +1,8 @@ | ||||
| [package] | ||||
| name = "ghost-eye" | ||||
| version = "0.2.2" | ||||
| authors = ["str3tch <stretch@ghostchain.io>"] | ||||
| description = "Application for interacting with Casper/Ghost nodes that are exposing RPC only to the localhost" | ||||
| version = "0.2.6" | ||||
| edition = "2021" | ||||
| 
 | ||||
| [dependencies] | ||||
|  | ||||
| @ -8,8 +8,6 @@ use crate::{ | ||||
|     types::{SystemAccount, ActionLevel, EraInfo, CasperExtrinsicDetails}, | ||||
| }; | ||||
| 
 | ||||
| use subxt::utils::AccountId32; | ||||
| 
 | ||||
| #[derive(Debug, Clone, PartialEq, Eq, Display, Serialize, Deserialize)] | ||||
| pub enum Action { | ||||
|     Tick, | ||||
| @ -26,18 +24,23 @@ pub enum Action { | ||||
|     SetActiveScreen(crate::app::Mode), | ||||
|     UsedExplorerBlock(Option<u32>), | ||||
|     UsedExplorerLog(Option<String>), | ||||
|     UsedAccount(AccountId32), | ||||
|     UsedAccount(String), | ||||
|     NewAccount(String), | ||||
|     NewAddressBookRecord(String, String), | ||||
| 
 | ||||
|     ClosePopup, | ||||
| 
 | ||||
|     BalanceRequest([u8; 32], bool), | ||||
|     BalanceResponse([u8; 32], SystemAccount), | ||||
|     BalanceSetActive(Option<SystemAccount>), | ||||
| 
 | ||||
|     RenameAccount(String), | ||||
|     RenameAddressBookRecord(String), | ||||
|     UpdateAccountName(String), | ||||
|     UpdateAddressBookRecord(String), | ||||
|     TransferTo(String), | ||||
| 
 | ||||
|     TransferBalance(String, [u8; 32], u128), | ||||
|     WalletLog(String, ActionLevel), | ||||
| 
 | ||||
|     NewBestBlock(u32), | ||||
|  | ||||
| @ -69,7 +69,7 @@ impl Component for FinalizedBlock { | ||||
|                     .title_alignment(Alignment::Right) | ||||
|                     .title_style(self.palette.create_title_style(false)) | ||||
|                     .padding(Padding::new(0, 0, height.saturating_sub(2) / 2, 0)) | ||||
|                     .title("Latest")) | ||||
|                     .title("Finalized")) | ||||
|                 .alignment(Alignment::Center) | ||||
|                 .wrap(Wrap { trim: true }); | ||||
|             frame.render_widget(paragraph, place); | ||||
| @ -88,7 +88,7 @@ impl Component for FinalizedBlock { | ||||
|                     .border_type(border_type) | ||||
|                     .title_alignment(Alignment::Right) | ||||
|                     .title_style(self.palette.create_title_style(false)) | ||||
|                     .title("Latest")) | ||||
|                     .title("Finalized")) | ||||
|                 .alignment(Alignment::Center) | ||||
|                 .wrap(Wrap { trim: true }); | ||||
|             frame.render_widget(paragraph, place); | ||||
|  | ||||
| @ -39,6 +39,7 @@ struct AccountInfo { | ||||
|     address: String, | ||||
|     account_id: [u8; 32], | ||||
|     seed: String, | ||||
|     #[allow(dead_code)] | ||||
|     pair_signer: PairSigner<CasperConfig, Pair>, | ||||
| } | ||||
| 
 | ||||
| @ -75,12 +76,43 @@ impl Accounts { | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn set_used_account(&mut self, index: usize) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let _ = action_tx.send(Action::UsedAccount( | ||||
|                     self.wallet_keys[index].seed.clone())); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn log_event(&mut self, message: String, level: ActionLevel) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let _ = action_tx.send(Action::WalletLog(message, level)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn send_balance_request(&mut self, account_id: [u8; 32], remove: bool) { | ||||
|         if let Some(action_tx) = &self.network_tx { | ||||
|             let _ = action_tx.send(Action::BalanceRequest(account_id, remove)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn set_balance_active(&mut self, index: usize) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let account_id = self.wallet_keys[index].account_id; | ||||
|             let _ = action_tx.send(Action::BalanceSetActive( | ||||
|                     self.balances.get(&account_id).cloned())); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn update_account_name(&mut self) { | ||||
|         if let Some(index) = self.table_state.selected() { | ||||
|             if let Some(action_tx) = &self.action_tx { | ||||
|                 let _ = action_tx.send(Action::RenameAccount( | ||||
|                         self.wallet_keys[index].name.clone() | ||||
|                 )); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn create_new_account(&mut self, name: String) { | ||||
|         let (pair, seed) = Pair::generate(); | ||||
|         let secret_seed = hex::encode(seed); | ||||
| @ -89,12 +121,10 @@ impl Accounts { | ||||
|         let address = AccountId32::from(seed.clone()) | ||||
|             .to_ss58check_with_version(Ss58AddressFormat::custom(1996)); | ||||
| 
 | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let _ = action_tx.send(Action::WalletLog( | ||||
|                 format!("new wallet '{}' with public address {} created", &name, &address), | ||||
|                 ActionLevel::Info, | ||||
|             )); | ||||
|         } | ||||
|         self.log_event( | ||||
|             format!("new wallet '{}' with public address {} created", 
 | ||||
|                 &name, &address), | ||||
|                 ActionLevel::Info); | ||||
| 
 | ||||
|         self.send_balance_request(account_id, false); | ||||
|         self.wallet_keys.push(AccountInfo { | ||||
| @ -112,29 +142,15 @@ impl Accounts { | ||||
|         if let Some(index) = self.table_state.selected() { | ||||
|             let old_name = self.wallet_keys[index].name.clone(); | ||||
| 
 | ||||
|             if let Some(action_tx) = &self.action_tx { | ||||
|                 let _ = action_tx.send(Action::WalletLog( | ||||
|                         format!("wallet '{}' renamed to {}", &new_name, &old_name), | ||||
|                         ActionLevel::Info, | ||||
|                 )); | ||||
|             } | ||||
| 
 | ||||
|             self.log_event(format!("wallet '{}' renamed to {}", 
 | ||||
|                     &new_name, &old_name), | ||||
|                     ActionLevel::Info); | ||||
|             self.wallet_keys[index].name = new_name; | ||||
|             self.save_to_file(); | ||||
| 
 | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn update_account_name(&mut self) { | ||||
|         if let Some(index) = self.table_state.selected() { | ||||
|             if let Some(action_tx) = &self.action_tx { | ||||
|                 let _ = action_tx.send(Action::RenameAccount( | ||||
|                         self.wallet_keys[index].name.clone() | ||||
|                 )); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|      fn swap_up(&mut self) { | ||||
|         if let Some(src_index) = self.table_state.selected() { | ||||
|             let dst_index = src_index.saturating_sub(1); | ||||
| @ -165,13 +181,9 @@ impl Accounts { | ||||
|                 self.previous_row(); | ||||
|                 self.save_to_file(); | ||||
| 
 | ||||
|                 if let Some(action_tx) = &self.action_tx { | ||||
|                     let _ = action_tx.send(Action::WalletLog( | ||||
|                             format!("wallet `{}` with public address {} removed", | ||||
|                                 &wallet.name, &wallet.address), | ||||
|                             ActionLevel::Warn, | ||||
|                     )); | ||||
|                 } | ||||
|                 self.log_event(format!("wallet `{}` with public address {} removed", | ||||
|                         &wallet.name, &wallet.address), | ||||
|                         ActionLevel::Warn); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| @ -215,12 +227,9 @@ impl Accounts { | ||||
|                             pair_signer, | ||||
|                     }); | ||||
|                 } | ||||
|                 if let Some(action_tx) = &self.action_tx { | ||||
|                     let _ = action_tx.send(Action::WalletLog( | ||||
|                             format!("read {} wallets from disk", self.wallet_keys.len()), | ||||
|                             ActionLevel::Info, | ||||
|                     )); | ||||
|                 } | ||||
|                 self.log_event(format!("read {} wallets from disk", 
 | ||||
|                         self.wallet_keys.len()), | ||||
|                         ActionLevel::Info); | ||||
|             }, | ||||
|             Err(_) => { | ||||
|                 let (pair, seed) = match std::fs::read_to_string("/etc/ghost/wallet-key") { | ||||
| @ -233,23 +242,17 @@ impl Accounts { | ||||
|                             .try_into() | ||||
|                             .expect("stored seed is valid length; qed"); | ||||
| 
 | ||||
|                         if let Some(action_tx) = &self.action_tx { | ||||
|                             let _ = action_tx.send(Action::WalletLog( | ||||
|                                     "wallet read from the `/etc/ghost/wallet-key`".to_string(), | ||||
|                                     ActionLevel::Warn, | ||||
|                             )); | ||||
|                         } | ||||
|                         self.log_event( | ||||
|                             "wallet read from the `/etc/ghost/wallet-key`".to_string(), | ||||
|                             ActionLevel::Warn); | ||||
| 
 | ||||
|                         let pair = Pair::from_seed(&seed); | ||||
|                         (pair, seed) | ||||
|                     } | ||||
|                     Err(_) => { | ||||
|                         if let Some(action_tx) = &self.action_tx { | ||||
|                             let _ = action_tx.send(Action::WalletLog( | ||||
|                                     "no wallets found on disk, new wallet created".to_string(), | ||||
|                                     ActionLevel::Warn, | ||||
|                             )); | ||||
|                         } | ||||
|                         self.log_event( | ||||
|                             "no wallets found on disk, new wallet created".to_string(), | ||||
|                             ActionLevel::Warn); | ||||
|                         let (pair, seed) = Pair::generate(); | ||||
|                         (pair, seed) | ||||
|                     } | ||||
| @ -276,23 +279,17 @@ impl Accounts { | ||||
|         }; | ||||
|         self.table_state.select(Some(0)); | ||||
|         self.scroll_state = self.scroll_state.content_length(self.wallet_keys.len()); | ||||
|         self.send_wallet_change(0); | ||||
|         self.set_balance_active(0); | ||||
|         self.set_used_account(0); | ||||
|         Ok(()) | ||||
|     } | ||||
| 
 | ||||
|     fn send_wallet_change(&mut self, index: usize) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let _ = action_tx.send(Action::UsedAccount(self.wallet_keys[index] | ||||
|                     .pair_signer | ||||
|                     .account_id() | ||||
|                     .clone())); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn first_row(&mut self) { | ||||
|         if self.wallet_keys.len() > 0 { | ||||
|             self.table_state.select(Some(0)); | ||||
|             self.scroll_state = self.scroll_state.position(0); | ||||
|             self.set_balance_active(0); | ||||
|             self.set_used_account(0); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -309,6 +306,8 @@ impl Accounts { | ||||
|         }; | ||||
|         self.table_state.select(Some(i)); | ||||
|         self.scroll_state = self.scroll_state.position(i); | ||||
|         self.set_balance_active(i); | ||||
|         self.set_used_account(i); | ||||
|     } | ||||
| 
 | ||||
|     fn last_row(&mut self) { | ||||
| @ -316,6 +315,8 @@ impl Accounts { | ||||
|             let last = self.wallet_keys.len() - 1; | ||||
|             self.table_state.select(Some(last)); | ||||
|             self.scroll_state = self.scroll_state.position(last); | ||||
|             self.set_balance_active(last); | ||||
|             self.set_used_account(last); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -332,6 +333,8 @@ impl Accounts { | ||||
|         }; | ||||
|         self.table_state.select(Some(i)); | ||||
|         self.scroll_state = self.scroll_state.position(i); | ||||
|         self.set_balance_active(i); | ||||
|         self.set_used_account(i); | ||||
|     } | ||||
| 
 | ||||
|     fn prepare_u128(&self, value: u128, after: usize, ticker: Option<&str>) -> String { | ||||
| @ -384,7 +387,14 @@ impl Component for Accounts { | ||||
|             Action::NewAccount(name) => self.create_new_account(name), | ||||
|             Action::UpdateAccountName(new_name) => self.rename_account(new_name), | ||||
|             Action::BalanceResponse(account_id, balance) => { | ||||
|                 let _ = self.balances.insert(account_id, balance); | ||||
|                 if self.wallet_keys.iter().any(|wallet| wallet.account_id == account_id) { | ||||
|                     let _ = self.balances.insert(account_id, balance); | ||||
|                     if let Some(index) = self.table_state.selected() { | ||||
|                         if self.wallet_keys[index].account_id == account_id { | ||||
|                             self.set_balance_active(index); | ||||
|                         } | ||||
|                     } | ||||
|                 } | ||||
|             }, | ||||
|             _ => {} | ||||
|         }; | ||||
|  | ||||
| @ -112,10 +112,12 @@ impl PartialComponent for AddAddressBookRecord { | ||||
|         match current_tab { | ||||
|             CurrentTab::AddAddressBookRecord => self.is_active = true, | ||||
|             _ => { | ||||
|                 self.is_active = false; | ||||
|                 self.name = Input::new(String::new()); | ||||
|                 self.address = Input::new(String::new()); | ||||
|                 self.name_or_address = NameOrAddress::Name; | ||||
|                 if self.is_active { | ||||
|                     self.is_active = false; | ||||
|                     self.name = Input::new(String::new()); | ||||
|                     self.address = Input::new(String::new()); | ||||
|                     self.name_or_address = NameOrAddress::Name; | ||||
|                 } | ||||
|             }, | ||||
|         }; | ||||
|     } | ||||
|  | ||||
| @ -12,22 +12,35 @@ use ratatui::{ | ||||
|     widgets::{Block, ScrollbarState, Row, Table, TableState}, 
 | ||||
|     Frame | ||||
| }; | ||||
| use subxt::ext::sp_core::crypto::{ByteArray, Ss58Codec, Ss58AddressFormat, AccountId32}; | ||||
| use subxt::ext::sp_core::crypto::{ | ||||
|     ByteArray, Ss58Codec, Ss58AddressFormat, AccountId32, | ||||
| }; | ||||
| use tokio::sync::mpsc::UnboundedSender; | ||||
| use std::sync::mpsc::Sender; | ||||
| 
 | ||||
| use super::{Component, PartialComponent, CurrentTab}; | ||||
| use crate::types::ActionLevel; | ||||
| use crate::types::{ActionLevel, SystemAccount}; | ||||
| use crate::widgets::DotSpinner; | ||||
| use crate::{ | ||||
|     action::Action, 
 | ||||
|     config::Config, 
 | ||||
|     palette::StylePalette, 
 | ||||
| }; | ||||
| 
 | ||||
| struct BookRecord { | ||||
|     name: String, | ||||
|     address: String, | ||||
|     account_id: [u8; 32], | ||||
|     seed: String, | ||||
| } | ||||
| 
 | ||||
| pub struct AddressBook { | ||||
|     is_active: bool, | ||||
|     action_tx: Option<UnboundedSender<Action>>, | ||||
|     network_tx: Option<Sender<Action>>, | ||||
|     address_book_file: PathBuf, | ||||
|     address_book: Vec<(String, String, AccountId32, String)>, | ||||
|     address_book: Vec<BookRecord>, | ||||
|     balances: std::collections::HashMap<[u8; 32], SystemAccount>, | ||||
|     scroll_state: ScrollbarState, | ||||
|     table_state: TableState, | ||||
|     palette: StylePalette, | ||||
| @ -44,8 +57,10 @@ impl AddressBook { | ||||
|         Self { | ||||
|             is_active: false, | ||||
|             action_tx: None, | ||||
|             network_tx: None, | ||||
|             address_book_file: Default::default(), | ||||
|             address_book: Vec::new(), | ||||
|             address_book: Default::default(), | ||||
|             balances: Default::default(), | ||||
|             scroll_state: ScrollbarState::new(0), | ||||
|             table_state: TableState::new(), | ||||
|             palette: StylePalette::default(), | ||||
| @ -55,7 +70,28 @@ impl AddressBook { | ||||
|     fn save_to_file(&mut self) { | ||||
|         let mut file = File::create(&self.address_book_file).unwrap(); | ||||
|         for wallet in self.address_book.iter() { | ||||
|             writeln!(file, "{}:0x{}", wallet.0, &wallet.3).unwrap(); | ||||
|             writeln!(file, "{}:0x{}", wallet.name, &wallet.seed).unwrap(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn send_transfer_to(&mut self) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             if let Some(index) = self.table_state.selected() { | ||||
|                 let _ = action_tx.send(Action::TransferTo( | ||||
|                         self.address_book[index].address.clone())); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn send_balance_request(&mut self, account_id: [u8; 32], remove: bool) { | ||||
|         if let Some(network_tx) = &self.network_tx { | ||||
|             let _ = network_tx.send(Action::BalanceRequest(account_id, remove)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn log_event(&mut self, message: String, level: ActionLevel) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let _ = action_tx.send(Action::WalletLog(message, level)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -70,24 +106,26 @@ impl AddressBook { | ||||
|                     let (name, seed) = line.split_at(line_split_at); | ||||
|                     let seed_str = &seed[3..]; | ||||
| 
 | ||||
|                     let seed: [u8; 32] = hex::decode(seed_str) | ||||
|                     let account_id: [u8; 32] = hex::decode(seed_str) | ||||
|                         .expect("stored seed is valid hex string; qed") | ||||
|                         .as_slice() | ||||
|                         .try_into() | ||||
|                         .expect("stored seed is valid length; qed"); | ||||
| 
 | ||||
|                     let account_id = AccountId32::from(seed); | ||||
|                     let address = AccountId32::from(seed.clone()) | ||||
|                     let address = AccountId32::from(account_id) | ||||
|                         .to_ss58check_with_version(Ss58AddressFormat::custom(1996)); | ||||
|                     self.address_book.push((name.to_string(), address, account_id, seed_str.to_string())); | ||||
| 
 | ||||
|                     self.address_book.push(BookRecord { | ||||
|                         name: name.to_string(), 
 | ||||
|                         address, 
 | ||||
|                         account_id, 
 | ||||
|                         seed: seed_str.to_string(), | ||||
|                     }); | ||||
|                     self.send_balance_request(account_id, false); | ||||
|                 } | ||||
|                 if let Some(action_tx) = &self.action_tx { | ||||
|                     let _ = action_tx.send(Action::WalletLog( | ||||
|                             format!("read {} records from address book", self.address_book.len()), | ||||
|                             ActionLevel::Info, | ||||
|                     )); | ||||
|                 } | ||||
|                 self.log_event( | ||||
|                     format!("read {} records from address book", self.address_book.len()), | ||||
|                     ActionLevel::Info) | ||||
|             }, | ||||
|             Err(_) => { | ||||
|                 let chad_boyz = vec![ | ||||
| @ -114,17 +152,20 @@ impl AddressBook { | ||||
|                             .as_slice() | ||||
|                             .try_into() | ||||
|                             .expect("stored seed is valid length; qed"); | ||||
|                         let chad_account_id = AccountId32::from(chad_account_id); | ||||
|                         let address = AccountId32::from(chad_account_id.clone()) | ||||
|                         let address = AccountId32::from(chad_account_id) | ||||
|                             .to_ss58check_with_version(Ss58AddressFormat::custom(1996)); | ||||
|                         self.address_book.push((chad_info.0.to_string(), address, chad_account_id, chad_info.1.to_string())); | ||||
| 
 | ||||
|                         self.address_book.push(BookRecord { | ||||
|                             name: chad_info.0.to_string(), 
 | ||||
|                             address, 
 | ||||
|                             account_id: chad_account_id, 
 | ||||
|                             seed: chad_info.1.to_string(), | ||||
|                         }); | ||||
|                         self.send_balance_request(chad_account_id, false); | ||||
|                     }); | ||||
|                 if let Some(action_tx) = &self.action_tx { | ||||
|                     let _ = action_tx.send(Action::WalletLog( | ||||
|                             format!("address book is empty, filling it with giga chad boyz as default"), | ||||
|                             ActionLevel::Warn, | ||||
|                     )); | ||||
|                 } | ||||
|                 self.log_event( | ||||
|                     format!("address book is empty, filling it with giga chad boyz as default"), | ||||
|                     ActionLevel::Warn) | ||||
|             } | ||||
|         }; | ||||
|         self.scroll_state = self.scroll_state.content_length(self.address_book.len()); | ||||
| @ -133,14 +174,11 @@ impl AddressBook { | ||||
| 
 | ||||
|     fn rename_record(&mut self, new_name: String) { | ||||
|         if let Some(index) = self.table_state.selected() { | ||||
|             let old_name = self.address_book[index].0.clone(); | ||||
|             if let Some(action_tx) = &self.action_tx { | ||||
|                 let _ = action_tx.send(Action::WalletLog( | ||||
|                         format!("record renamed from {} to {}", &old_name, &new_name), | ||||
|                         ActionLevel::Info, | ||||
|                 )); | ||||
|             } | ||||
|             self.address_book[index].0 = new_name; | ||||
|             let old_name = self.address_book[index].name.clone(); | ||||
|             self.log_event( | ||||
|                 format!("record renamed from {} to {}", &old_name, &new_name), | ||||
|                 ActionLevel::Info); | ||||
|             self.address_book[index].name = new_name; | ||||
|             self.save_to_file(); | ||||
|         } | ||||
|     } | ||||
| @ -149,42 +187,41 @@ impl AddressBook { | ||||
|         match AccountId32::from_ss58check_with_version(&address) { | ||||
|             Ok((account_id, format)) => { | ||||
|                 if format != Ss58AddressFormat::custom(1996) { | ||||
|                     if let Some(action_tx) = &self.action_tx { | ||||
|                         let _ = action_tx.send(Action::WalletLog( | ||||
|                                 format!("provided public address for {} is not part of Casper/Ghost ecosystem", &address), | ||||
|                                 ActionLevel::Error, | ||||
|                         )); | ||||
|                     } | ||||
|                     self.log_event( | ||||
|                         format!("provided public address for {} is not part of Casper/Ghost ecosystem", &address), | ||||
|                         ActionLevel::Error); | ||||
|                 } | ||||
| 
 | ||||
|                 if let Some(action_tx) = &self.action_tx { | ||||
|                     let _ = action_tx.send(Action::WalletLog( | ||||
|                             format!("account {} with address {} added to address book", &name, &address), | ||||
|                             ActionLevel::Info, | ||||
|                     )); | ||||
|                 } | ||||
|                 self.log_event( | ||||
|                     format!("account {} with address {} added to address book", &name, &address), | ||||
|                     ActionLevel::Info); | ||||
| 
 | ||||
|                 let seed_vec = account_id.to_raw_vec(); | ||||
|                 let mut account_id = [0u8; 32]; | ||||
|                 account_id.copy_from_slice(&seed_vec); | ||||
|                 let seed_str = hex::encode(seed_vec); | ||||
|                 self.address_book.push((name, address, account_id, seed_str)); | ||||
| 
 | ||||
|                 self.address_book.push(BookRecord { | ||||
|                     name, 
 | ||||
|                     address, 
 | ||||
|                     account_id, 
 | ||||
|                     seed: seed_str, | ||||
|                 }); | ||||
|                 self.save_to_file(); | ||||
|                 self.last_row(); | ||||
|                 self.send_balance_request(account_id, false); | ||||
|             }, | ||||
|             Err(_) => if let Some(action_tx) = &self.action_tx { | ||||
|                 let _ = action_tx.send(Action::WalletLog( | ||||
|                         format!("provided account address {} is invalid", &address), | ||||
|                         ActionLevel::Error, | ||||
|                 )); | ||||
|             } | ||||
|             Err(_) => self.log_event( | ||||
|                 format!("provided account address {} is invalid", &address), | ||||
|                 ActionLevel::Error), | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     fn update_address_book_record(&mut self) { | ||||
|         if let Some(index) = self.table_state.selected() { | ||||
|             if let Some(action_tx) = &self.action_tx { | ||||
|                 let _ = action_tx.send(Action::RenameAddressBookRecord( | ||||
|                         self.address_book[index].0.clone() | ||||
|                         self.address_book[index].name.clone() | ||||
|                 )); | ||||
|             } | ||||
|         } | ||||
| @ -214,9 +251,12 @@ impl AddressBook { | ||||
| 
 | ||||
|     fn delete_row(&mut self) { | ||||
|         if let Some(index) = self.table_state.selected() { | ||||
|             let _ = self.address_book.remove(index); | ||||
|             let record = self.address_book.remove(index); | ||||
|             self.previous_row(); | ||||
|             self.save_to_file(); | ||||
|             self.log_event(format!("record `{}` with public address {} removed", | ||||
|                     &record.name, &record.address), | ||||
|                     ActionLevel::Warn); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -264,6 +304,16 @@ impl AddressBook { | ||||
|         self.table_state.select(Some(i)); | ||||
|         self.scroll_state = self.scroll_state.position(i); | ||||
|     } | ||||
| 
 | ||||
|     fn prepare_u128(&self, maybe_value: Option<u128>, ticker: Option<&str>, after: usize) -> String { | ||||
|         match maybe_value { | ||||
|             Some(value) => { | ||||
|                 let value = value as f64 / 10f64.powi(18); | ||||
|                 format!("{:.after$}{}", value, ticker.unwrap_or_default()) | ||||
|             }, | ||||
|             None => DotSpinner::default().to_string(), | ||||
|         } | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| impl PartialComponent for AddressBook { | ||||
| @ -276,6 +326,15 @@ impl PartialComponent for AddressBook { | ||||
| } | ||||
| 
 | ||||
| impl Component for AddressBook { | ||||
|     fn register_network_handler(&mut self, tx: Sender<Action>) -> Result<()> { | ||||
|         self.network_tx = Some(tx); | ||||
|         Ok(()) | ||||
|     } | ||||
|     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::Wallet) { | ||||
|             self.palette.with_normal_style(style.get("normal_style").copied()); | ||||
| @ -295,17 +354,17 @@ impl Component for AddressBook { | ||||
|         Ok(()) | ||||
|     } | ||||
| 
 | ||||
|     fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> { | ||||
|         self.action_tx = Some(tx); | ||||
|         Ok(()) | ||||
|     } | ||||
| 
 | ||||
|     fn update(&mut self, action: Action) -> Result<Option<Action>> { | ||||
|         match action { | ||||
|             Action::UpdateAddressBookRecord(new_name) => 
 | ||||
|                 self.rename_record(new_name), | ||||
|             Action::NewAddressBookRecord(name, address) => 
 | ||||
|                 self.add_new_record(name, address), | ||||
|             Action::BalanceResponse(account_id, balance) => { | ||||
|                 if self.address_book.iter().any(|record| record.account_id == account_id) { | ||||
|                     let _ = self.balances.insert(account_id, balance); | ||||
|                 } | ||||
|             }, | ||||
|             _ => {} | ||||
|         }; | ||||
|         Ok(None) | ||||
| @ -313,17 +372,20 @@ impl Component for AddressBook { | ||||
| 
 | ||||
| 
 | ||||
|     fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> { | ||||
|         match key.code { | ||||
|            KeyCode::Up | KeyCode::Char('k') if self.is_active => self.previous_row(), 
 | ||||
|            KeyCode::Down | KeyCode::Char('j') if self.is_active => self.next_row(), 
 | ||||
|            KeyCode::Char('g') if self.is_active => self.first_row(), | ||||
|            KeyCode::Char('G') if self.is_active => self.last_row(), | ||||
|            KeyCode::Char('K') if self.is_active => self.swap_up(), | ||||
|            KeyCode::Char('J') if self.is_active => self.swap_down(), | ||||
|            KeyCode::Char('D') if self.is_active => self.delete_row(), | ||||
|            KeyCode::Char('R') if self.is_active => self.update_address_book_record(), | ||||
|            _ => {}, | ||||
|         }; | ||||
|         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::Char('K') => self.swap_up(), | ||||
|                 KeyCode::Char('J') => self.swap_down(), | ||||
|                 KeyCode::Char('D') => self.delete_row(), | ||||
|                 KeyCode::Char('R') => self.update_address_book_record(), | ||||
|                 KeyCode::Enter => self.send_transfer_to(), | ||||
|                 _ => {}, | ||||
|             }; | ||||
|         } | ||||
|         Ok(None) | ||||
|     } | ||||
| 
 | ||||
| @ -334,15 +396,24 @@ impl Component for AddressBook { | ||||
|         let table = Table::new( | ||||
|             self.address_book | ||||
|                 .iter() | ||||
|                 .map(|info| Row::new(vec![ | ||||
|                         Cell::from(Text::from(info.0.clone()).alignment(Alignment::Left)), 
 | ||||
|                         Cell::from(Text::from(info.1.clone()).alignment(Alignment::Center)), 
 | ||||
|                         Cell::from(Text::from("31 CSPR".to_string()).alignment(Alignment::Right)), | ||||
|                 ])), | ||||
|                 .map(|info| { | ||||
|                     let balance = self.balances | ||||
|                         .get(&info.account_id) | ||||
|                         .map(|inner_balance| { | ||||
|                             inner_balance.free | ||||
|                                 .saturating_add(inner_balance.reserved) | ||||
|                                 .saturating_add(inner_balance.frozen) | ||||
|                         }); | ||||
|                     Row::new(vec![ | ||||
|                         Cell::from(Text::from(info.name.clone()).alignment(Alignment::Left)), 
 | ||||
|                         Cell::from(Text::from(info.address.clone()).alignment(Alignment::Center)), 
 | ||||
|                         Cell::from(Text::from(self.prepare_u128(balance, Some(" CSPR"), 2)).alignment(Alignment::Right)), | ||||
|                     ]) | ||||
|                 }), | ||||
|             [ | ||||
|                 Constraint::Min(5), | ||||
|                 Constraint::Max(51), | ||||
|                 Constraint::Min(10), | ||||
|                 Constraint::Min(11), | ||||
|             ], | ||||
|         ) | ||||
|         .style(self.palette.create_basic_style(false)) | ||||
|  | ||||
| @ -8,6 +8,7 @@ use ratatui::{ | ||||
| 
 | ||||
| use super::{Component, PartialComponent, CurrentTab}; | ||||
| use crate::{ | ||||
|     widgets::DotSpinner, | ||||
|     action::Action, 
 | ||||
|     config::Config, 
 | ||||
|     palette::StylePalette, 
 | ||||
| @ -20,6 +21,7 @@ pub struct Balance { | ||||
|     transferable_balance: Option<u128>, | ||||
|     locked_balance: Option<u128>, | ||||
|     bonded_balance: Option<u128>, | ||||
|     nonce: Option<u32>, | ||||
|     palette: StylePalette | ||||
| } | ||||
| 
 | ||||
| @ -39,13 +41,19 @@ impl Balance { | ||||
|             transferable_balance: None, | ||||
|             locked_balance: None, | ||||
|             bonded_balance: None, | ||||
|             nonce: None, | ||||
|             palette: StylePalette::default(), | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn prepare_u128(&self, value: u128, after: usize) -> String { | ||||
|         let value = value as f64 / 10f64.powi(18); | ||||
|         format!("{:.after$}", value) | ||||
|     fn prepare_u128(&self, maybe_value: Option<u128>, ticker: Option<&str>, after: usize) -> String { | ||||
|         match maybe_value { | ||||
|             Some(value) => { | ||||
|                 let value = value as f64 / 10f64.powi(18); | ||||
|                 format!("{:.after$}{}", value, ticker.unwrap_or_default()) | ||||
|             }, | ||||
|             None => DotSpinner::default().to_string() | ||||
|         } | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| @ -73,6 +81,28 @@ impl Component for Balance { | ||||
| 
 | ||||
|     fn update(&mut self, action: Action) -> Result<Option<Action>> { | ||||
|         match action { | ||||
|             Action::BalanceSetActive(maybe_balance) => { | ||||
|                 match maybe_balance { | ||||
|                     Some(balance) => { | ||||
|                         self.transferable_balance = Some(balance.free); | ||||
|                         self.locked_balance = Some(balance.reserved); | ||||
|                         self.bonded_balance = Some(balance.frozen); | ||||
| 
 | ||||
|                         let total_balance = balance.free | ||||
|                             .saturating_add(balance.reserved) | ||||
|                             .saturating_add(balance.frozen); | ||||
|                         self.total_balance = Some(total_balance); | ||||
|                         self.nonce = Some(balance.nonce); | ||||
|                     }, | ||||
|                     None => { | ||||
|                         self.transferable_balance = None; | ||||
|                         self.locked_balance = None; | ||||
|                         self.bonded_balance = None; | ||||
|                         self.total_balance = None; | ||||
|                         self.nonce = None; | ||||
|                     } | ||||
|                 } | ||||
|             }, | ||||
|             _ => {} | ||||
|         }; | ||||
|         Ok(None) | ||||
| @ -85,43 +115,45 @@ impl Component for Balance { | ||||
| 
 | ||||
|         let table = Table::new( | ||||
|             [ | ||||
|                 Row::new(vec![ | ||||
|                     Cell::from(Text::from("nonce: ".to_string()).alignment(Alignment::Left)), | ||||
|                     Cell::from(Text::from(self.prepare_u128( | ||||
|                                 self.nonce.map(|n| n as u128), 
 | ||||
|                                 None, | ||||
|                                 0)).alignment(Alignment::Right)), | ||||
|                 ]), | ||||
|                 Row::new(vec![ | ||||
|                     Cell::from(Text::from("account: ".to_string()).alignment(Alignment::Left)), | ||||
|                     Cell::from(Text::from(self.prepare_u128( | ||||
|                                 self.total_balance.unwrap_or_default(), 
 | ||||
|                                 Self::DECIMALS_FOR_BALANCE, | ||||
|                                 )).alignment(Alignment::Center)), | ||||
|                     Cell::from(Text::from("CSPR".to_string()).alignment(Alignment::Right)) | ||||
|                                 self.total_balance, 
 | ||||
|                                 Some(" CSPR"), | ||||
|                                 Self::DECIMALS_FOR_BALANCE)).alignment(Alignment::Right)), | ||||
|                 ]), | ||||
|                 Row::new(vec![ | ||||
|                     Cell::from(Text::from("free: ".to_string()).alignment(Alignment::Left)), | ||||
|                     Cell::from(Text::from(self.prepare_u128( | ||||
|                                 self.transferable_balance.unwrap_or_default(), 
 | ||||
|                                 Self::DECIMALS_FOR_BALANCE, | ||||
|                                 )).alignment(Alignment::Center)), | ||||
|                     Cell::from(Text::from("CSPR".to_string()).alignment(Alignment::Right)), | ||||
|                                 self.transferable_balance, 
 | ||||
|                                 Some(" CSPR"), | ||||
|                                 Self::DECIMALS_FOR_BALANCE)).alignment(Alignment::Right)) | ||||
|                 ]), | ||||
|                 Row::new(vec![ | ||||
|                     Cell::from(Text::from("locked: ".to_string()).alignment(Alignment::Left)), | ||||
|                     Cell::from(Text::from(self.prepare_u128( | ||||
|                                 self.locked_balance.unwrap_or_default(), 
 | ||||
|                                 Self::DECIMALS_FOR_BALANCE, | ||||
|                                 )).alignment(Alignment::Center)), | ||||
|                     Cell::from(Text::from("CSPR".to_string()).alignment(Alignment::Right)), | ||||
|                                 self.locked_balance, 
 | ||||
|                                 Some(" CSPR"), | ||||
|                                 Self::DECIMALS_FOR_BALANCE)).alignment(Alignment::Right)), | ||||
|                 ]), | ||||
|                 Row::new(vec![ | ||||
|                     Cell::from(Text::from("bonded: ".to_string()).alignment(Alignment::Left)), | ||||
|                     Cell::from(Text::from(self.prepare_u128( | ||||
|                                 self.bonded_balance.unwrap_or_default(), 
 | ||||
|                                 Self::DECIMALS_FOR_BALANCE, | ||||
|                                 )).alignment(Alignment::Center)), | ||||
|                     Cell::from(Text::from("CSPR".to_string()).alignment(Alignment::Right)), | ||||
|                                 self.bonded_balance, 
 | ||||
|                                 Some(" CSPR"), | ||||
|                                 Self::DECIMALS_FOR_BALANCE)).alignment(Alignment::Right)), | ||||
|                 ]), | ||||
|             ], | ||||
|             [ | ||||
|                 Constraint::Max(10), | ||||
|                 Constraint::Min(0), | ||||
|                 Constraint::Length(5), | ||||
|                 Constraint::Min(14), | ||||
|             ] | ||||
|         ) | ||||
|         .block(Block::bordered() | ||||
|  | ||||
| @ -43,6 +43,7 @@ pub enum CurrentTab { | ||||
|     AddAddressBookRecord, | ||||
|     RenameAccount, | ||||
|     RenameAddressBookRecord, | ||||
|     Transfer, | ||||
| } | ||||
| 
 | ||||
| pub trait PartialComponent: Component { | ||||
| @ -66,11 +67,11 @@ impl Default for Wallet { | ||||
|                 Box::new(Balance::default()), | ||||
|                 Box::new(AddressBook::default()), | ||||
|                 Box::new(EventLogs::default()), | ||||
|                 Box::new(Transfer::default()), | ||||
|                 Box::new(AddAccount::default()), | ||||
|                 Box::new(RenameAccount::default()), | ||||
|                 Box::new(AddAddressBookRecord::default()), | ||||
|                 Box::new(RenameAddressBookRecord::default()), | ||||
|                 Box::new(Transfer::default()), | ||||
|             ], | ||||
|         } | ||||
|     } | ||||
| @ -125,6 +126,7 @@ impl Component for Wallet { | ||||
|             CurrentTab::AddAccount | 
 | ||||
|                 CurrentTab::RenameAccount | 
 | ||||
|                 CurrentTab::RenameAddressBookRecord | 
 | ||||
|                 CurrentTab::Transfer | | ||||
|                 CurrentTab::AddAddressBookRecord => match key.code { | ||||
|                     KeyCode::Esc => { | ||||
|                         self.current_tab = CurrentTab::Accounts; | ||||
| @ -159,7 +161,13 @@ impl Component for Wallet { | ||||
|                         component.set_active(self.current_tab.clone()); | ||||
|                     } | ||||
|                 }, | ||||
|                 KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => { | ||||
|                 KeyCode::Char('T') => { | ||||
|                     self.current_tab = CurrentTab::Transfer; | ||||
|                     for component in self.components.iter_mut() { | ||||
|                         component.set_active(self.current_tab.clone()); | ||||
|                     } | ||||
|                 }, | ||||
|                 KeyCode::Char('l') | KeyCode::Right => { | ||||
|                     self.move_right(); | ||||
|                     for component in self.components.iter_mut() { | ||||
|                         component.set_active(self.current_tab.clone()); | ||||
| @ -186,11 +194,12 @@ impl Component for Wallet { | ||||
|             Action::SetActiveScreen(Mode::Wallet) => self.is_active = true, | ||||
|             Action::UpdateAccountName(_) | Action::NewAccount(_) => 
 | ||||
|                 self.current_tab = CurrentTab::Accounts, | ||||
|             Action::UpdateAddressBookRecord(_) | Action::NewAddressBookRecord(_, _) => 
 | ||||
|             Action::UpdateAddressBookRecord(_) | Action::NewAddressBookRecord(_, _) | Action::ClosePopup => 
 | ||||
|                 self.current_tab = CurrentTab::AddressBook, | ||||
|             Action::RenameAccount(_) => self.current_tab = CurrentTab::RenameAccount, | ||||
|             Action::RenameAddressBookRecord(_) => 
 | ||||
|                 self.current_tab = CurrentTab::RenameAddressBookRecord, | ||||
|             Action::TransferTo(_) => self.current_tab = CurrentTab::Transfer, | ||||
|             _ => {} | ||||
|         } | ||||
|         for component in self.components.iter_mut() { | ||||
| @ -229,6 +238,6 @@ pub fn account_layout(area: Rect) -> [Rect; 3] { | ||||
|     Layout::vertical([ | ||||
|         Constraint::Max(4), | ||||
|         Constraint::Min(0), | ||||
|         Constraint::Max(6), | ||||
|         Constraint::Max(7), | ||||
|     ]).areas(place) | ||||
| } | ||||
|  | ||||
| @ -28,7 +28,7 @@ impl Default for Overview { | ||||
| } | ||||
| 
 | ||||
| impl Overview { | ||||
|     const DECIMALS_FOR_BALANCE: usize = 5; | ||||
|     const DECIMALS_FOR_BALANCE: usize = 6; | ||||
| 
 | ||||
|     pub fn new() -> Self { | ||||
|         Self { | ||||
|  | ||||
| @ -1,10 +1,15 @@ | ||||
| use color_eyre::Result; | ||||
| use crossterm::event::KeyEvent; | ||||
| use crossterm::event::{KeyCode, KeyEvent, KeyEventKind}; | ||||
| use ratatui::{ | ||||
|     layout::{Constraint, Flex, Layout, Rect}, 
 | ||||
|     widgets::{Block, Clear}, 
 | ||||
|     layout::{Alignment, Constraint, Flex, Layout, Position, Rect}, | ||||
|     widgets::{Block, Clear, Paragraph}, | ||||
|     Frame, | ||||
|     prelude::Stylize, | ||||
| }; | ||||
| use tokio::sync::mpsc::UnboundedSender; | ||||
| use std::sync::mpsc::Sender; | ||||
| 
 | ||||
| use subxt::ext::sp_core::crypto::{ | ||||
|     ByteArray, Ss58Codec, Ss58AddressFormat, AccountId32, | ||||
| }; | ||||
| 
 | ||||
| use super::{Component, PartialComponent, CurrentTab}; | ||||
| @ -12,12 +17,26 @@ use crate::{ | ||||
|     action::Action, 
 | ||||
|     config::Config, 
 | ||||
|     palette::StylePalette, 
 | ||||
|     types::ActionLevel, 
 | ||||
|     widgets::{Input, InputRequest}, | ||||
| }; | ||||
| 
 | ||||
| #[derive(Debug)] | ||||
| enum ReceiverOrAmount { | ||||
|     Receiver, | ||||
|     Amount, | ||||
| } | ||||
| 
 | ||||
| #[derive(Debug)] | ||||
| pub struct Transfer { | ||||
|     network_tx: Option<Sender<Action>>, | ||||
|     action_tx: Option<UnboundedSender<Action>>, | ||||
|     receiver_or_amount: ReceiverOrAmount, | ||||
|     sender: String, | ||||
|     receiver: Input, | ||||
|     amount: Input, | ||||
|     palette: StylePalette, | ||||
|     is_shown: bool, | ||||
|     is_active: bool, | ||||
| } | ||||
| 
 | ||||
| impl Default for Transfer { | ||||
| @ -29,17 +48,136 @@ impl Default for Transfer { | ||||
| impl Transfer { | ||||
|     pub fn new() -> Self { | ||||
|         Self { | ||||
|             is_shown: false, | ||||
|             sender: Default::default(), | ||||
|             network_tx: None, | ||||
|             action_tx: None, | ||||
|             receiver_or_amount: ReceiverOrAmount::Receiver, | ||||
|             receiver: Input::new(String::new()), | ||||
|             amount: Input::new(String::new()), | ||||
|             palette: StylePalette::default(), | ||||
|             is_active: false, | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn log_event(&mut self, message: String, level: ActionLevel) { | ||||
|         if let Some(action_tx) = &self.action_tx { | ||||
|             let _ = action_tx.send(Action::WalletLog(message, level)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn submit_message(&mut self) { | ||||
|         match self.receiver_or_amount { | ||||
|             ReceiverOrAmount::Receiver => 
 | ||||
|                 self.receiver_or_amount = ReceiverOrAmount::Amount, | ||||
|             ReceiverOrAmount::Amount => if let Some(network_tx) = &self.network_tx { | ||||
|                 match AccountId32::from_ss58check_with_version(self.receiver.value()) { | ||||
|                     Ok((_account_id, format)) if format != Ss58AddressFormat::custom(1996) => { | ||||
|                         self.log_event( | ||||
|                             format!("provided public address for {} is not part of Casper/Ghost ecosystem", self.receiver.value()), | ||||
|                             ActionLevel::Error); | ||||
|                     }, | ||||
|                     Ok((account_id, format)) if format == Ss58AddressFormat::custom(1996) => { | ||||
|                         let seed_vec = account_id.to_raw_vec(); | ||||
|                         let mut account_id = [0u8; 32]; | ||||
|                         account_id.copy_from_slice(&seed_vec); | ||||
| 
 | ||||
|                         match self.amount.value().parse::<f64>() { | ||||
|                             Ok(value) => { | ||||
|                                 let amount = (value * 1_000_000_000_000_000_000.0) as u128; | ||||
|                                 let _ = network_tx.send(Action::TransferBalance( | ||||
|                                         self.sender.clone(), account_id, 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), | ||||
|                         } | ||||
|                     }, | ||||
|                     _ => self.log_event( | ||||
|                         format!("could not create valid account id from {}", self.receiver.value()), | ||||
|                         ActionLevel::Error), | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn enter_char(&mut self, new_char: char) { | ||||
|         match self.receiver_or_amount { | ||||
|             ReceiverOrAmount::Receiver => { | ||||
|                 let _ = self.receiver.handle(InputRequest::InsertChar(new_char)); | ||||
|             }, | ||||
|             ReceiverOrAmount::Amount => { | ||||
|                 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) { | ||||
|         match self.receiver_or_amount { | ||||
|             ReceiverOrAmount::Receiver => { | ||||
|                 let _ = self.receiver.handle(InputRequest::DeletePrevChar); | ||||
|             }, | ||||
|             ReceiverOrAmount::Amount => { | ||||
|                 let _ = self.amount.handle(InputRequest::DeletePrevChar); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn move_cursor_right(&mut self) { | ||||
|         match self.receiver_or_amount { | ||||
|             ReceiverOrAmount::Receiver => { | ||||
|                 let _ = self.receiver.handle(InputRequest::GoToNextChar); | ||||
|             }, | ||||
|             ReceiverOrAmount::Amount => { | ||||
|                 let _ = self.amount.handle(InputRequest::GoToNextChar); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     fn move_cursor_left(&mut self) { | ||||
|         match self.receiver_or_amount { | ||||
|             ReceiverOrAmount::Receiver => { | ||||
|                 let _ = self.receiver.handle(InputRequest::GoToPrevChar); | ||||
|             }, | ||||
|             ReceiverOrAmount::Amount => { | ||||
|                 let _ = self.amount.handle(InputRequest::GoToPrevChar); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| impl PartialComponent for Transfer { | ||||
|     fn set_active(&mut self, _current_tab: CurrentTab) {} | ||||
|     fn set_active(&mut self, current_tab: CurrentTab) { | ||||
|         match current_tab { | ||||
|             CurrentTab::Transfer => self.is_active = true, | ||||
|             _ => { | ||||
|                 if self.is_active { | ||||
|                     self.is_active = false; | ||||
|                     self.receiver = Input::new(String::new()); | ||||
|                     self.amount = Input::new(String::new()); | ||||
|                     self.receiver_or_amount = ReceiverOrAmount::Receiver; | ||||
|                 } | ||||
|             }, | ||||
|         }; | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| 
 | ||||
| impl Component for Transfer { | ||||
|     fn register_network_handler(&mut self, tx: Sender<Action>) -> Result<()> { | ||||
|         self.network_tx = Some(tx); | ||||
|         Ok(()) | ||||
|     } | ||||
| 
 | ||||
|     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::Wallet) { | ||||
|             self.palette.with_normal_style(style.get("normal_style").copied()); | ||||
| @ -52,28 +190,84 @@ impl Component for Transfer { | ||||
|     } | ||||
| 
 | ||||
|     fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> { | ||||
|         match key.code { | ||||
|             _ => {}, | ||||
|         }; | ||||
|         if self.is_active && key.kind == KeyEventKind::Press { | ||||
|             match key.code { | ||||
|                 KeyCode::Up => self.receiver_or_amount = ReceiverOrAmount::Receiver, | ||||
|                 KeyCode::Down => self.receiver_or_amount = ReceiverOrAmount::Amount, | ||||
|                 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<Option<Action>> { | ||||
|         match action { | ||||
|             Action::UsedAccount(seed) => self.sender = seed, | ||||
|             Action::TransferTo(who) => { | ||||
|                 self.receiver = Input::new(who); | ||||
|                 self.receiver_or_amount = ReceiverOrAmount::Amount; | ||||
|             } | ||||
|             _ => {} | ||||
|         }; | ||||
|         Ok(None) | ||||
|     } | ||||
| 
 | ||||
|     fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> { | ||||
|         if self.is_shown { | ||||
|             let block = Block::bordered().on_red().title("Transfer"); | ||||
|             let v = Layout::vertical([Constraint::Max(10)]).flex(Flex::Center); | ||||
|             let h = Layout::horizontal([Constraint::Max(55)]).flex(Flex::Center); | ||||
|             let [area] = v.areas(area); | ||||
|             let [area] = h.areas(area); | ||||
|             frame.render_widget(Clear, area); | ||||
|             frame.render_widget(block, area); | ||||
|         if self.is_active { | ||||
|             let size = area.as_size(); | ||||
|             let receiver_area = Rect::new(size.width / 2, size.height / 2, 50, 3); 
 | ||||
|             let amount_area = Rect::new(size.width / 2, size.height / 2 + 3, 50, 3); 
 | ||||
|             let (border_style, border_type) = self.palette.create_popup_style(); | ||||
| 
 | ||||
|             let input_receiver = Paragraph::new(self.receiver.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("Receiver")); | ||||
| 
 | ||||
|             let input_amount = 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("Amount to send")); | ||||
| 
 | ||||
|             let v = Layout::vertical([Constraint::Max(3)]).flex(Flex::Center); | ||||
|             let h = Layout::horizontal([Constraint::Max(50)]).flex(Flex::Center); | ||||
| 
 | ||||
|             let [receiver_area] = v.areas(receiver_area); | ||||
|             let [receiver_area] = h.areas(receiver_area); | ||||
|             let [amount_area] = v.areas(amount_area); | ||||
|             let [amount_area] = h.areas(amount_area); | ||||
| 
 | ||||
|             frame.render_widget(Clear, receiver_area); | ||||
|             frame.render_widget(Clear, amount_area); | ||||
|             frame.render_widget(input_receiver, receiver_area); | ||||
|             frame.render_widget(input_amount, amount_area); | ||||
| 
 | ||||
|             match self.receiver_or_amount { | ||||
|                 ReceiverOrAmount::Receiver => { | ||||
|                     frame.set_cursor_position(Position::new( | ||||
|                             receiver_area.x + self.receiver.cursor() as u16 + 1, | ||||
|                             receiver_area.y + 1 | ||||
|                     )); | ||||
|                 }, | ||||
|                 ReceiverOrAmount::Amount => { | ||||
|                     frame.set_cursor_position(Position::new( | ||||
|                             amount_area.x + self.amount.cursor() as u16 + 1, | ||||
|                             amount_area.y + 1 | ||||
|                     )); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|         Ok(()) | ||||
|     } | ||||
|  | ||||
| @ -4,9 +4,10 @@ use subxt::{ | ||||
|     backend::{ | ||||
|         legacy::LegacyRpcMethods, 
 | ||||
|         rpc::RpcClient, | ||||
|     }, | ||||
|     }, 
 | ||||
|     tx::{TxProgress, TxStatus}, 
 | ||||
|     utils::H256, 
 | ||||
|     OnlineClient | ||||
|     OnlineClient, | ||||
| }; | ||||
| 
 | ||||
| mod legacy_rpc_calls; | ||||
| @ -14,6 +15,7 @@ mod predefinded_calls; | ||||
| mod subscriptions; | ||||
| 
 | ||||
| use crate::{ | ||||
|     types::ActionLevel, | ||||
|     action::Action, 
 | ||||
|     casper::CasperConfig, | ||||
| }; | ||||
| @ -27,7 +29,8 @@ pub struct Network { | ||||
|     rpc_client: RpcClient, | ||||
|     best_hash: Option<H256>, | ||||
|     finalized_hash: Option<H256>, | ||||
|     accounts_to_watch: std::collections::HashSet<[u8; 32]> | ||||
|     accounts_to_watch: std::collections::HashSet<[u8; 32]>, | ||||
|     transactions_to_watch: Vec<TxProgress<CasperConfig, OnlineClient<CasperConfig>>>, | ||||
| } | ||||
| 
 | ||||
| impl Network { | ||||
| @ -45,6 +48,7 @@ impl Network { | ||||
|             best_hash: None, | ||||
|             finalized_hash: None, | ||||
|             accounts_to_watch: Default::default(), | ||||
|             transactions_to_watch: Default::default(), | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -59,6 +63,41 @@ impl Network { | ||||
|             }, | ||||
|             Action::NewFinalizedHash(hash) => { | ||||
|                 self.finalized_hash = Some(hash); | ||||
|                 let length = self.transactions_to_watch.len(); | ||||
|                 for i in (0..length).rev() { | ||||
|                     let pending_tx = &mut self.transactions_to_watch[i]; | ||||
|                     let ext_hash = pending_tx.extrinsic_hash(); | ||||
|                     match (*pending_tx).next().await { | ||||
|                         Some(Ok(status)) => { | ||||
|                             match status { | ||||
|                                 TxStatus::Validated => self.action_tx.send(Action::WalletLog(format!("transaction {} is part of future queue", ext_hash), ActionLevel::Info))?, | ||||
|                                 TxStatus::Broadcasted { num_peers } => self.action_tx.send(Action::WalletLog(format!("transaction {} has been broardcasted to {} nodes", ext_hash, num_peers), ActionLevel::Info))?, | ||||
|                                 TxStatus::NoLongerInBestBlock => self.action_tx.send(Action::WalletLog(format!("transaction {} is no longer in a best block", ext_hash), ActionLevel::Warn))?, | ||||
|                                 TxStatus::InBestBlock(b) => self.action_tx.send(Action::WalletLog(format!("transaction {} included in the block header {}", b.extrinsic_hash(), b.block_hash()), ActionLevel::Info))?, | ||||
|                                 TxStatus::InFinalizedBlock(b) => { | ||||
|                                     self.action_tx.send(Action::WalletLog(format!("transaction {} has been finalized in block header {}", b.extrinsic_hash(), b.block_hash()), ActionLevel::Info))?; | ||||
|                                     self.transactions_to_watch.remove(i); | ||||
|                                 } | ||||
|                                 TxStatus::Error { message } => { | ||||
|                                     self.action_tx.send(Action::WalletLog(format!("transaction {} error, something get wrong: {message}", ext_hash), ActionLevel::Error))?; | ||||
|                                     self.transactions_to_watch.remove(i); | ||||
|                                 } | ||||
|                                 TxStatus::Invalid { message } => { | ||||
|                                     self.action_tx.send(Action::WalletLog(format!("transaction {} invalid: {message}", ext_hash), ActionLevel::Error))?; | ||||
|                                     self.transactions_to_watch.remove(i); | ||||
|                                 } | ||||
|                                 TxStatus::Dropped { message } => { | ||||
|                                     self.action_tx.send(Action::WalletLog(format!("transaction {} was dropped: {message}", ext_hash), ActionLevel::Error))?; | ||||
|                                     self.transactions_to_watch.remove(i); | ||||
|                                 } | ||||
|                             } | ||||
|                         }, | ||||
|                         _ => { | ||||
|                             self.action_tx.send(Action::WalletLog(format!("transaction {} was dropped", ext_hash), ActionLevel::Error))?; | ||||
|                             self.transactions_to_watch.remove(i); | ||||
|                         } | ||||
|                     } | ||||
|                 } | ||||
|                 Ok(()) | ||||
|             }, | ||||
|             Action::GetSystemHealth => legacy_rpc_calls::get_system_health(&self.action_tx, &self.legacy_client_api).await, | ||||
| @ -83,6 +122,24 @@ impl Network { | ||||
|                     predefinded_calls::get_balance(&self.action_tx, &self.online_client_api, &account_id).await | ||||
|                 } | ||||
|             } | ||||
|             Action::TransferBalance(sender, receiver, amount) => { | ||||
|                 let sender: [u8; 32] = hex::decode(sender) | ||||
|                     .expect("stored seed is valid hex string; qed") | ||||
|                     .as_slice() | ||||
|                     .try_into() | ||||
|                     .expect("stored seed is valid length; qed"); | ||||
| 
 | ||||
|                 if let Ok(tx_progress) = predefinded_calls::transfer_balance( | ||||
|                     &self.action_tx, 
 | ||||
|                     &self.online_client_api, 
 | ||||
|                     &sender, 
 | ||||
|                     &receiver, 
 | ||||
|                     &amount, | ||||
|                 ).await { | ||||
|                     self.transactions_to_watch.push(tx_progress); | ||||
|                 } | ||||
|                 Ok(()) | ||||
|             } | ||||
|             _ => Ok(()) | ||||
|         } | ||||
|     } | ||||
|  | ||||
| @ -1,21 +1,27 @@ | ||||
| use tokio::sync::mpsc::UnboundedSender; | ||||
| use color_eyre::Result; | ||||
| use subxt::{ | ||||
|     ext::sp_core::crypto::{AccountId32, Ss58Codec, Ss58AddressFormat}, | ||||
|     backend::rpc::RpcClient, 
 | ||||
|     client::OnlineClient, 
 | ||||
|     config::substrate::DigestItem, 
 | ||||
|     ext::sp_core::{ | ||||
|         crypto::{AccountId32, Ss58AddressFormat, Ss58Codec}, 
 | ||||
|         Pair as PairT, | ||||
|         sr25519::Pair, | ||||
|     }, | ||||
|     rpc_params, 
 | ||||
|     tx::{PairSigner, TxProgress}, 
 | ||||
|     utils::H256, | ||||
|     backend::rpc::RpcClient, | ||||
|     client::OnlineClient, | ||||
|     config::substrate::DigestItem, | ||||
|     rpc_params, | ||||
| }; | ||||
| 
 | ||||
| 
 | ||||
| use crate::{ | ||||
|     action::Action, 
 | ||||
|     casper_network::{ | ||||
|         self, 
 | ||||
|         runtime_types::sp_consensus_slots, | ||||
|     }, 
 | ||||
|     types::{SystemAccount, EraInfo}, 
 | ||||
|     types::{SystemAccount, EraInfo, ActionLevel}, 
 | ||||
|     CasperAccountId, CasperConfig | ||||
| }; | ||||
| 
 | ||||
| @ -147,7 +153,6 @@ pub async fn get_existential_deposit( | ||||
|     Ok(()) | ||||
| } | ||||
| 
 | ||||
| 
 | ||||
| pub async fn get_balance( | ||||
|     action_tx: &UnboundedSender<Action>, | ||||
|     api: &OnlineClient<CasperConfig>, | ||||
| @ -178,3 +183,39 @@ pub async fn get_balance( | ||||
|     action_tx.send(Action::BalanceResponse(*account_id, balance))?; | ||||
|     Ok(()) | ||||
| } | ||||
| 
 | ||||
| pub async fn transfer_balance( | ||||
|     action_tx: &UnboundedSender<Action>, | ||||
|     api: &OnlineClient<CasperConfig>, | ||||
|     sender: &[u8; 32], | ||||
|     receiver: &[u8; 32], | ||||
|     amount: &u128, | ||||
| ) -> Result<TxProgress<CasperConfig, OnlineClient<CasperConfig>>> { | ||||
|     let receiver_id = subxt::utils::MultiAddress::Id( | ||||
|         subxt::utils::AccountId32::from(*receiver) | ||||
|     ); | ||||
| 
 | ||||
|     let transfer_tx = casper_network::tx() | ||||
|         .balances() | ||||
|         .transfer_allow_death(receiver_id, *amount); | ||||
| 
 | ||||
|     let pair = Pair::from_seed(sender); | ||||
|     let signer = PairSigner::<CasperConfig, Pair>::new(pair); | ||||
| 
 | ||||
|     match api | ||||
|         .tx() | ||||
|         .sign_and_submit_then_watch_default(&transfer_tx, &signer) | ||||
|         .await { | ||||
|             Ok(tx_progress) => { | ||||
|                 action_tx.send(Action::WalletLog( | ||||
|                         format!("transfer transaction {} sent", tx_progress.extrinsic_hash()), | ||||
|                         ActionLevel::Info))?; | ||||
|                 Ok(tx_progress) | ||||
|             }, | ||||
|             Err(err) => { | ||||
|                 action_tx.send(Action::WalletLog( | ||||
|                         format!("error during transfer: {err}"), ActionLevel::Error))?; | ||||
|                 Err(err.into()) | ||||
|             } | ||||
|         } | ||||
| } | ||||
|  | ||||
| @ -48,9 +48,9 @@ impl FinalizedSubscription { | ||||
| 
 | ||||
|             self.action_tx.send(Action::FinalizedBlockInformation(block_hash, block_number))?; | ||||
|             self.action_tx.send(Action::ExtrinsicsForBlock(block_number, extrinsic_details))?; | ||||
|             self.action_tx.send(Action::NewFinalizedHash(block_hash))?; | ||||
|             self.action_tx.send(Action::NewFinalizedBlock(block_number))?; | ||||
| 
 | ||||
|             self.network_tx.send(Action::NewFinalizedHash(block_hash))?; | ||||
|             self.network_tx.send(Action::GetBlockAuthor(block_hash, block.header().digest.logs.clone()))?; | ||||
|         } | ||||
|         Ok(()) | ||||
| @ -105,11 +105,11 @@ impl BestSubscription { | ||||
| 
 | ||||
|             self.action_tx.send(Action::BestBlockInformation(block_hash, block_number))?; | ||||
|             self.action_tx.send(Action::ExtrinsicsForBlock(block_number, extrinsic_details))?; | ||||
|             self.action_tx.send(Action::NewBestHash(block_hash))?; | ||||
|             self.action_tx.send(Action::BestBlockUpdated(block_number))?; | ||||
|             self.action_tx.send(Action::NewBestBlock(block_number))?; | ||||
|             self.action_tx.send(Action::ExtrinsicsLength(block_number, extrinsics_length))?; | ||||
| 
 | ||||
|             self.network_tx.send(Action::NewBestHash(block_hash))?; | ||||
|             self.network_tx.send(Action::GetBlockAuthor(block_hash, block.header().digest.logs.clone()))?; | ||||
|             self.network_tx.send(Action::GetActiveEra)?; | ||||
|             self.network_tx.send(Action::GetEpochProgress)?; | ||||
|  | ||||
		Loading…
	
		Reference in New Issue
	
	Block a user