use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Tabs};
use starknet::core::types::Felt;
use crate::app::state::TxNavItem;
use crate::app::views::address_info::{RenderedRow, rendered_row};
use crate::app::{AddressTab, App};
use crate::data::types::{
AddressTxSummary, ContractCallSummary, MetaTxIntenderSummary, TokenBalance, TokenTransfer,
};
use crate::registry::AddressRegistry;
use crate::ui::theme;
use crate::ui::widgets::address_color::known_or_palette_style;
use crate::ui::widgets::hex_display::{format_fri, format_strk_u128, short_address, tx_hash_cell};
use crate::ui::widgets::list_window::ListWindow;
use crate::ui::widgets::param_display::format_token_amount;
use crate::ui::widgets::price;
use crate::ui::widgets::{search_bar, status_bar};
use crate::utils::{felt_to_u64, felt_to_u128};
enum CountBound {
Exact(u64),
LowerBound { hint: Option<u64> },
}
fn count_fragment(shown: u64, bound: CountBound) -> String {
match bound {
CountBound::Exact(total) if shown < total => format!("{shown} / {total}"),
CountBound::Exact(_) => shown.to_string(),
CountBound::LowerBound { hint: Some(h) } if h > shown => format!("{shown} / {h}+"),
CountBound::LowerBound { .. } => format!("{shown} / {shown}+"),
}
}
fn tx_count_fragment(app: &App) -> String {
let count = app.address.txs.items.len() as u64;
let bound = match app.address.info.as_ref().map(|i| felt_to_u64(&i.nonce)) {
Some(nonce) => CountBound::Exact(nonce),
None => CountBound::LowerBound { hint: None },
};
count_fragment(count, bound)
}
fn call_count_fragment(app: &App) -> String {
let count = app.address.calls.items.len() as u64;
let dune_total = app
.address
.activity_probe
.as_ref()
.map(|p| p.callee_call_count);
let bound = match dune_total {
Some(total) => CountBound::Exact(total),
None => CountBound::LowerBound { hint: None },
};
count_fragment(count, bound)
}
fn events_count_fragment(app: &App) -> String {
let count = app.address.events.items.len() as u64;
let reached_floor = match (
app.address.event_window.as_ref().map(|w| w.min_searched),
app.address.deployment.as_ref().map(|d| d.block_number),
) {
(Some(m), Some(d)) if m > 0 => m <= d,
_ => false,
};
let bound = if reached_floor {
CountBound::Exact(count)
} else {
CountBound::LowerBound { hint: None }
};
count_fragment(count, bound)
}
fn transfers_count_fragment(app: &App) -> String {
let count = app.address.transfers.items.len() as u64;
let bound = if app.address.transfers_fully_scanned() {
CountBound::Exact(count)
} else {
CountBound::LowerBound { hint: None }
};
count_fragment(count, bound)
}
fn meta_tx_count_fragment(app: &App) -> String {
let count = app.address.meta_txs.items.len() as u64;
let reached_floor = match (
app.address.event_window.as_ref().map(|w| w.min_searched),
app.address.deployment.as_ref().map(|d| d.block_number),
) {
(Some(m), Some(d)) if m > 0 => m <= d,
_ => false,
};
let bound = if reached_floor {
CountBound::Exact(count)
} else {
CountBound::LowerBound { hint: None }
};
count_fragment(count, bound)
}
fn event_window_gap_suffix(app: &App) -> String {
let Some(hint) = app.address.event_window.as_ref() else {
return String::new();
};
match hint.deferred_gap {
Some((lo, hi)) => {
let span = hi.saturating_sub(lo).saturating_add(1);
format!(" — gap {lo}..{hi} ({span} blocks deferred) ")
}
None => String::new(),
}
}
pub fn draw(f: &mut Frame, app: &mut App) {
let has_deploy = app.address.deployment.is_some();
let has_deployer = app
.address
.deployment
.as_ref()
.and_then(|d| d.sender)
.is_some_and(|s| {
app.address.info.as_ref().is_none_or(|i| s != i.address) && s != Felt::ZERO
});
let has_not_deployed_note = app.address.not_deployed
&& app
.address
.info
.as_ref()
.is_some_and(|i| i.class_hash.is_none() && !i.token_balances.is_empty());
let header_height =
4 + u16::from(has_deploy) + u16::from(has_deployer) + u16::from(has_not_deployed_note);
let chunks = Layout::vertical([
Constraint::Length(1), Constraint::Length(header_height), Constraint::Length(1), Constraint::Min(5), Constraint::Length(1), ])
.split(f.area());
search_bar::draw_input(f, app, chunks[0]);
draw_header(f, app, chunks[1]);
let private_holdings: Vec<(Felt, u128, usize)> = app
.address
.info
.as_ref()
.map(|i| compute_private_holdings(app, i.address))
.unwrap_or_default();
draw_tabs(f, app, chunks[2], &private_holdings);
match app.address.tab {
AddressTab::Transactions => draw_transactions_tab(f, app, chunks[3]),
AddressTab::MetaTxs => draw_meta_txs_tab(f, app, chunks[3]),
AddressTab::Calls => draw_calls_tab(f, app, chunks[3]),
AddressTab::Balances => draw_balances_tab(f, app, chunks[3], &private_holdings),
AddressTab::Transfers => draw_transfers_tab(f, app, chunks[3]),
AddressTab::Events => draw_events_tab(f, app, chunks[3]),
AddressTab::ClassHistory => draw_class_history_tab(f, app, chunks[3]),
}
status_bar::draw(f, app, chunks[4]);
search_bar::draw_dropdown(f, app, chunks[0]);
}
fn draw_header(f: &mut Frame, app: &App, area: Rect) {
let info = match &app.address.info {
Some(i) => i,
None => {
let addr_str = app
.address
.context
.map(|a| format!(" Loading {:#x}...", a))
.unwrap_or_else(|| " Loading address...".to_string());
f.render_widget(Paragraph::new(addr_str).style(theme::STATUS_LOADING), area);
return;
}
};
let label = app.format_address_full(&info.address);
let class_hash_str = info
.class_hash
.map(|c| format!("{:#x}", c))
.unwrap_or_else(|| "N/A".into());
let selected: Option<&TxNavItem> = if app.address.visual_mode {
app.address.nav_items.get(app.address.nav_cursor)
} else {
None
};
let mut lines = vec![Line::from(vec![
Span::styled(" ", theme::NORMAL_STYLE),
Span::styled(&label, theme::LABEL_STYLE),
Span::styled(format!(" {:#x}", info.address), theme::BLOCK_HASH_STYLE),
])];
{
let ch_selected = info
.class_hash
.is_some_and(|ch| matches!(selected, Some(TxNavItem::ClassHash(c)) if *c == ch));
let ch_style = if ch_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::TX_HASH_STYLE
};
let marker = if ch_selected { "►" } else { " " };
let mut class_line = vec![
Span::styled(
marker,
if ch_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::NORMAL_STYLE
},
),
Span::styled("Class: ", theme::NORMAL_STYLE),
Span::styled(&class_hash_str, ch_style),
];
if let Some(vl) = app.voyager_labels.get(&info.address)
&& let Some(ca) = &vl.class_alias
&& !ca.is_empty()
{
class_line.push(Span::styled(format!(" [{}]", ca), theme::LABEL_STYLE));
}
class_line.push(Span::styled(
format!(" Nonce: {}", felt_to_u64(&info.nonce)),
theme::NORMAL_STYLE,
));
lines.push(Line::from(class_line));
}
if let Some(deploy) = &app.address.deployment {
let has_tx = deploy.hash != Felt::ZERO;
let blk_selected = deploy.block_number > 0
&& matches!(selected, Some(TxNavItem::Block(b)) if *b == deploy.block_number);
let blk_style = if blk_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::BLOCK_NUMBER_STYLE
};
if has_tx {
let tx_selected =
matches!(selected, Some(TxNavItem::Transaction(h)) if *h == deploy.hash);
let tx_style = if tx_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::TX_HASH_STYLE
};
let tx_marker = if tx_selected { "►" } else { " " };
lines.push(Line::from(vec![
Span::styled(
tx_marker,
if tx_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::NORMAL_STYLE
},
),
Span::styled("Deployed at: ", theme::NORMAL_STYLE),
Span::styled(format!("{:#x}", deploy.hash), tx_style),
Span::styled(" Block: ", theme::NORMAL_STYLE),
Span::styled(format!("{}", deploy.block_number), blk_style),
]));
} else {
let blk_marker = if blk_selected { "►" } else { " " };
lines.push(Line::from(vec![
Span::styled(
blk_marker,
if blk_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::NORMAL_STYLE
},
),
Span::styled("Deployed at: ", theme::NORMAL_STYLE),
Span::styled("Block: ", theme::NORMAL_STYLE),
Span::styled(format!("{}", deploy.block_number), blk_style),
]));
}
if let Some(sender) = deploy.sender
&& sender != info.address
&& sender != Felt::ZERO
{
let addr_selected = matches!(selected, Some(TxNavItem::Address(a)) if *a == sender);
let addr_style = if addr_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::LABEL_STYLE
};
let addr_marker = if addr_selected { "►" } else { " " };
lines.push(Line::from(vec![
Span::styled(
addr_marker,
if addr_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::NORMAL_STYLE
},
),
Span::styled("Deployed by: ", theme::NORMAL_STYLE),
Span::styled(format!("{:#x}", sender), addr_style),
{
let label = app.format_address_full(&sender);
if label.starts_with("0x") {
Span::raw("")
} else {
Span::styled(format!(" {}", label), theme::LABEL_STYLE)
}
},
]));
}
}
if app.address.not_deployed && info.class_hash.is_none() && !info.token_balances.is_empty() {
lines.push(Line::from(Span::styled(
" ⚠ This contract is not deployed",
theme::STATUS_ERROR.add_modifier(Modifier::BOLD),
)));
}
let widget = Paragraph::new(lines).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_FOCUSED_STYLE)
.title(Span::styled(" Address ", theme::TITLE_STYLE)),
);
f.render_widget(widget, area);
}
fn draw_tabs(f: &mut Frame, app: &App, area: Rect, private_holdings: &[(Felt, u128, usize)]) {
let bal_count = app
.address
.info
.as_ref()
.map(|i| i.token_balances.len())
.unwrap_or(0);
let class_count = app.address.class_history.len();
let tx_label = format!(" Txs ({}) ", tx_count_fragment(app));
let call_label = format!(" Calls ({}) ", call_count_fragment(app));
let meta_label = format!(" MetaTxs ({}) ", meta_tx_count_fragment(app));
let prv_count = private_holdings.len();
let balances_title: Line = if prv_count > 0 {
Line::from(vec![
Span::raw(format!(" Balances ({bal_count}) ")),
Span::styled(format!("Prv ({prv_count}) "), theme::PRIVACY_STYLE),
])
} else {
Line::from(Span::raw(format!(" Balances ({bal_count}) ")))
};
let titles: Vec<Line> = vec![
Line::from(Span::raw(tx_label)),
Line::from(Span::raw(meta_label)),
Line::from(Span::raw(call_label)),
balances_title,
Line::from(Span::raw(format!(
" Transfers ({}) ",
transfers_count_fragment(app)
))),
Line::from(Span::raw(format!(
" Events ({}) ",
events_count_fragment(app)
))),
Line::from(Span::raw(format!(" Class ({class_count}) "))),
];
let selected = match app.address.tab {
AddressTab::Transactions => 0,
AddressTab::MetaTxs => 1,
AddressTab::Calls => 2,
AddressTab::Balances => 3,
AddressTab::Transfers => 4,
AddressTab::Events => 5,
AddressTab::ClassHistory => 6,
};
let tabs = Tabs::new(titles)
.select(selected)
.highlight_style(theme::TITLE_STYLE.add_modifier(Modifier::UNDERLINED))
.divider(Span::raw(" | "));
f.render_widget(tabs, area);
}
fn list_block(title: String) -> Block<'static> {
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE)
.title(Span::styled(title, theme::TITLE_STYLE))
}
fn highlighted_list(items: Vec<ListItem<'static>>, block: Block<'static>) -> List<'static> {
List::new(items)
.block(block)
.highlight_style(theme::SELECTED_STYLE.add_modifier(Modifier::BOLD))
.highlight_symbol(">> ")
}
fn draw_transactions_tab(f: &mut Frame, app: &mut App, area: Rect) {
let header_area = Rect { height: 1, ..area };
let list_area = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
let header = Paragraph::new(Line::from(vec![
Span::styled(" Nonce ", theme::SUGGESTION_STYLE),
Span::styled("Type ", theme::SUGGESTION_STYLE),
Span::styled("Hash ", theme::SUGGESTION_STYLE),
Span::styled("Contracts ", theme::SUGGESTION_STYLE),
Span::styled("Endpoint(s) ", theme::SUGGESTION_STYLE),
Span::styled("Fee(STRK) ", theme::SUGGESTION_STYLE),
Span::styled("Tip ", theme::SUGGESTION_STYLE),
Span::styled("Block ", theme::SUGGESTION_STYLE),
Span::styled("St ", theme::SUGGESTION_STYLE),
Span::styled("Prv ", theme::SUGGESTION_STYLE),
Span::styled("Age ", theme::SUGGESTION_STYLE),
]));
f.render_widget(header, header_area);
if app.address.txs.items.is_empty() {
let msg = if app.is_loading {
" Loading transactions..."
} else {
" No transactions found"
};
f.render_widget(
Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
),
area,
);
return;
}
let registry = app.search_engine.as_ref().map(|e| e.registry());
app.address
.update_tx_color_map(|addr| registry.is_some_and(|r| r.is_known(addr)));
let gap_suffix = if app.address.unfilled_gaps.is_empty() {
String::new()
} else {
let total_missing: u64 = app
.address
.unfilled_gaps
.iter()
.map(|g| g.missing_count)
.sum();
let n = app.address.unfilled_gaps.len();
let any_pending = app.address.unfilled_gaps.iter().any(|g| !g.fill_dispatched);
if any_pending {
format!(
" — {n} gap{plural} ({total_missing} txs deferred, Enter on a gap row to load) ",
plural = if n == 1 { "" } else { "s" }
)
} else {
format!(
" — {n} gap{plural} ({total_missing} txs, press r to retry) ",
plural = if n == 1 { "" } else { "s" }
)
}
};
let count = tx_count_fragment(app);
let title = if app.is_loading {
format!(" Transactions ({count}) fetching...{gap_suffix} ")
} else {
format!(" Transactions ({count}){gap_suffix} ")
};
let block = list_block(title);
let gaps = app.address.gap_render_positions();
let window = ListWindow::new(
app.address.txs.items.len() + gaps.len(),
app.address.tx_list_rendered_selected_with(&gaps),
app.address.txs_render_state.offset(),
block.inner(list_area).height as usize,
);
let items: Vec<ListItem> = window
.range()
.map(|r| match rendered_row(r, &gaps) {
RenderedRow::Gap(lo) => tx_gap_row(app, lo),
RenderedRow::Item(idx) => tx_row(app, registry, &app.address.txs.items[idx]),
})
.collect();
window.render(
f,
highlighted_list(items, block),
list_area,
&mut app.address.txs_render_state,
);
}
fn tx_gap_row(app: &App, lo_nonce: u64) -> ListItem<'static> {
let msg = match app
.address
.unfilled_gaps
.iter()
.find(|g| g.lo_nonce == lo_nonce)
{
Some(g) if g.fill_dispatched => {
format!(
" ── gap of {} txs — loading / press r to retry ──",
g.missing_count
)
}
Some(g) => format!(
" ── {} txs hidden — press Enter to load ──",
g.missing_count
),
None => " ── gap ──".to_string(),
};
ListItem::new(Line::from(Span::styled(msg, theme::SUGGESTION_STYLE)))
}
fn tx_row(
app: &App,
registry: Option<&AddressRegistry>,
tx: &AddressTxSummary,
) -> ListItem<'static> {
let fee_str = format_strk_u128(tx.total_fee_fri)
.trim_end_matches(" STRK")
.to_string();
let tip_str = if tx.tip > 0 {
format_fri(tx.tip as u128)
} else {
"0".to_string()
};
let age = format_age(tx.timestamp);
let endpoint = if tx.endpoint_names.chars().count() > 30 {
let truncated: String = tx.endpoint_names.chars().take(29).collect();
format!("{truncated}…")
} else {
tx.endpoint_names.clone()
};
let contract_spans = format_called_contracts_spans(app, &tx.called_contracts);
let is_privacy_tx = registry.is_some_and(|reg| {
tx.called_contracts
.iter()
.any(|c| reg.is_privacy_address(c))
});
let status_style = match tx.status.as_str() {
"OK" => theme::STATUS_OK,
"REV" => theme::STATUS_REVERTED,
_ => theme::SUGGESTION_STYLE,
};
let type_style = match tx.tx_type.as_str() {
"INVOKE" => theme::TX_TYPE_INVOKE,
"DECLARE" => theme::TX_TYPE_DECLARE,
"DEPLOY_ACCOUNT" | "DEPLOY" => theme::TX_TYPE_DEPLOY,
"L1_HANDLER" => theme::TX_TYPE_L1HANDLER,
_ => theme::NORMAL_STYLE,
};
let tx_label = app.resolve_tx(&tx.hash);
let tx_hash_display = tx_hash_cell(tx_label, &tx.hash);
let tx_hash_style = if tx_label.is_some() {
theme::LABEL_STYLE
} else {
theme::TX_HASH_STYLE
};
let prv_marker_text = if is_privacy_tx { "🛡 " } else { " " };
let mut row_spans: Vec<Span<'static>> = vec![
Span::styled(format!(" {:<8}", tx.nonce), theme::NORMAL_STYLE),
Span::styled(format!("{:<15}", tx.tx_type), type_style),
Span::styled(format!("{:<14}", tx_hash_display), tx_hash_style),
];
row_spans.extend(contract_spans);
row_spans.extend([
Span::styled(format!("{:<31}", endpoint), theme::LABEL_STYLE),
Span::styled(format!("{:<17}", fee_str), theme::TX_FEE_STYLE),
Span::styled(format!("{:<17}", tip_str), theme::SUGGESTION_STYLE),
Span::styled(
format!("#{:<9}", tx.block_number),
theme::BLOCK_NUMBER_STYLE,
),
Span::styled(format!("{:<4}", tx.status), status_style),
Span::styled(prv_marker_text, theme::PRIVACY_STYLE),
Span::styled(age, theme::BLOCK_AGE_STYLE),
]);
ListItem::new(Line::from(row_spans))
}
fn format_called_contracts_spans(app: &App, contracts: &[Felt]) -> Vec<Span<'static>> {
const CONTENT_BUDGET: usize = 29;
const COLUMN_WIDTH: usize = 30;
if contracts.is_empty() {
return vec![Span::raw(" ".repeat(COLUMN_WIDTH))];
}
let registry = app.search_engine.as_ref().map(|e| e.registry());
let color_map = &app.address.tx_color_map;
let labels: Vec<String> = contracts.iter().map(|c| app.format_address(c)).collect();
let mut spans: Vec<Span<'static>> = Vec::new();
let used_chars;
if labels.len() == 1 {
let label = truncate_to(&labels[0], CONTENT_BUDGET);
let style = known_or_palette_style(&contracts[0], registry, color_map);
used_chars = label.chars().count();
spans.push(Span::styled(label, style));
} else {
let extra = labels.len().saturating_sub(2);
let suffix = if extra > 0 {
format!(" +{extra}")
} else {
String::new()
};
const SEP: &str = ", ";
let inner_budget = CONTENT_BUDGET.saturating_sub(suffix.chars().count() + SEP.len());
let a_budget = inner_budget / 2;
let a = truncate_to(&labels[0], a_budget);
let b_budget = inner_budget.saturating_sub(a.chars().count());
let b = truncate_to(&labels[1], b_budget);
let style_a = known_or_palette_style(&contracts[0], registry, color_map);
let style_b = known_or_palette_style(&contracts[1], registry, color_map);
used_chars = a.chars().count() + SEP.len() + b.chars().count() + suffix.chars().count();
spans.push(Span::styled(a, style_a));
spans.push(Span::styled(SEP, theme::SUGGESTION_STYLE));
spans.push(Span::styled(b, style_b));
if !suffix.is_empty() {
spans.push(Span::styled(suffix, theme::SUGGESTION_STYLE));
}
}
let pad = COLUMN_WIDTH.saturating_sub(used_chars);
if pad > 0 {
spans.push(Span::raw(" ".repeat(pad)));
}
spans
}
fn truncate_to(label: &str, max: usize) -> String {
if max == 0 {
return String::new();
}
if label.chars().count() <= max {
return label.to_string();
}
let head: String = label.chars().take(max - 1).collect();
format!("{head}…")
}
use crate::ui::widgets::hex_display::format_age_short as format_age;
fn draw_calls_tab(f: &mut Frame, app: &mut App, area: Rect) {
let header_area = Rect { height: 1, ..area };
let list_area = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
let header = Paragraph::new(Line::from(vec![
Span::styled(" Sender ", theme::SUGGESTION_STYLE),
Span::styled("Endpoint(s) ", theme::SUGGESTION_STYLE),
Span::styled("Hash ", theme::SUGGESTION_STYLE),
Span::styled("Nonce ", theme::SUGGESTION_STYLE),
Span::styled("Fee(STRK) ", theme::SUGGESTION_STYLE),
Span::styled("Tip ", theme::SUGGESTION_STYLE),
Span::styled("Block ", theme::SUGGESTION_STYLE),
Span::styled("St ", theme::SUGGESTION_STYLE),
Span::styled("Prv ", theme::SUGGESTION_STYLE),
Span::styled("Age ", theme::SUGGESTION_STYLE),
]));
f.render_widget(header, header_area);
if app.address.calls.items.is_empty() {
let msg = if app.is_loading {
" Loading contract calls..."
} else {
" No calls found"
};
f.render_widget(
Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
),
list_area,
);
return;
}
let registry = app.search_engine.as_ref().map(|e| e.registry());
app.address
.update_call_color_map(|addr| registry.is_some_and(|r| r.is_known(addr)));
let viewed_is_privacy = registry
.zip(app.address.info.as_ref())
.map(|(reg, info)| reg.is_privacy_address(&info.address))
.unwrap_or(false);
let gap_suffix = if app.address.call_gaps.is_empty() {
event_window_gap_suffix(app)
} else {
let n = app.address.call_gaps.len();
let plural = if n == 1 { "" } else { "s" };
let any_pending = app.address.call_gaps.iter().any(|g| !g.fill_dispatched);
if any_pending {
format!(" — {n} gap{plural} (Enter on a gap row to load) ")
} else {
format!(" — {n} gap{plural} (loading…) ")
}
};
let count = call_count_fragment(app);
let title = if app.is_loading {
format!(" Calls ({count}) fetching...{gap_suffix} ")
} else {
format!(" Calls ({count}){gap_suffix} ")
};
let block = list_block(title);
let gaps = app.address.call_gap_render_positions();
let window = ListWindow::new(
app.address.calls.items.len() + gaps.len(),
app.address.call_list_rendered_selected_with(&gaps),
app.address.calls_render_state.offset(),
block.inner(list_area).height as usize,
);
let items: Vec<ListItem> = window
.range()
.map(|r| match rendered_row(r, &gaps) {
RenderedRow::Gap(lo) => call_gap_row(app, lo),
RenderedRow::Item(idx) => call_row(
app,
registry,
viewed_is_privacy,
&app.address.calls.items[idx],
),
})
.collect();
window.render(
f,
highlighted_list(items, block),
list_area,
&mut app.address.calls_render_state,
);
}
fn call_gap_row(app: &App, lo_block: u64) -> ListItem<'static> {
let msg = match app
.address
.call_gaps
.iter()
.find(|g| g.lo_block == lo_block)
{
Some(g) if g.fill_dispatched => {
format!(
" ── calls gap (blocks {lo_block}..{}) — loading… ──",
g.hi_block
)
}
Some(g) => format!(
" ── calls gap (blocks {lo_block}..{}) — press Enter to load ──",
g.hi_block
),
None => " ── calls gap ──".to_string(),
};
ListItem::new(Line::from(Span::styled(msg, theme::SUGGESTION_STYLE)))
}
fn call_row(
app: &App,
registry: Option<&AddressRegistry>,
viewed_is_privacy: bool,
call: &ContractCallSummary,
) -> ListItem<'static> {
let sender_style = known_or_palette_style(&call.sender, registry, &app.address.call_color_map);
let sender_label = app.format_address(&call.sender);
let sender_display = if sender_label.chars().count() > 25 {
let truncated: String = sender_label.chars().take(24).collect();
format!("{truncated}…")
} else {
sender_label
};
let func = if call.function_name.chars().count() > 30 {
let truncated: String = call.function_name.chars().take(29).collect();
format!("{truncated}…")
} else {
call.function_name.clone()
};
let fee_str = format_strk_u128(call.total_fee_fri)
.trim_end_matches(" STRK")
.to_string();
let nonce_str = match call.nonce {
Some(n) => n.to_string(),
None => "—".to_string(),
};
let tip_str = if call.tip > 0 {
format_fri(call.tip as u128)
} else {
"0".to_string()
};
let status_style = match call.status.as_str() {
"OK" => theme::STATUS_OK,
"REV" => theme::STATUS_REVERTED,
_ => theme::SUGGESTION_STYLE,
};
let tx_label = app.resolve_tx(&call.tx_hash);
let tx_hash_display = tx_hash_cell(tx_label, &call.tx_hash);
let tx_hash_style = if tx_label.is_some() {
theme::LABEL_STYLE
} else {
theme::TX_HASH_STYLE
};
let is_privacy_call = viewed_is_privacy
|| registry.is_some_and(|reg| call.inner_targets.iter().any(|t| reg.is_privacy_address(t)));
let prv_marker_text = if is_privacy_call { "🛡 " } else { " " };
ListItem::new(Line::from(vec![
Span::styled(format!(" {:<25} ", sender_display), sender_style),
Span::styled(format!("{:<31}", func), theme::LABEL_STYLE),
Span::styled(format!("{:<14}", tx_hash_display), tx_hash_style),
Span::styled(format!("{:<10}", nonce_str), theme::NORMAL_STYLE),
Span::styled(format!("{:<17}", fee_str), theme::TX_FEE_STYLE),
Span::styled(format!("{:<17}", tip_str), theme::SUGGESTION_STYLE),
Span::styled(
format!("#{:<9}", call.block_number),
theme::BLOCK_NUMBER_STYLE,
),
Span::styled(format!("{:<4}", call.status), status_style),
Span::styled(prv_marker_text, theme::PRIVACY_STYLE),
Span::styled(format_age(call.timestamp), theme::BLOCK_AGE_STYLE),
]))
}
fn draw_meta_txs_tab(f: &mut Frame, app: &mut App, area: Rect) {
let header_area = Rect { height: 1, ..area };
let list_area = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
let header = Paragraph::new(Line::from(vec![
Span::styled(" Age ", theme::SUGGESTION_STYLE),
Span::styled("Hash ", theme::SUGGESTION_STYLE),
Span::styled("Block ", theme::SUGGESTION_STYLE),
Span::styled("Paymaster ", theme::SUGGESTION_STYLE),
Span::styled("Ver ", theme::SUGGESTION_STYLE),
Span::styled("Protocol(s) ", theme::SUGGESTION_STYLE),
Span::styled(
"Endpoint(s) ",
theme::SUGGESTION_STYLE,
),
Span::styled("Fee(STRK) ", theme::SUGGESTION_STYLE),
Span::styled("St ", theme::SUGGESTION_STYLE),
Span::styled("Prv ", theme::SUGGESTION_STYLE),
]));
f.render_widget(header, header_area);
if app.address.meta_txs.items.is_empty() {
let msg = if app.address.fetching_meta_txs || !app.address.meta_txs_dispatched {
" Scanning for meta-transactions..."
} else {
" No meta-transactions found (requires pf-query; only Argent/Braavos accounts)"
};
f.render_widget(
Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
),
list_area,
);
return;
}
let gap_suffix = event_window_gap_suffix(app);
let count = meta_tx_count_fragment(app);
let scan_suffix = match app.address.event_window.as_ref() {
Some(hint) if hint.min_searched > 0 && app.address.fetching_meta_txs => {
format!(" scanned to block {}", hint.min_searched)
}
_ => String::new(),
};
let title = if app.address.fetching_meta_txs {
format!(" MetaTxs ({count}) fetching...{scan_suffix}{gap_suffix} ")
} else {
format!(" MetaTxs ({count}){gap_suffix} ")
};
let block = list_block(title);
let window = ListWindow::new(
app.address.meta_txs.items.len(),
app.address.meta_txs.state.selected(),
app.address.meta_txs.state.offset(),
block.inner(list_area).height as usize,
);
let items: Vec<ListItem> = app.address.meta_txs.items[window.range()]
.iter()
.map(|m| meta_tx_row(app, m))
.collect();
window.render(
f,
highlighted_list(items, block),
list_area,
&mut app.address.meta_txs.state,
);
}
fn meta_tx_row(app: &App, m: &MetaTxIntenderSummary) -> ListItem<'static> {
let age = format_age(m.timestamp);
let paymaster_label = app.format_address(&m.paymaster);
let paymaster_display = if paymaster_label.chars().count() > 20 {
let truncated: String = paymaster_label.chars().take(19).collect();
format!("{truncated}…")
} else {
paymaster_label
};
let protocol = match m.inner_targets.first() {
Some(t) => {
let base = app.format_address(t);
let trimmed: String = if base.chars().count() > 16 {
let t: String = base.chars().take(15).collect();
format!("{t}…")
} else {
base
};
let extra = m.inner_targets.len().saturating_sub(1);
if extra > 0 {
format!("{trimmed} +{extra}")
} else {
trimmed
}
}
None => "-".to_string(),
};
let protocol_display = if protocol.chars().count() > 20 {
let truncated: String = protocol.chars().take(19).collect();
format!("{truncated}…")
} else {
protocol
};
let is_privacy_meta = app
.search_engine
.as_ref()
.map(|e| {
let reg = e.registry();
m.inner_targets.iter().any(|t| reg.is_privacy_address(t))
})
.unwrap_or(false);
let protocol_style = if is_privacy_meta {
theme::PRIVACY_STYLE
} else {
theme::LABEL_STYLE
};
let endpoint = if m.inner_endpoints.chars().count() > 34 {
let truncated: String = m.inner_endpoints.chars().take(33).collect();
format!("{truncated}…")
} else {
m.inner_endpoints.clone()
};
let fee_str = format_strk_u128(m.total_fee_fri)
.trim_end_matches(" STRK")
.to_string();
let status_style = match m.status.as_str() {
"OK" => theme::STATUS_OK,
"REV" => theme::STATUS_REVERTED,
_ => theme::SUGGESTION_STYLE,
};
let tx_label = app.resolve_tx(&m.hash);
let tx_hash_display = tx_hash_cell(tx_label, &m.hash);
let tx_hash_style = if tx_label.is_some() {
theme::LABEL_STYLE
} else {
theme::TX_HASH_STYLE
};
let prv_marker_text = if is_privacy_meta { "🛡 " } else { " " };
ListItem::new(Line::from(vec![
Span::styled(format!(" {:<5}", age), theme::BLOCK_AGE_STYLE),
Span::styled(format!("{:<14}", tx_hash_display), tx_hash_style),
Span::styled(
format!("#{:<10}", m.block_number),
theme::BLOCK_NUMBER_STYLE,
),
Span::styled(format!("{:<21}", paymaster_display), theme::LABEL_STYLE),
Span::styled(format!("{:<6}", m.version), theme::SUGGESTION_STYLE),
Span::styled(format!("{:<21}", protocol_display), protocol_style),
Span::styled(format!("{:<35}", endpoint), theme::LABEL_STYLE),
Span::styled(format!("{:<15}", fee_str), theme::TX_FEE_STYLE),
Span::styled(format!("{:<4}", m.status), status_style),
Span::styled(prv_marker_text, theme::PRIVACY_STYLE),
]))
}
fn draw_balances_tab(
f: &mut Frame,
app: &App,
area: Rect,
private_by_token: &[(Felt, u128, usize)],
) {
let info = match &app.address.info {
Some(i) => i,
None => return,
};
let nonzero: Vec<&TokenBalance> = info
.token_balances
.iter()
.filter(|b| felt_to_u128(&b.balance_raw) > 0)
.collect();
if private_by_token.is_empty() {
draw_token_balances(f, app, area, &nonzero);
return;
}
let token_rows = nonzero.len().max(1) as u16;
let token_height = (token_rows + 2).clamp(3, 12);
let holdings_rows = private_by_token.len() as u16;
let holdings_height = (holdings_rows + 2).clamp(3, 12);
let chunks = Layout::default()
.direction(ratatui::layout::Direction::Vertical)
.constraints([
Constraint::Length(token_height),
Constraint::Length(holdings_height),
Constraint::Min(0),
])
.split(area);
draw_token_balances(f, app, chunks[0], &nonzero);
draw_private_holdings(f, app, chunks[1], private_by_token);
}
fn fmt_token_name(name: &str, width: usize) -> String {
fmt_fixed_width(name, width)
}
fn fmt_fixed_width(s: &str, width: usize) -> String {
let len = s.chars().count();
if len <= width {
let pad = " ".repeat(width - len);
format!("{s}{pad}")
} else if width == 0 {
String::new()
} else {
let truncated: String = s.chars().take(width.saturating_sub(1)).collect();
format!("{truncated}…")
}
}
fn draw_token_balances(f: &mut Frame, app: &App, area: Rect, nonzero: &[&TokenBalance]) {
if nonzero.is_empty() {
f.render_widget(
Paragraph::new(" No token balances found")
.style(theme::SUGGESTION_STYLE)
.block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE)
.title(Span::styled(" Token Balances ", theme::TITLE_STYLE)),
),
area,
);
return;
}
let items: Vec<ListItem> = nonzero
.iter()
.map(|bal| {
let formatted = format_token_balance(bal);
let usd_str = balance_usd_value(app, bal)
.map(price::format_usd)
.unwrap_or_default();
let spans = vec![
Span::styled(
format!(" {} ", fmt_token_name(&bal.token_name, 10)),
theme::LABEL_STYLE,
),
Span::styled(fmt_fixed_width(&formatted, 18), theme::NORMAL_STYLE),
Span::styled(format!(" {usd_str}"), theme::SUGGESTION_STYLE),
];
ListItem::new(Line::from(spans))
})
.collect();
let list = List::new(items).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE)
.title(Span::styled(" Token Balances ", theme::TITLE_STYLE)),
);
f.render_widget(list, area);
}
fn compute_private_holdings(app: &App, address: Felt) -> Vec<(Felt, u128, usize)> {
use crate::decode::privacy_sync::NoteDirection;
let mut by_token: std::collections::HashMap<Felt, (u128, usize)> =
std::collections::HashMap::new();
for note in app.private_notes.values() {
if note.user != address {
continue;
}
if note.spent {
continue;
}
if note.direction != NoteDirection::Incoming {
continue;
}
let entry = by_token.entry(note.token).or_insert((0u128, 0usize));
entry.0 = entry.0.saturating_add(note.amount);
entry.1 += 1;
}
let mut rows: Vec<(Felt, u128, usize)> =
by_token.into_iter().map(|(t, (a, n))| (t, a, n)).collect();
rows.sort_by(|a, b| b.1.cmp(&a.1));
rows
}
fn draw_private_holdings(f: &mut Frame, app: &App, area: Rect, rows: &[(Felt, u128, usize)]) {
let items: Vec<ListItem> = rows
.iter()
.map(|(token, amount, n_unspent)| {
let token_name = app.token_symbol(token).unwrap_or_else(|| short_addr(token));
let amount_str =
crate::ui::views::tx_detail::format_amount_for_token(app, token, *amount);
let suffix = if *n_unspent == 1 {
"1 unspent note".to_string()
} else {
format!("{} unspent notes", n_unspent)
};
let usd_str = private_holding_usd(app, token, *amount)
.map(price::format_usd)
.unwrap_or_default();
let spans = vec![
Span::styled(
format!(" {} ", fmt_token_name(&token_name, 10)),
theme::LABEL_STYLE,
),
Span::styled(fmt_fixed_width(&amount_str, 18), theme::NORMAL_STYLE),
Span::styled(
format!(" {}", fmt_fixed_width(&usd_str, 8)),
theme::SUGGESTION_STYLE,
),
Span::styled(format!(" · {}", suffix), theme::SUGGESTION_STYLE),
];
ListItem::new(Line::from(spans))
})
.collect();
let list = List::new(items).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE)
.title(Span::styled(
" Private holdings (viewing key) ",
theme::PRIVACY_STYLE,
)),
);
f.render_widget(list, area);
}
fn short_addr(felt: &Felt) -> String {
let s = format!("{:#x}", felt);
if s.len() <= 10 {
s
} else {
format!("{}…{}", &s[..6], &s[s.len() - 4..])
}
}
fn private_holding_usd(app: &App, token: &Felt, amount: u128) -> Option<f64> {
let price = app.price_client.as_ref()?.get_today_price(token)?;
let registry = app.search_engine.as_ref().map(|e| e.registry())?;
let decimals = registry.get_decimals(token)? as i32;
let raw = amount as f64;
let scale = 10f64.powi(decimals);
Some(raw / scale * price)
}
fn balance_usd_value(app: &App, bal: &TokenBalance) -> Option<f64> {
let price = app
.price_client
.as_ref()?
.get_today_price(&bal.token_address)?;
let raw = felt_to_u128(&bal.balance_raw) as f64;
let scale = 10f64.powi(bal.decimals as i32);
Some(raw / scale * price)
}
fn draw_transfers_tab(f: &mut Frame, app: &mut App, area: Rect) {
let header_area = Rect { height: 1, ..area };
let list_area = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
let header = Paragraph::new(Line::from(vec![
Span::styled(" Dir ", theme::SUGGESTION_STYLE),
Span::styled("Token ", theme::SUGGESTION_STYLE),
Span::styled(" Amount ", theme::SUGGESTION_STYLE),
Span::styled(" USD ", theme::SUGGESTION_STYLE),
Span::styled("From ", theme::SUGGESTION_STYLE),
Span::styled("To ", theme::SUGGESTION_STYLE),
Span::styled("Tx ", theme::SUGGESTION_STYLE),
Span::styled("Block ", theme::SUGGESTION_STYLE),
Span::styled("Age ", theme::SUGGESTION_STYLE),
]));
f.render_widget(header, header_area);
let gaps = app.address.transfer_gap_render_positions();
if app.address.transfers.items.is_empty() && gaps.is_empty() {
let msg = if app.address.fetching_transfers {
" Loading transfers..."
} else if app.address.transfers_dispatched {
" No transfers found"
} else {
" Press Tab to reach this tab; transfers load on entry"
};
f.render_widget(
Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
),
list_area,
);
return;
}
let registry = app.search_engine.as_ref().map(|e| e.registry());
app.address
.update_transfer_color_map(|addr| registry.is_some_and(|r| r.is_known(addr)));
let gap_suffix = if app.address.transfer_gaps.is_empty() {
String::new()
} else {
let n = app.address.transfer_gaps.len();
let plural = if n == 1 { "" } else { "s" };
if app.address.transfer_gaps.iter().any(|g| !g.fill_dispatched) {
format!(" — {n} gap{plural} (Enter on a gap row to load) ")
} else {
format!(" — {n} gap{plural} (loading…) ")
}
};
let count = transfers_count_fragment(app);
let title = if app.address.fetching_transfers {
format!(" Transfers ({count}) fetching...{gap_suffix} ")
} else {
format!(" Transfers ({count}){gap_suffix} ")
};
let block = list_block(title);
let viewed = app.address.context.unwrap_or(Felt::ZERO);
let selected_nav: Option<&TxNavItem> = if app.address.visual_mode {
app.address.nav_items.get(app.address.nav_cursor)
} else {
None
};
let window = ListWindow::new(
app.address.transfers.items.len() + gaps.len(),
app.address.transfer_list_rendered_selected_with(&gaps),
app.address.transfers_render_state.offset(),
block.inner(list_area).height as usize,
);
let items: Vec<ListItem> = window
.range()
.map(|r| match rendered_row(r, &gaps) {
RenderedRow::Gap(lo) => transfer_gap_row(app, lo),
RenderedRow::Item(idx) => transfer_row(
app,
registry,
viewed,
selected_nav,
&app.address.transfers.items[idx],
),
})
.collect();
window.render(
f,
highlighted_list(items, block),
list_area,
&mut app.address.transfers_render_state,
);
}
fn transfer_gap_row(app: &App, lo_block: u64) -> ListItem<'static> {
let Some(g) = app
.address
.transfer_gaps
.iter()
.find(|g| g.lo_block == lo_block)
else {
return ListItem::new(Line::from(Span::styled(
" ── transfers gap ──",
theme::SUGGESTION_STYLE,
)));
};
let is_bottom = g.lo_block == app.address.transfer_floor();
let span = g.hi_block.saturating_sub(g.lo_block).saturating_add(1);
let what = if is_bottom {
format!(
"{span} older blocks unsearched (below block {})",
g.hi_block + 1
)
} else {
format!("transfers gap (blocks {}..{})", g.lo_block, g.hi_block)
};
let action = match (g.fill_dispatched, is_bottom) {
(true, _) => "loading…",
(false, true) => "press Enter to search further",
(false, false) => "press Enter to load",
};
ListItem::new(Line::from(Span::styled(
format!(" ── {what} — {action} ──"),
theme::SUGGESTION_STYLE,
)))
}
fn transfer_value_usd(app: &App, t: &TokenTransfer) -> Option<f64> {
if let Some(v) = t.value_usd {
return Some(v);
}
if t.amount_high != 0 || t.timestamp == 0 {
return None;
}
let decimals = app.token_decimals(&t.token).or(t.decimals)?;
let (_, historic) = price::token_prices(app, &t.token, Some(t.timestamp));
Some(t.amount_low as f64 / 10f64.powi(decimals as i32) * historic?)
}
fn transfer_party_style(
app: &App,
registry: Option<&AddressRegistry>,
viewed: Felt,
selected_nav: Option<&TxNavItem>,
addr: &Felt,
) -> ratatui::style::Style {
if matches!(selected_nav, Some(TxNavItem::Address(a)) if a == addr) {
return theme::VISUAL_SELECTED_STYLE;
}
if *addr == viewed {
return theme::TX_SENDER_STYLE;
}
known_or_palette_style(addr, registry, &app.address.transfer_color_map)
}
fn transfer_row(
app: &App,
registry: Option<&AddressRegistry>,
viewed: Felt,
selected_nav: Option<&TxNavItem>,
t: &TokenTransfer,
) -> ListItem<'static> {
let (dir, dir_style) = match (t.from == viewed, t.to == viewed) {
(true, true) => ("SELF", theme::SUGGESTION_STYLE),
(false, true) => ("IN", theme::STATUS_OK),
(true, false) => ("OUT", theme::STATUS_REVERTED),
(false, false) => ("?", theme::SUGGESTION_STYLE),
};
let token_label = app
.token_symbol(&t.token)
.or_else(|| t.symbol.clone())
.unwrap_or_else(|| short_address(&t.token));
let token_style = if matches!(selected_nav, Some(TxNavItem::Address(a)) if *a == t.token) {
theme::VISUAL_SELECTED_STYLE
} else if registry.is_some_and(|r| r.is_known(&t.token)) {
theme::LABEL_STYLE
} else {
theme::NORMAL_STYLE
};
let amount = match app.token_decimals(&t.token).or(t.decimals) {
Some(d) => format_token_amount(t.amount_low, t.amount_high, d),
None if t.amount_high == 0 => t.amount_low.to_string(),
None => format!("0x{:x}{:032x}", t.amount_high, t.amount_low),
};
let usd = transfer_value_usd(app, t)
.map(price::format_usd)
.unwrap_or_default();
let from_style = transfer_party_style(app, registry, viewed, selected_nav, &t.from);
let to_style = transfer_party_style(app, registry, viewed, selected_nav, &t.to);
let tx_label = app.resolve_tx(&t.tx_hash);
let tx_style = if matches!(selected_nav, Some(TxNavItem::Transaction(h)) if *h == t.tx_hash) {
theme::VISUAL_SELECTED_STYLE
} else if tx_label.is_some() {
theme::LABEL_STYLE
} else {
theme::TX_HASH_STYLE
};
let block_style = if matches!(selected_nav, Some(TxNavItem::Block(b)) if *b == t.block_number) {
theme::VISUAL_SELECTED_STYLE
} else {
theme::BLOCK_NUMBER_STYLE
};
ListItem::new(Line::from(vec![
Span::styled(format!(" {dir:<4} "), dir_style),
Span::styled(
format!("{:<12}", truncate_to(&token_label, 11)),
token_style,
),
Span::styled(
format!("{:>19} ", truncate_to(&amount, 19)),
theme::TX_HASH_STYLE,
),
Span::styled(
format!("{:>13} ", truncate_to(&usd, 13)),
theme::SUGGESTION_STYLE,
),
Span::styled(
format!("{:<24}", truncate_to(&app.format_address(&t.from), 23)),
from_style,
),
Span::styled(
format!("{:<24}", truncate_to(&app.format_address(&t.to), 23)),
to_style,
),
Span::styled(
format!("{:<15}", tx_hash_cell(tx_label, &t.tx_hash)),
tx_style,
),
Span::styled(format!("{:<11}", t.block_number), block_style),
Span::styled(format_age(t.timestamp), theme::BLOCK_AGE_STYLE),
]))
}
fn draw_events_tab(f: &mut Frame, app: &mut App, area: Rect) {
let header_area = Rect { height: 1, ..area };
let list_area = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
let header = Paragraph::new(Line::from(vec![
Span::styled(" Event ", theme::SUGGESTION_STYLE),
Span::styled("Contract ", theme::SUGGESTION_STYLE),
Span::styled("Tx ", theme::SUGGESTION_STYLE),
]));
f.render_widget(header, header_area);
if app.address.events.items.is_empty() {
let msg = if app.is_loading {
" Loading events..."
} else {
" No events found"
};
f.render_widget(
Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
),
list_area,
);
return;
}
let count = events_count_fragment(app);
let title = if app.is_loading {
format!(" Events ({count}) fetching... ")
} else {
format!(" Events ({count}) ")
};
let block = list_block(title);
let window = ListWindow::new(
app.address.events.items.len(),
app.address.events.state.selected(),
app.address.events.state.offset(),
block.inner(list_area).height as usize,
);
let items: Vec<ListItem> = app.address.events.items[window.range()]
.iter()
.map(|event| {
let contract = app.format_address(&event.contract_address);
let name = event.event_name.as_deref().unwrap_or("?");
let tx_hash = event.raw.transaction_hash;
let tx_label = app.resolve_tx(&tx_hash);
let tx_display = tx_hash_cell(tx_label, &tx_hash);
let tx_style = if tx_label.is_some() {
theme::LABEL_STYLE
} else {
theme::TX_HASH_STYLE
};
ListItem::new(Line::from(vec![
Span::styled(format!(" {:<20}", name), theme::LABEL_STYLE),
Span::styled(format!("{:<17}", contract), theme::BLOCK_HASH_STYLE),
Span::styled(tx_display, tx_style),
]))
})
.collect();
window.render(
f,
highlighted_list(items, block),
list_area,
&mut app.address.events.state,
);
}
fn format_token_balance(bal: &TokenBalance) -> String {
let raw = felt_to_u128(&bal.balance_raw);
if raw == 0 {
return "0".to_string();
}
let divisor = 10u128.pow(bal.decimals as u32);
let whole = raw / divisor;
let frac = raw % divisor;
let frac_digits = bal.decimals.min(6) as u32;
let frac_divisor = 10u128.pow(bal.decimals as u32 - frac_digits);
let frac_display = frac / frac_divisor;
format!(
"{}.{:0>width$}",
whole,
frac_display,
width = frac_digits as usize
)
}
fn draw_class_history_tab(f: &mut Frame, app: &App, area: Rect) {
let header_area = Rect { height: 1, ..area };
let list_area = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
let header = Paragraph::new(Line::from(vec![
Span::styled(" Block ", theme::SUGGESTION_STYLE),
Span::styled(
"Class Hash ",
theme::SUGGESTION_STYLE,
),
]));
f.render_widget(header, header_area);
if app.address.class_history.is_empty() {
let msg = if app.is_loading {
" Loading class history..."
} else {
" No class history available (requires PF service)"
};
f.render_widget(
Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
),
list_area,
);
return;
}
let items: Vec<ListItem> = app
.address
.class_history
.iter()
.enumerate()
.map(|(i, entry)| {
let hash_display = if entry.class_hash.len() > 66 {
format!("{}…", &entry.class_hash[..65])
} else {
entry.class_hash.clone()
};
let is_selected = i == app.address.class_history_scroll;
let hash_style = if is_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::TX_HASH_STYLE
};
let marker = if is_selected { "►" } else { " " };
let line = Line::from(vec![
Span::styled(
marker,
if is_selected {
theme::VISUAL_SELECTED_STYLE
} else {
theme::NORMAL_STYLE
},
),
Span::styled(
format!("#{:<14}", entry.block_number),
theme::BLOCK_NUMBER_STYLE,
),
Span::styled(format!("{:<68}", hash_display), hash_style),
]);
ListItem::new(line)
})
.collect();
let list = List::new(items).block(
Block::default()
.borders(Borders::ALL)
.border_style(theme::BORDER_STYLE),
);
f.render_widget(list, list_area);
}
#[cfg(test)]
mod count_fragment_tests {
use super::{CountBound, count_fragment};
#[test]
fn exact_shown_less_than_total_renders_fraction() {
assert_eq!(count_fragment(7, CountBound::Exact(20)), "7 / 20");
}
#[test]
fn exact_shown_equal_total_renders_bare_count() {
assert_eq!(count_fragment(20, CountBound::Exact(20)), "20");
}
#[test]
fn exact_shown_greater_than_total_falls_back_to_bare_count() {
assert_eq!(count_fragment(20, CountBound::Exact(7)), "20");
}
#[test]
fn lower_bound_without_hint_renders_shown_over_shown_plus() {
assert_eq!(
count_fragment(7, CountBound::LowerBound { hint: None }),
"7 / 7+"
);
}
#[test]
fn lower_bound_zero_renders_zero_over_zero_plus() {
assert_eq!(
count_fragment(0, CountBound::LowerBound { hint: None }),
"0 / 0+"
);
}
#[test]
fn lower_bound_with_hint_above_shown_renders_fraction_plus() {
assert_eq!(
count_fragment(7, CountBound::LowerBound { hint: Some(100) }),
"7 / 100+"
);
}
#[test]
fn lower_bound_with_hint_at_or_below_shown_falls_back_to_shown_denominator() {
assert_eq!(
count_fragment(7, CountBound::LowerBound { hint: Some(3) }),
"7 / 7+"
);
assert_eq!(
count_fragment(7, CountBound::LowerBound { hint: Some(7) }),
"7 / 7+"
);
}
}