diff --git a/src/tui.rs b/src/tui.rs index 8900af4..b2a5783 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1177,7 +1177,6 @@ enum Screen { selected: usize, detail: bool, }, - Send { form: SendForm }, ChainSetup(ChainSetup), WalletSetup(WalletSetup), WalletConfig(WalletConfigScreen), @@ -1376,18 +1375,6 @@ impl WalletReadiness { Self::ViewOnly => "view-only wallet: spend is refused locally, before any dial", } } - - /// The refusal copy shown on the send screen when spend is blocked, - /// `None` when spend is allowed. Uses the exact contract strings from - /// `wallet.rs` — never invented here. - pub fn refusal(self) -> Option<&'static str> { - match self { - Self::Ready => None, - Self::NotConfigured => Some(wallet::NOT_CONFIGURED_MSG), - Self::NotConnected => Some(wallet::NOT_CONNECTED_MSG), - Self::ViewOnly => Some(wallet::VIEW_ONLY_MSG), - } - } } /// Lines that must fit the wallet body at 80 columns (the body is inset by a @@ -1425,235 +1412,6 @@ impl ChainView { } } -/// A pure state struct for the send / tip flow screen. It holds the recipient -/// info (already resolved by the caller from the selected friend), the XMR -/// amount being typed, a memo, the current validation error, and which pane of -/// the form has focus. It is cloneable and testable without a live `Node`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SendForm { - /// Short fingerprint of the selected friend (identity proof). - pub friend_fp: String, - /// Display name, if the friend has one. - pub friend_petname: Option, - /// The recipient's Monero address (raw, no `monero:` prefix). - pub friend_xmr: String, - /// `true` for `/tip` (spend), `false` for `/pay` (invoice request). - pub is_tip: bool, - /// What the user is typing as an XMR amount (e.g. "0.01"). - pub amount: String, - /// Optional memo attached to the payment. - pub memo: String, - /// Validation error from `xmr_to_atomic`, shown inline. - pub amount_err: Option, - /// Which field currently has focus. - pub focused: SendPane, - /// Wallet spend-readiness as of form open. Drives the confirm guard and the - /// inline refusal line on screen. - pub readiness: WalletReadiness, - /// `true` when the wallet is view-only (no-spend). Drives the spend badge, - /// which is visible on both /tip and /pay. - pub no_spend: bool, - /// `true` when the selected friend has no Monero address. The recipient - /// line shows exactly `friend has no Monero address — they must /profile`. - pub friend_no_address: bool, -} - -/// The four editable panes on the send screen, in Tab order. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SendPane { - Recipient, - Amount, - Memo, - Confirm, -} - -impl SendPane { - pub fn next(self) -> Self { - match self { - Self::Recipient => Self::Amount, - Self::Amount => Self::Memo, - Self::Memo => Self::Confirm, - Self::Confirm => Self::Recipient, - } - } -} - -impl SendForm { - /// Resolve the typed XMR amount to atomic (piconero) string. - /// Returns the error from `xmr_to_atomic` on failure. - pub fn resolved(&self) -> Result { - crate::pay::xmr_to_atomic(&self.amount) - .map_err(|e| e.to_string()) - } -} - -/// Validate the amount field, returning `Ok(atomic_string)` or `Err(message)`. -pub fn send_form_resolved(form: &SendForm) -> Result { - form.resolved() -} - -/// Whether the confirm button is enabled: the friend is selected (non-empty -/// `friend_fp` and `friend_xmr`) and the amount resolves to a positive atomic. -/// Readiness and address checks are layered on top in `send_form_confirm_enabled`. -pub fn send_form_ready(form: &SendForm) -> bool { - if form.friend_fp.is_empty() || form.friend_xmr.is_empty() { - return false; - } - send_form_resolved(form).is_ok() -} - -/// Whether the confirm button can dispatch: readiness guard passes, friend has -/// an address, and the form amount is valid. -pub fn send_form_confirm_enabled(form: &SendForm) -> bool { - form.readiness.ready() && !form.friend_no_address && send_form_ready(form) -} - -/// Key hints for the send screen footer. -pub fn send_footer_hints() -> &'static str { - "Tab Enter confirm Esc back ? help" -} - -/// The title for the send screen block, showing tip or pay-invoice mode. -fn send_screen_title(is_tip: bool) -> &'static str { - if is_tip { - "(o) pay friend" - } else { - "(o) request invoice" - } -} - -/// Render the send / tip flow screen. -pub fn draw_send(f: &mut Frame, form: &SendForm, hints: &str) { - let area = f.area(); - let cols = Layout::vertical([ - Constraint::Length(1), - Constraint::Min(3), - Constraint::Length(1), - ]) - .split(area); - - let header = main_header_line(area.width, &form.friend_fp, ""); - f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); - - let body = send_body(form, cols[1].width as usize); - f.render_widget( - Paragraph::new(body) - .style(style_text()) - .wrap(Wrap { trim: false }) - .block(themed_block(send_screen_title(form.is_tip))), - cols[1], - ); - - let footer = status_footer( - area.width, - &form.friend_fp, - "", - None, - hints, - ); - f.render_widget(Paragraph::new(footer).style(style_dim()), cols[2]); -} - -/// Build the body text for the send screen. -fn send_body(form: &SendForm, width: usize) -> String { - let display_name = form - .friend_petname - .as_ref() - .filter(|s| !s.is_empty()) - .map(|s| s.as_str()) - .unwrap_or("?"); - let recipient_line = format!("to {display_name}"); - let fp_line = format!("fp {}", form.friend_fp); - let addr_line = format!( - "xmr {}", - truncate_chars(&form.friend_xmr, width.saturating_sub(6)) - ); - let amount_line = if let Some(err) = &form.amount_err { - format!("amount {} {}", form.amount, err) - } else { - format!("amount {}", form.amount) - }; - let memo_line = format!("memo {}", form.memo); - let atomic = send_form_resolved(form) - .map(|s| format!("atomic {s}")) - .unwrap_or_else(|_| "atomic —".to_string()); - - // Confirm guard: readiness refusal takes priority over friend/amount. - let confirm_line = send_confirm_line(form); - - // Spend badge: shown whenever the wallet is view-only (is_tip or pay on - // a no-spend wallet), per Deliverable 5 copy table. - let badge = spend_badge(form); - - // Address-less friend: shows the exact refusal line inline. - let addr_err = if form.friend_no_address { - NO_ADDRESS_MSG.to_string() - } else { - String::new() - }; - - let parts = [ - recipient_line, - fp_line, - addr_line, - addr_err, - String::new(), - amount_line, - memo_line, - atomic, - String::new(), - confirm_line, - ]; - let mut body = String::new(); - for (i, p) in parts.iter().enumerate() { - if i > 0 { - body.push('\n'); - } - body.push_str(p); - } - if !badge.is_empty() { - body.push_str("\n\n"); - body.push_str(badge); - } - body -} - -/// The confirm row text: reflects whether Enter will dispatch, and why it -/// won't when it doesn't. Readiness refusal takes priority, then missing -/// recipient, then amount validity. -fn send_confirm_line(form: &SendForm) -> String { - if let Some(refusal) = form.readiness.refusal() { - // Readiness refusal (incl. view-only for /tip) blocks confirm. - // The exact string is the contract copy from wallet.rs. - format!("confirm {}", refusal) - } else if form.friend_no_address { - format!("confirm {}", NO_ADDRESS_MSG) - } else if form.friend_fp.is_empty() || form.friend_xmr.is_empty() { - "confirm no recipient — pick a friend from the roster".to_string() - } else if send_form_ready(form) { - "confirm ready (Enter)".to_string() - } else { - "confirm —".to_string() - } -} - -/// The spend badge shown on the send screen, identical to the wallet screen. -/// Per spec: `view-only — /tip off` (word + glyph, never color-only). -fn spend_badge(form: &SendForm) -> &'static str { - if form.no_spend { - VIEW_ONLY_BADGE - } else { - "" - } -} - -/// Exact badge copy for a view-only wallet. -pub const VIEW_ONLY_BADGE: &str = "view-only — /tip off"; - -/// The line shown when the selected friend has no Monero address. -/// Must match the string node.rs returns from `tip`'s address guard. -pub const NO_ADDRESS_MSG: &str = "friend has no Monero address — they must /profile"; - /// A pruned node is a real trade-off and the screen says so instead of implying /// an archive. pub const PRUNED_NOTE: &str = "pruned nodes are not archives: a deep seed restore can degrade. once this wallet has scanned, its own cache is the history"; @@ -1937,6 +1695,8 @@ impl App { let mut quit_clear = None; let mut profile_save = None; let mut open_profile = false; + let mut pay_cmd = None; + let mut tip_cmd = None; let mut file_cmd = None; let mut chat_send = None; let mut pass_submit = None; @@ -1987,11 +1747,11 @@ impl App { } Some(ComposerAction::Cmd(SlashCmd::Pay { atomic, memo })) => { self.composer.clear(); - self.open_send_from_slash(false, &atomic, &memo); + pay_cmd = Some((atomic, memo)); } Some(ComposerAction::Cmd(SlashCmd::Tip { atomic, memo })) => { self.composer.clear(); - self.open_send_from_slash(true, &atomic, &memo); + tip_cmd = Some((atomic, memo)); } Some(ComposerAction::Cmd(SlashCmd::Backup { path })) => { self.composer.clear(); @@ -2158,8 +1918,6 @@ impl App { KeyCode::Char('y') => self.wallet_copy_address(), KeyCode::Char('h') => self.open_history()?, KeyCode::F(7) => self.open_wallet_config(), - KeyCode::Char('p') => self.open_send(false), - KeyCode::Char('t') => self.open_send(true), _ => {} }, Screen::History { selected, payments, detail, .. } => match key.code { @@ -2180,53 +1938,6 @@ impl App { _ => {} }, Screen::ChainSetup(_) => self.handle_chain_setup(key)?, - Screen::Send { form } => { - let mut do_send = false; - { - match key.code { - KeyCode::Esc => self.screen = Screen::Main, - KeyCode::Tab => form.focused = form.focused.next(), - KeyCode::BackTab => { - form.focused = match form.focused { - SendPane::Recipient => SendPane::Confirm, - SendPane::Amount => SendPane::Recipient, - SendPane::Memo => SendPane::Amount, - SendPane::Confirm => SendPane::Memo, - }; - } - KeyCode::Backspace => match form.focused { - SendPane::Amount => { - form.amount.pop(); - form.amount_err = None; - } - SendPane::Memo => { - form.memo.pop(); - } - _ => {} - }, - KeyCode::Enter => { - if form.focused == SendPane::Confirm && send_form_confirm_enabled(form) { - do_send = true; - } - } - KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { - match form.focused { - SendPane::Amount => { - form.amount.push(c); - form.amount_err = - send_form_resolved(form).err().map(|e| e.to_string()); - } - SendPane::Memo => form.memo.push(c), - _ => {} - } - } - _ => {} - } - } - if do_send { - self.send_from_form()?; - } - } Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, Screen::WalletConfig(_) => self.handle_wallet_config(key)?, Screen::Quit { prompt } => match key.code { @@ -2260,6 +1971,12 @@ impl App { if let Some(draft) = profile_save { self.save_profile(draft)?; } + if let Some((atomic, memo)) = pay_cmd { + self.send_pay(&atomic, &memo)?; + } + if let Some((atomic, memo)) = tip_cmd { + self.send_tip(&atomic, &memo)?; + } if let Some(path) = file_cmd { self.send_file(&path)?; } @@ -2463,68 +2180,6 @@ impl App { self.screen = Screen::WalletConfig(screen); } - /// Open the send / tip form, pre-filled from the selected friend. - /// `is_tip` = true for `/tip` (spend), false for `/pay` (invoice request). - fn open_send(&mut self, is_tip: bool) { - let friend = self.friends.get(self.selected); - let (fp, petname, xmr, no_addr) = friend - .map(|f| { - let profile = self.node.friend_profile(&f.pubkey).ok().flatten(); - let xmr_addr = profile.as_ref().map(|p| p.xmr_addr.clone()).unwrap_or_default(); - let no_addr = xmr_addr.is_empty(); - (f.fingerprint.clone(), f.petname.clone().or_else(|| profile.map(|p| p.display_name)), xmr_addr, no_addr) - }) - .unwrap_or_default(); - let (readiness, no_spend) = self.send_readiness(is_tip); - self.screen = Screen::Send { - form: SendForm { - friend_fp: fp, - friend_petname: petname, - friend_xmr: xmr, - is_tip, - amount: String::new(), - memo: String::new(), - amount_err: None, - focused: SendPane::Recipient, - readiness, - no_spend, - friend_no_address: no_addr, - }, - }; - } - - /// Open the send screen from a slash command (`/pay` or `/tip`), pre-filling - /// the amount and memo from the parsed command. The atomic value is - /// converted back to XMR for the amount field. - fn open_send_from_slash(&mut self, is_tip: bool, atomic: &str, memo: &str) { - let friend = self.friends.get(self.selected); - let (fp, petname, xmr, no_addr) = friend - .map(|f| { - let profile = self.node.friend_profile(&f.pubkey).ok().flatten(); - let xmr_addr = profile.as_ref().map(|p| p.xmr_addr.clone()).unwrap_or_default(); - let no_addr = xmr_addr.is_empty(); - (f.fingerprint.clone(), f.petname.clone().or_else(|| profile.map(|p| p.display_name)), xmr_addr, no_addr) - }) - .unwrap_or_default(); - let amount = crate::pay::atomic_to_xmr_str(atomic); - let (readiness, no_spend) = self.send_readiness(is_tip); - self.screen = Screen::Send { - form: SendForm { - friend_fp: fp, - friend_petname: petname, - friend_xmr: xmr, - is_tip, - amount, - memo: memo.to_string(), - amount_err: None, - focused: SendPane::Amount, - readiness, - no_spend, - friend_no_address: no_addr, - }, - }; - } - /// Draw state for the wallet screen. /// /// One probe per open/refresh, then everything the screen says comes from @@ -2571,28 +2226,6 @@ impl App { } } - /// Compute the spend-readiness the send screen needs: the same guard the - /// slash-command path uses. Probed cheaply (steps 1+2 are local, step 3 - /// is one loopback probe) so it is fine to block_on here. - /// - /// Returns (readiness, no_spend) — readiness drives the confirm guard, - /// no_spend drives the spend badge (visible on both /tip and /pay). - fn send_readiness(&self, is_tip: bool) -> (WalletReadiness, bool) { - let status = self.rt.block_on(self.node.wallet_refresh()); - let no_spend = self - .node - .wallet_config() - .map(|c| c.no_spend) - .unwrap_or(false); - // /pay is allowed on a view-only wallet (invoice only); /tip is blocked. - let readiness = if !is_tip && no_spend { - WalletReadiness::Ready - } else { - wallet_readiness(status.configured, status.connected, no_spend) - }; - (readiness, no_spend) - } - /// `s`: pick the chain source, with the stored choice shown as current. fn open_chain_setup(&mut self) { let current = ChainChoice::of(&self.node.wallet_chain_source()); @@ -3082,51 +2715,6 @@ impl App { Ok(()) } - /// Fire a tip to the selected friend from the send form. The readiness - /// check runs first: view-only / not-configured / not-connected are - /// refused before any dial (same guard as the slash-command path). - fn send_from_form(&mut self) -> Result<(), String> { - let Screen::Send { form } = &mut self.screen else { - return Ok(()); - }; - let Some(friend) = self.friends.get(self.selected) else { - self.status_note = Some("no friend selected".into()); - return Ok(()); - }; - let pk = friend.pubkey.clone(); - let is_tip = form.is_tip; - let memo = std::mem::take(&mut form.memo); - let atomic = match send_form_resolved(form) { - Ok(a) => a, - Err(e) => { - form.amount_err = Some(e); - return Ok(()); - } - }; - let readiness = self.rt.block_on(self.node.wallet_readiness(is_tip)); - if !readiness.is_ready() { - if let Some(refusal) = readiness.refusal() { - self.status_note = Some(refusal.to_string()); - } else { - self.status_note = Some("wallet not ready".into()); - } - return Ok(()); - } - let result = if is_tip { - self.rt.block_on(self.node.tip(&pk, &atomic, &memo)) - } else { - self.rt.block_on(self.node.pay_invoice(&pk, &atomic, &memo)) - }; - match result { - Ok(()) => { - self.status_note = Some(if is_tip { "tip sent".into() } else { "invoice sent".into() }); - self.screen = Screen::Main; - } - Err(e) => self.status_note = Some(e), - } - Ok(()) - } - fn submit_paste(&mut self, raw: &str) -> Result<(), String> { match qr::decode(raw.trim()) { Err(e) => { @@ -3194,6 +2782,32 @@ impl App { Ok(()) } + fn send_pay(&mut self, atomic: &str, memo: &str) -> Result<(), String> { + let Some(friend) = self.friends.get(self.selected) else { + self.status_note = Some("no friend selected".into()); + return Ok(()); + }; + let pk = friend.pubkey.clone(); + match self.rt.block_on(self.node.pay_invoice(&pk, atomic, memo)) { + Ok(()) => self.status_note = Some("invoice sent".into()), + Err(e) => self.status_note = Some(e), + } + Ok(()) + } + + fn send_tip(&mut self, atomic: &str, memo: &str) -> Result<(), String> { + let Some(friend) = self.friends.get(self.selected) else { + self.status_note = Some("no friend selected".into()); + return Ok(()); + }; + let pk = friend.pubkey.clone(); + match self.rt.block_on(self.node.tip(&pk, atomic, memo)) { + Ok(()) => self.status_note = Some("tip sent".into()), + Err(e) => self.status_note = Some(e), + } + Ok(()) + } + fn send_file(&mut self, path: &str) -> Result<(), String> { let Some(friend) = self.friends.get(self.selected) else { self.status_note = Some("no friend selected".into()); @@ -3279,7 +2893,6 @@ impl App { .unwrap_or("friend"); draw_history(f, payments, *selected, *detail, name, unix_now_secs()) } - Screen::Send { form } => draw_send(f, form, footer_hints(&self.screen)), Screen::ChainSetup(setup) => draw_chain_setup(f, setup), Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), Screen::WalletConfig(s) => draw_wallet_config(f, s), @@ -3600,9 +3213,8 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "s chain n node t tip p pay c create i import h history r qr y copy Esc back ? help", + Screen::Wallet { .. } => "s chain n node c create i import h history r qr y copy Esc back ? help", Screen::History { .. } => "Enter detail Esc back ? help", - Screen::Send { .. } => send_footer_hints(), Screen::ChainSetup(_) => "Enter select/save Esc back ? help", Screen::WalletConfig(_) => "Tab fields t test s save Esc back ? help", Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index cad5169..b7986ca 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -5,15 +5,12 @@ use onionwire::Message; use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::Payment; -use onionwire::wallet; use onionwire::tui::{ - ConfigField, ConfigStatus, NO_ADDRESS_MSG, OutboxSummary, SendForm, SendPane, VIEW_ONLY_BADGE, - WalletConfigScreen, WalletReadiness, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, - draw_chat, draw_history, draw_send, draw_share, draw_text_overlay, empty_friend_chat_text, - help_overlay_text, history_detail, history_row_text, is_onion_host, main_footer_hints, - main_header_line, parse_daemon_addr, paste_screen_text, retry_in_text, roster_col_width, - send_footer_hints, send_form_confirm_enabled, send_form_ready, send_form_resolved, - short_send_reason, status_footer, wrap_invite, + ConfigField, ConfigStatus, OutboxSummary, WalletConfigScreen, alert_line, ascii_chrome, + chat_with_delivery, delivery_tag, draw_chat, draw_history, draw_share, draw_text_overlay, + empty_friend_chat_text, help_overlay_text, history_detail, history_row_text, is_onion_host, + main_footer_hints, main_header_line, parse_daemon_addr, paste_screen_text, retry_in_text, + roster_col_width, short_send_reason, status_footer, wrap_invite, }; use onionwire::wallet::PingResult; use ratatui::Frame; @@ -230,33 +227,6 @@ fn dump_spec_frames() { } } -#[test] -fn dump_send_frames() { - for (w, h) in [(80u16, 24u16), (120, 40)] { - let form = SendForm { - friend_fp: "AB:CD:EF:01:23:45".to_string(), - friend_petname: Some("alice".to_string()), - friend_xmr: "4AaaaaBBBBccccDDDDEeee".to_string(), - is_tip: true, - amount: "0.001".to_string(), - memo: "coffee".to_string(), - amount_err: None, - focused: SendPane::Confirm, - readiness: WalletReadiness::Ready, - no_spend: false, - friend_no_address: false, - }; - let hints = send_footer_hints(); - let backend = TestBackend::new(w, h); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - println!("===== AFTER send {w}x{h} ====="); - print!("{}", screen_from(terminal.backend().buffer(), w, h)); - } -} - fn sample_invite() -> String { let sk = [7u8; 32]; qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") @@ -1380,419 +1350,3 @@ fn wallet_config_focus_cycles_through_fields() { assert_eq!(ConfigField::NoSpend.prev(), ConfigField::RpcLogin); assert_eq!(ConfigField::Action.prev(), ConfigField::NoSpend); } - -// Send / tip flow screen (card C5) -// --------------------------------------------------------------------------- - -const SEND_FP: &str = "abcdef0123456789deadbeefcafebabe"; -const SEND_ADDR: &str = "4A1234567890abcdef4A1234567890abcdef4A1234567890abcdef4A12345678"; - -fn friend_form() -> SendForm { - SendForm { - friend_fp: SEND_FP.to_string(), - friend_petname: Some("alice".to_string()), - friend_xmr: SEND_ADDR.to_string(), - is_tip: false, - amount: "0.01".to_string(), - memo: String::new(), - amount_err: None, - focused: SendPane::Recipient, - readiness: WalletReadiness::Ready, - no_spend: false, - friend_no_address: false, - } -} - -#[test] -fn send_form_resolved_accepts_valid_xmr_amount() { - let form = friend_form(); - assert_eq!(send_form_resolved(&form), Ok("10000000000".to_string())); -} - -#[test] -fn send_form_resolved_rejects_empty_amount() { - let mut form = friend_form(); - form.amount = String::new(); - assert!( - send_form_resolved(&form).is_err(), - "empty amount should fail" - ); -} - -#[test] -fn send_form_ready_requires_friend_and_valid_amount() { - let form = friend_form(); - assert!( - send_form_ready(&form), - "ready: friend present + valid amount + 0.01 atomic" - ); - - let mut no_friend = form.clone(); - no_friend.friend_fp.clear(); - no_friend.friend_xmr.clear(); - assert!( - !send_form_ready(&no_friend), - "missing friend must not be ready" - ); - - let mut bad = form.clone(); - bad.amount = String::new(); - assert!( - !send_form_ready(&bad), - "empty amount must not be ready" - ); -} - -#[test] -fn send_form_ready_for_tip_path() { - let mut form = friend_form(); - form.is_tip = true; - form.focused = SendPane::Confirm; - assert!(send_form_ready(&form), "tip path with tip=true should still resolve"); -} - -#[test] -fn send_screen_fits_80x24_and_shows_fields() { - let form = friend_form(); - let hints = send_footer_hints(); - assert!(hints.contains("Enter confirm")); - assert!(hints.contains("Esc back")); - - for (w, h) in [(80u16, 24u16), (120, 40)] { - let backend = TestBackend::new(w, h); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), w, h); - for line in screen.lines() { - assert!( - line.chars().count() <= w as usize, - "line wider than {w} at {w}x{h}: {line:?}" - ); - } - assert!( - screen.contains("request invoice") || screen.contains("pay friend"), - "send screen missing title at {w}x{h}\n{screen}" - ); - assert!( - screen.contains("to alice"), - "send screen missing recipient at {w}x{h}\n{screen}" - ); - assert!( - screen.contains("amount"), - "send screen missing amount field at {w}x{h}\n{screen}" - ); - assert!( - screen.contains("0.01"), - "send screen missing amount value at {w}x{h}\n{screen}" - ); - assert!( - screen.contains("memo"), - "send screen missing memo field at {w}x{h}\n{screen}" - ); - assert!( - screen.contains(&form.friend_xmr), - "send screen missing xmr address at {w}x{h}\n{screen}" - ); - } -} - -#[test] -fn send_screen_shows_amount_error() { - let mut form = friend_form(); - form.amount = "xyz".to_string(); - form.amount_err = Some("invalid XMR amount".to_string()); - form.focused = SendPane::Amount; - let hints = send_footer_hints(); - - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - assert!( - screen.contains("invalid XMR amount"), - "error not shown -{screen}" - ); -} - -#[test] -fn send_screen_shows_confirm_when_ready() { - let mut form = friend_form(); - form.focused = SendPane::Confirm; - let hints = send_footer_hints(); - - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - assert!( - screen.contains("ready"), - "confirm row should show ready state -{screen}" - ); -} - -#[test] -fn send_screen_disabled_when_no_friend() { - let mut form = friend_form(); - form.friend_fp.clear(); - form.friend_xmr.clear(); - form.friend_petname = None; - form.focused = SendPane::Confirm; - let hints = send_footer_hints(); - - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), 80, 24); - assert!( - screen.contains("no recipient"), - "disabled state should show 'no recipient'\n{screen}" - ); -} - -// --- Readiness guard: the send screen must refuse with the exact contract strings. - -fn not_configured_form(is_tip: bool) -> SendForm { - let mut form = friend_form(); - form.is_tip = is_tip; - form.readiness = WalletReadiness::NotConfigured; - form -} - -fn view_only_form(is_tip: bool) -> SendForm { - let mut form = friend_form(); - form.is_tip = is_tip; - form.no_spend = true; - // /pay on view-only is allowed by the readiness guard; only /tip is blocked. - form.readiness = if is_tip { - WalletReadiness::ViewOnly - } else { - WalletReadiness::Ready - }; - form -} - -fn not_connected_form(is_tip: bool) -> SendForm { - let mut form = friend_form(); - form.is_tip = is_tip; - form.readiness = WalletReadiness::NotConnected; - form -} - -fn no_address_form() -> SendForm { - let mut form = friend_form(); - form.friend_no_address = true; - form -} - -#[test] -fn send_form_confirm_disabled_when_not_configured() { - let form = not_configured_form(true); - assert!( - !send_form_confirm_enabled(&form), - "not-configured must block confirm" - ); - let screen = draw_send_screen(&form); - assert!( - screen.contains("wallet not configured"), - "screen must show not-configured refusal\n{screen}" - ); -} - -#[test] -fn send_form_confirm_disabled_when_view_only_tip() { - let form = view_only_form(true); - assert!( - !send_form_confirm_enabled(&form), - "view-only must block /tip confirm" - ); - let screen = draw_send_screen(&form); - assert!( - screen.contains("view-only/no-spend mode"), - "screen must show VIEW_ONLY_MSG\n{screen}" - ); - assert!( - screen.contains(VIEW_ONLY_BADGE), - "screen must show spend badge\n{screen}" - ); -} - -#[test] -fn send_form_confirm_disabled_when_view_only_pay() { - // /pay on view-only is allowed (invoice), but the badge still shows. - // Runtime: open_send with is_tip=false returns WalletReadiness::Ready - // for a no-spend wallet (pay is fine on view-only). - let form = view_only_form(false); - assert!( - send_form_confirm_enabled(&form), - "/pay on view-only should still confirm" - ); - let screen = draw_send_screen(&form); - // Badge shows on /pay too — view-only is a real mode. - assert!( - screen.contains(VIEW_ONLY_BADGE), - "view-only badge should show even for /pay\n{screen}" - ); -} - -#[test] -fn send_form_confirm_disabled_when_not_connected() { - let form = not_connected_form(true); - assert!( - !send_form_confirm_enabled(&form), - "not-connected must block confirm" - ); - let screen = draw_send_screen(&form); - assert!( - screen.contains(wallet::NOT_CONNECTED_MSG), - "screen must show NOT_CONNECTED_MSG\n{screen}" - ); -} - -#[test] -fn send_form_confirm_disabled_when_friend_has_no_address() { - let form = no_address_form(); - assert!( - !send_form_confirm_enabled(&form), - "no-address friend must block confirm" - ); - let screen = draw_send_screen(&form); - assert!( - screen.contains(NO_ADDRESS_MSG), - "screen must show NO_ADDRESS_MSG\n{screen}" - ); -} - -#[test] -fn send_screen_shows_amount_must_be_positive() { - let mut form = friend_form(); - form.amount = String::new(); - form.amount_err = Some("amount must be > 0".to_string()); - form.focused = SendPane::Amount; - let screen = draw_send_screen(&form); - assert!( - screen.contains("amount must be > 0"), - "zero/empty amount error not shown\n{screen}" - ); - assert!( - !send_form_confirm_enabled(&form), - "empty amount must not confirm" - ); -} - -#[test] -fn send_screen_shows_invalid_amount_error() { - let mut form = friend_form(); - form.amount = "abc".to_string(); - form.amount_err = Some("invalid XMR amount".to_string()); - form.focused = SendPane::Amount; - let screen = draw_send_screen(&form); - assert!( - screen.contains("invalid XMR amount"), - "amount parse error not shown\n{screen}" - ); -} - -#[test] -fn send_screen_shows_negative_amount_error() { - let mut form = friend_form(); - form.amount = "-1.0".to_string(); - form.amount_err = Some("invalid XMR amount".to_string()); - form.focused = SendPane::Amount; - let screen = draw_send_screen(&form); - assert!( - screen.contains("invalid XMR amount"), - "negative amount error not shown\n{screen}" - ); -} - -#[test] -fn send_screen_fits_80x24_at_all_readiness_states() { - let hints = send_footer_hints(); - for readiness in [ - WalletReadiness::Ready, - WalletReadiness::NotConfigured, - WalletReadiness::NotConnected, - WalletReadiness::ViewOnly, - ] { - let mut form = friend_form(); - form.readiness = readiness; - for (w, h) in [(80u16, 24u16), (120, 40)] { - let backend = TestBackend::new(w, h); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - let screen = screen_from(terminal.backend().buffer(), w, h); - for line in screen.lines() { - assert!( - line.chars().count() <= w as usize, - "line wider than {w} at {w}x{h} readiness={readiness:?}: {line:?}" - ); - } - } - } -} - -fn draw_send_screen(form: &SendForm) -> String { - let hints = send_footer_hints(); - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, form, hints)) - .expect("draw"); - screen_from(terminal.backend().buffer(), 80, 24) -} - -#[test] -fn dump_send_refusal_frames() { - let hints = send_footer_hints(); - let cases = [ - ("empty form 80x24", { - let mut f = friend_form(); - f.amount.clear(); - f.amount_err = Some("amount must be > 0".to_string()); - f.focused = SendPane::Amount; - f - }), - ("view-only tip refusal", { - let mut f = friend_form(); - f.is_tip = true; - f.no_spend = true; - f.readiness = WalletReadiness::ViewOnly; - f - }), - ("not-configured refusal", { - let mut f = friend_form(); - f.readiness = WalletReadiness::NotConfigured; - f - }), - ("not-connected refusal", { - let mut f = friend_form(); - f.readiness = WalletReadiness::NotConnected; - f - }), - ("no-address friend", { - let mut f = friend_form(); - f.friend_no_address = true; - f - }), - ]; - for (label, form) in cases { - let backend = TestBackend::new(80, 24); - let mut terminal = Terminal::new(backend).expect("terminal"); - terminal - .draw(|f| draw_send(f, &form, hints)) - .expect("draw"); - println!("===== AFTER send: {label} 80x24 =====\n{}", screen_from(terminal.backend().buffer(), 80, 24)); - } -}