-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtui_wallet.py
More file actions
1739 lines (1486 loc) · 63.6 KB
/
Copy pathtui_wallet.py
File metadata and controls
1739 lines (1486 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Coldstar TUI Wallet - Live version with real wallet integration
"""
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical, ScrollableContainer
from textual.widgets import Header, Footer, Static, Button, Input, Label
from textual.screen import ModalScreen
from textual.binding import Binding
from textual.reactive import reactive
from textual.message import Message
from rich.text import Text
from datetime import datetime
from typing import Optional
# Import wallet components
from src.wallet import WalletManager
from src.usb import USBManager
from src.network import SolanaNetwork
from src.transaction import TransactionManager
from src.token_fetcher import TokenFetcher
from src.token_logos import TokenLogoManager
from config import SOLANA_RPC_URL
class LiveStatusBar(Static):
"""Top status bar with live wallet info"""
wallet_name = reactive("No USB")
mode = reactive("OFFLINE")
network_status = reactive("Disconnected")
def render(self) -> Text:
text = Text()
text.append("❄ COLDSTAR", style="bold #38bdf8")
text.append(" ", style="")
text.append(f"{self.wallet_name}", style="#7dd3fc")
text.append(" ", style="")
if self.mode == "SYNCING...":
text.append(self.mode, style="bold #f59e0b")
elif self.mode == "OFFLINE":
text.append(self.mode, style="bold #ef4444")
else:
text.append(self.mode, style="bold #4ade80")
text.append(" ", style="")
if "Connected" in self.network_status:
text.append("● ", style="#4ade80")
text.append(self.network_status, style="#4ade80")
else:
text.append("● ", style="#ef4444")
text.append(self.network_status, style="#ef4444")
return text
class LiveInfoBar(Static):
"""Second bar with live sync status and portfolio value"""
balance = reactive(0.0)
last_sync = reactive("Never")
warnings = reactive(0)
public_key = reactive("")
def render(self) -> Text:
text = Text()
text.append("Wallet: ", style="#64748b")
if self.public_key:
text.append(f"{self.public_key[:8]}...{self.public_key[-8:]}", style="bold #38bdf8")
else:
text.append("(No wallet loaded)", style="#ef4444")
text.append(" ", style="")
text.append(f"{self.balance:.6f} SOL", style="bold #4ade80")
text.append(" ", style="")
text.append(f"sync {self.last_sync}", style="#64748b")
if self.warnings > 0:
text.append(f" ⚠ {self.warnings}", style="#f59e0b")
return text
class LivePortfolioPanel(Static):
"""Portfolio panel with live multi-token balance"""
can_focus = True # Allow arrow key focus
BINDINGS = [
Binding("up", "select_prev", "Previous token", show=False),
Binding("down", "select_next", "Next token", show=False),
]
sol_balance = reactive(0.0)
tokens = reactive([])
public_key = reactive("")
selected_index = reactive(0) # 0 = SOL, 1+ = tokens
def compose(self) -> ComposeResult:
yield Static(" PORTFOLIO ↑↓ select TAB focus", classes="panel-header")
yield ScrollableContainer(
Static("", id="portfolio-content")
)
def on_mount(self) -> None:
"""Render initial state on mount"""
self.refresh_portfolio()
def action_select_prev(self) -> None:
"""Move selection up"""
if self.selected_index > 0:
self.selected_index -= 1
def action_select_next(self) -> None:
"""Move selection down"""
max_index = len(self.tokens) # 0=SOL, 1..N=tokens
if self.selected_index < max_index:
self.selected_index += 1
def watch_sol_balance(self, balance: float) -> None:
"""Update display when SOL balance changes"""
self.refresh_portfolio()
def watch_tokens(self, tokens: list) -> None:
"""Update display when tokens change"""
self.refresh_portfolio()
def watch_public_key(self, key: str) -> None:
"""Update display when public key changes"""
self.refresh_portfolio()
def watch_selected_index(self, index: int) -> None:
"""Update display when selection changes"""
self.refresh_portfolio()
# Notify the app about selection change
self.post_message(self.TokenSelected(index))
class TokenSelected(Message):
"""Message when a token is selected"""
def __init__(self, index: int):
super().__init__()
self.index = index
def refresh_portfolio(self) -> None:
"""Refresh the multi-token portfolio display"""
content = self.query_one("#portfolio-content", Static)
text = Text()
# Get logo manager from app
logo_manager = self.app.logo_manager
# Highlight colours
SEL_BG = "on #1e3a5f" # selected row background
SEL_NAME = f"bold white {SEL_BG}"
SEL_BAL = f"bold #38bdf8 {SEL_BG}"
SEL_USD = f"bold #4ade80 {SEL_BG}"
SEL_PFX = f"bold #38bdf8 {SEL_BG}"
UNS_NAME = "bold #94a3b8"
UNS_BAL = "#7dd3fc"
UNS_USD = "#4ade80"
def _usd(symbol: str, balance: float) -> float:
if symbol in ("USDC", "USDT"): return balance
if symbol == "RAY": return balance * 0.17
if symbol == "BONK": return balance * 0.00001
if symbol == "JUP": return balance * 0.65
return 0.0
def _bal_str(balance: float) -> str:
return f"{balance:,.2f}" if balance >= 1000 else f"{balance:.4f}"
# SOL row (index 0)
is_sel = self.selected_index == 0
sol_icon = logo_manager.get_token_icon("SOL")
sol_value = self.sol_balance * 147.50
bg = SEL_BG if is_sel else ""
text.append("\n")
text.append(f" {'◆' if is_sel else ' '} {sol_icon}{'SOL':<8}", style=SEL_PFX if is_sel else UNS_NAME)
text.append(f"{self.sol_balance:>12.4f}", style=SEL_BAL if is_sel else UNS_BAL)
text.append(f" ${sol_value:>8.2f} ", style=SEL_USD if is_sel else UNS_USD)
# SPL token rows
for idx, token in enumerate(self.tokens, start=1):
symbol = token.get("symbol", "Unknown")
balance = token.get("balance", 0)
is_sel = self.selected_index == idx
icon = logo_manager.get_token_icon(symbol)
usd_val = _usd(symbol, balance)
bal_str = _bal_str(balance)
text.append("\n")
text.append(f" {'◆' if is_sel else ' '} {icon}{symbol:<8}", style=SEL_PFX if is_sel else UNS_NAME)
text.append(f"{bal_str:>12}", style=SEL_BAL if is_sel else UNS_BAL)
if usd_val > 0:
text.append(f" ${usd_val:>8.2f} ", style=SEL_USD if is_sel else UNS_USD)
else:
text.append(f" {'—':>9} ", style=f"dim {SEL_BG}" if is_sel else "dim")
# Total portfolio value
total_value = sol_value + sum([
t.get("balance", 0) if t.get("symbol") in ["USDC", "USDT"] else 0
for t in self.tokens
])
text.append(f"\n\n{'━' * 40}\n", style="bold cyan")
text.append(f" TOTAL ", style="bold white on dark_green")
text.append(f" ${total_value:,.2f} USD", style="bold green")
# ALWAYS show full public key section for copying
text.append(f"\n\n{'─' * 40}\n", style="dim")
text.append("Public Key ", style="cyan bold")
text.append("[c] copy\n", style="cyan dim")
if self.public_key:
text.append(f"{self.public_key[:44]}\n", style="cyan")
text.append(f"{self.public_key[44:]}", style="cyan")
else:
text.append("(No wallet loaded)\n", style="dim red")
content.update(text)
class TokenDetailsPanel(Static):
"""Top panel - Selected token details"""
selected_token = reactive(None)
sol_balance = reactive(0.0)
def compose(self) -> ComposeResult:
yield Static(" TOKEN DETAILS", classes="panel-header")
yield ScrollableContainer(
Static("", id="token-details-content")
)
def watch_selected_token(self, token: dict) -> None:
"""Update when selected token changes"""
self.refresh_details()
def watch_sol_balance(self, balance: float) -> None:
"""Update when SOL balance changes"""
self.refresh_details()
def refresh_details(self) -> None:
"""Refresh token details display"""
content = self.query_one("#token-details-content", Static)
text = Text()
# Get logo manager from app
logo_manager = self.app.logo_manager
if self.selected_token is None:
# Default: Show SOL details
sol_icon = logo_manager.get_token_icon("SOL")
text.append(f"\n{sol_icon}", style="")
text.append("SOL (Solana)\n", style="bold white")
text.append("─" * 35 + "\n\n", style="dim")
text.append("Native Token\n", style="dim")
text.append(f"Decimals: 9\n", style="dim")
text.append(f"Balance: {self.sol_balance:.9f} SOL\n", style="cyan")
text.append(f"Value: ${self.sol_balance * 147.50:.2f} USD\n\n", style="green")
text.append("Network Info:\n", style="bold dim")
text.append("• Fast & low-cost transactions\n", style="dim")
text.append("• Proof of Stake consensus\n", style="dim")
text.append("• ~400ms block time\n", style="dim")
else:
# Show selected token details
symbol = self.selected_token.get("symbol", "Unknown")
mint = self.selected_token.get("mint", "")
balance = self.selected_token.get("balance", 0)
decimals = self.selected_token.get("decimals", 0)
# Get real token logo image or empty string (NO FALLBACK)
icon = logo_manager.get_token_icon(symbol)
text.append(f"\n{icon}", style="")
text.append(f"{symbol}\n", style="bold white")
text.append("─" * 35 + "\n\n", style="dim")
text.append(f"Mint: {mint[:20]}...\n", style="dim")
text.append(f" ...{mint[-20:]}\n", style="dim")
text.append(f"Decimals: {decimals}\n", style="dim")
text.append(f"Type: SPL Token\n\n", style="dim")
if balance >= 1000:
balance_str = f"{balance:,.2f}"
else:
balance_str = f"{balance:.4f}"
text.append(f"Balance: {balance_str} {symbol}\n", style="cyan")
# Calculate USD value
usd_value = 0.0
if symbol in ["USDC", "USDT"]:
usd_value = balance
text.append(f"Value: ${usd_value:,.2f} USD\n", style="green")
text.append("\n💰 Stablecoin (1:1 USD)\n", style="dim")
elif symbol == "RAY":
usd_value = balance * 0.17
text.append(f"Value: ${usd_value:,.2f} USD\n", style="green")
elif symbol == "BONK":
usd_value = balance * 0.00001
text.append(f"Value: ${usd_value:,.6f} USD\n", style="green")
elif symbol == "JUP":
usd_value = balance * 0.65
text.append(f"Value: ${usd_value:,.2f} USD\n", style="green")
# Token-specific info
if symbol == "USDC":
text.append("\nToken Info:\n", style="bold dim")
text.append("• Circle USD Coin\n", style="dim")
text.append("• Verified stablecoin\n", style="dim")
text.append("• Widely accepted\n", style="dim")
content.update(text)
class TokenSecurityPanel(Static):
"""Bottom-centre panel - RugCheck security info"""
selected_token = reactive(None)
security_data = reactive(None)
def compose(self) -> ComposeResult:
yield Static(" TOKEN SECURITY", classes="panel-header")
yield ScrollableContainer(
Static("", id="security-content")
)
def watch_selected_token(self, token: dict) -> None:
"""Fetch security data when token changes"""
if token and token.get("mint"):
mint = token["mint"]
# Reset to loading state
self.security_data = None
# Fetch in background
self.app.run_worker(
lambda: self._fetch_security(mint),
thread=True
)
else:
self.security_data = None
self.refresh_security()
def watch_security_data(self, data: dict) -> None:
"""Update display when security data arrives"""
self.refresh_security()
def _fetch_security(self, mint: str) -> None:
"""Background worker: fetch RugCheck data"""
if "devnet" in SOLANA_RPC_URL or "testnet" in SOLANA_RPC_URL:
self.app.call_from_thread(setattr, self, "security_data", {"error": "non_mainnet"})
return
try:
url = f"https://premium.rugcheck.xyz/v1/tokens/{mint}/report"
headers = {"X-API-KEY": "f1de9137-eb1d-4341-9da7-b6920b4839c4"}
response = None
try:
import httpx
with httpx.Client(timeout=10.0) as client:
response = client.get(url, headers=headers)
except Exception:
try:
import requests
response = requests.get(url, headers=headers, timeout=10)
except Exception as e:
self.app.call_from_thread(setattr, self, "security_data", {"error": f"http_client:{str(e)[:30]}"})
return
if response is None:
self.app.call_from_thread(setattr, self, "security_data", {"error": "no_response"})
return
if response.status_code == 200:
self.app.call_from_thread(setattr, self, "security_data", response.json())
elif response.status_code in (401, 403):
self.app.call_from_thread(setattr, self, "security_data", {"error": "auth"})
elif response.status_code == 429:
self.app.call_from_thread(setattr, self, "security_data", {"error": "rate_limited"})
elif response.status_code == 400:
# 400 = invalid/unknown token (likely not indexed)
self.app.call_from_thread(setattr, self, "security_data", {"error": "unknown_token"})
else:
self.app.call_from_thread(setattr, self, "security_data", {"error": f"API error {response.status_code}"})
except Exception as e:
self.app.call_from_thread(setattr, self, "security_data", {"error": f"Check failed: {str(e)[:30]}"})
def refresh_security(self) -> None:
"""Refresh security display"""
content = self.query_one("#security-content", Static)
text = Text()
if not self.selected_token:
text.append("\nSelect an SPL token to view security info\n", style="dim")
elif not self.security_data:
text.append("\nLoading security check...\n", style="#f59e0b")
elif "error" in self.security_data:
error = self.security_data['error']
if error == "non_mainnet":
text.append("\nℹ Info\n", style="bold #38bdf8")
text.append("─" * 35 + "\n\n", style="dim")
text.append("Security checks are only available\n", style="dim")
text.append("on mainnet.\n\n", style="dim")
elif error == "unknown_token":
text.append("\nℹ Info\n", style="bold #38bdf8")
text.append("─" * 35 + "\n\n", style="dim")
text.append("Token not indexed yet by RugCheck.\n", style="dim")
text.append("Try again later.\n\n", style="dim")
elif error == "auth":
text.append("\n⚠ RugCheck API Key\n", style="bold #f59e0b")
text.append("─" * 35 + "\n\n", style="dim")
text.append("API key invalid or expired.\n", style="dim")
text.append("Update the RugCheck key.\n\n", style="dim")
elif error == "rate_limited":
text.append("\n⏳ Rate Limited\n", style="bold #f59e0b")
text.append("─" * 35 + "\n\n", style="dim")
text.append("Too many requests. Try again.\n\n", style="dim")
elif error.startswith("http_client"):
text.append("\n⚠ HTTP Client Error\n", style="bold #f59e0b")
text.append("─" * 35 + "\n\n", style="dim")
text.append("Failed to call RugCheck API.\n", style="dim")
text.append("Install httpx or requests.\n\n", style="dim")
else:
text.append("\n⚠ Security Check Failed\n", style="bold #f59e0b")
text.append("─" * 35 + "\n\n", style="dim")
text.append(f"Error: {error}\n", style="dim")
text.append("Try again later.\n\n", style="dim")
else:
# Display RugCheck results
data = self.security_data
symbol = self.selected_token.get("symbol", "TOKEN")
text.append(f"\n{symbol} Security Report\n", style="bold white")
text.append("─" * 35 + "\n\n", style="dim")
# Safety Score (0-1 normalized)
score = data.get("score_normalised", 0)
score_pct = int(score * 100)
if score >= 0.8:
text.append("Safety Score: ", style="dim")
text.append(f"{score_pct}% ", style="bold #4ade80")
text.append("✓ GOOD\n", style="#4ade80")
elif score >= 0.5:
text.append("Safety Score: ", style="dim")
text.append(f"{score_pct}% ", style="bold #f59e0b")
text.append("⚠ WARNING\n", style="#f59e0b")
else:
text.append("Safety Score: ", style="dim")
text.append(f"{score_pct}% ", style="bold #ef4444")
text.append("⚠ DANGER\n", style="#ef4444")
text.append("\n", style="")
# Rugged status
if data.get("rugged"):
text.append("⛔ RUGGED TOKEN DETECTED\n\n", style="bold #ef4444")
# Key metrics
text.append("Token Info:\n", style="bold dim")
token_type = data.get("tokenType") or "Unknown"
if token_type:
text.append(f"• Type: {token_type}\n", style="dim")
holders = data.get("totalHolders", 0)
if holders > 0:
text.append(f"• Holders: {holders:,}\n", style="dim")
liq = data.get("totalStableLiquidity", 0)
if liq > 0:
text.append(f"• Liquidity: ${liq:,.0f}\n", style="dim")
# Risks
risks = data.get("risks")
if risks:
text.append("\n⚠ Risks Detected:\n", style="bold #f59e0b")
risk_list = []
for risk_item in risks[:5]:
if isinstance(risk_item, dict):
risk_list.append(risk_item.get("name", str(risk_item)))
else:
risk_list.append(str(risk_item))
for risk_name in risk_list:
text.append(f"• {risk_name}\n", style="#f59e0b")
content.update(text)
class TransactionHistoryPanel(Static):
"""Bottom panel - Transaction history"""
can_focus = True
BINDINGS = [
Binding("up", "select_prev", "Previous tx", show=False),
Binding("down", "select_next", "Next tx", show=False),
]
transactions = reactive([])
page_size = reactive(5) # Start with 5, load more on demand
selected_index = reactive(0)
def compose(self) -> ComposeResult:
yield Static(" TRANSACTIONS", classes="panel-header")
yield ScrollableContainer(
Static("", id="tx-history-content"),
Button("Load more...", id="btn-load-more", variant="default"),
)
yield Static("", id="tx-detail")
def on_mount(self) -> None:
self.query_one("#btn-load-more").display = False
def watch_transactions(self, txs: list) -> None:
"""Update when transactions change"""
self.page_size = 5 # Reset to first page on new data
if self.selected_index >= len(txs):
self.selected_index = max(0, len(txs) - 1)
self.refresh_history()
def watch_page_size(self, size: int) -> None:
self.refresh_history()
def watch_selected_index(self, index: int) -> None:
self.refresh_history()
def action_select_prev(self) -> None:
if self.selected_index > 0:
self.selected_index -= 1
def action_select_next(self) -> None:
if self.selected_index < max(0, len(self.transactions) - 1):
self.selected_index += 1
if self.selected_index >= self.page_size and self.page_size < len(self.transactions):
self.page_size += 5
def get_selected_signature(self) -> Optional[str]:
if not self.transactions:
return None
return self.transactions[self.selected_index].get("signature")
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "btn-load-more":
self.page_size += 5
self.post_message(self.LoadMore())
class LoadMore(Message):
"""Request more transactions from the app"""
pass
def refresh_history(self) -> None:
"""Refresh transaction history"""
content = self.query_one("#tx-history-content", Static)
btn = self.query_one("#btn-load-more")
detail = self.query_one("#tx-detail", Static)
text = Text()
if not self.transactions:
text.append("\nNo transactions yet\n", style="dim")
btn.display = False
detail.update("[dim]Select a transaction to view details[/dim]")
else:
visible = self.transactions[:self.page_size]
has_more = len(self.transactions) > self.page_size
for idx, tx in enumerate(visible):
signature = tx.get("signature", "Unknown")
err = tx.get("err")
status = "✓" if err is None else "✗"
status_color = "green" if err is None else "red"
is_sel = idx == self.selected_index
block_time = tx.get("blockTime")
if block_time:
import datetime as dt_mod
dt = dt_mod.datetime.fromtimestamp(block_time)
time_str = dt.strftime("%m/%d %H:%M")
else:
time_str = "Pending "
sig_short = f"{signature[:6]}...{signature[-6:]}"
# Direction arrow + amount
direction = tx.get("direction")
sol_delta = tx.get("sol_delta")
if direction == "sent" and sol_delta is not None:
dir_str = "↑ SENT "
dir_color = "red"
amt_str = f"-{abs(sol_delta):.6f} SOL"
amt_color = "red"
elif direction == "received" and sol_delta is not None:
dir_str = "↓ RECV "
dir_color = "green"
amt_str = f"+{abs(sol_delta):.6f} SOL"
amt_color = "green"
else:
dir_str = " ------ "
dir_color = "dim"
amt_str = ""
amt_color = "dim"
row_style = "on #1e3a5f" if is_sel else ""
text.append(f"\n{status} ", style=f"{status_color} {row_style}".strip())
text.append(f"{time_str} ", style="dim")
text.append(f"{dir_str}", style=f"{dir_color} {row_style}".strip())
if amt_str:
text.append(f"{amt_str:<18}", style=f"{amt_color} {row_style}".strip())
text.append(sig_short, style=f"cyan {row_style}".strip())
if err:
text.append(" FAILED", style=f"bold red {row_style}".strip())
btn.display = has_more
if has_more:
remaining = len(self.transactions) - self.page_size
btn.label = f"Load {min(remaining, 5)} more ({remaining} remaining)"
content.update(text)
if self.transactions:
tx = self.transactions[self.selected_index]
signature = tx.get("signature", "")
slot = tx.get("slot", "N/A")
err = tx.get("err")
block_time = tx.get("blockTime")
time_str = datetime.fromtimestamp(block_time).strftime("%Y-%m-%d %H:%M:%S") if block_time else "Pending"
sol_delta = tx.get("sol_delta")
fee_sol = tx.get("fee_sol")
delta_str = f"{sol_delta:+.6f} SOL" if isinstance(sol_delta, (int, float)) else "—"
fee_str = f"{fee_sol:.6f} SOL" if isinstance(fee_sol, (int, float)) else "—"
status = "✓ Success" if err is None else "✗ Failed"
link = ""
try:
link = self.app._tx_explorer_link(signature)
except Exception:
link = ""
detail.update(
f"[bold]Selected:[/bold] {signature[:10]}...{signature[-10:]}\n"
f"Status: {status}\n"
f"Slot: {slot} Time: {time_str}\n"
f"Amount: {delta_str} Fee: {fee_str}\n"
f"Explorer: {link}\n"
f"[dim]Press x to copy explorer link[/dim]"
)
class LiveSendPanel(Static):
"""Send panel with live wallet connection"""
current_balance = reactive(0.0)
_confirming = False # True when showing password confirm step
def compose(self) -> ComposeResult:
yield Static(" SEND TOKENS", classes="panel-header")
yield Container(
# Review box at the top so it's always visible
Static("Fill in address and amount below", id="review-box"),
Static("", id="fee-info"),
Static("", id="balance-info"),
Label("To Address:"),
Input(placeholder="Enter recipient address", id="to-address"),
Label("Amount (SOL):"),
Horizontal(
Input(placeholder="0.0", id="amount-input"),
Button("25%", id="btn-25"),
Button("50%", id="btn-50"),
Button("75%", id="btn-75"),
Button("MAX", id="btn-max"),
),
# Action buttons below inputs
Horizontal(
Button("Send", variant="success", id="btn-send"),
Button("Clear", id="btn-cancel"),
id="send-buttons"
),
# Confirmation step - hidden until Send is clicked
Container(
Static("", id="confirm-summary"),
Label("Wallet Password:"),
Input(placeholder="Enter password to sign", id="wallet-password", password=True),
Horizontal(
Button("Confirm Send", variant="error", id="btn-confirm"),
Button("Go Back", id="btn-back"),
),
id="confirm-container"
),
id="send-container"
)
def on_mount(self) -> None:
"""Hide confirm section on mount"""
self.query_one("#confirm-container").display = False
self.update_balance_info()
def watch_current_balance(self, balance: float) -> None:
self.update_balance_info()
def update_balance_info(self) -> None:
balance_info = self.query_one("#balance-info", Static)
balance_info.update(f"Available: {self.current_balance:.9f} SOL")
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "btn-25":
self.set_amount(self.current_balance * 0.25)
elif event.button.id == "btn-50":
self.set_amount(self.current_balance * 0.50)
elif event.button.id == "btn-75":
self.set_amount(self.current_balance * 0.75)
elif event.button.id == "btn-max":
self.set_amount(max(0, self.current_balance - 0.000005))
elif event.button.id == "btn-send":
self._show_confirm_step()
elif event.button.id == "btn-cancel":
self.clear_form()
elif event.button.id == "btn-confirm":
self.post_message(self.SendRequested())
elif event.button.id == "btn-back":
self._hide_confirm_step()
def _show_confirm_step(self) -> None:
"""Validate inputs then show password + confirm button"""
review = self.query_one("#review-box", Static)
to = self.query_one("#to-address", Input).value.strip()
amount_str = self.query_one("#amount-input", Input).value.strip()
if not to or not amount_str:
review.update("[red]Fill in address and amount first[/red]")
return
# Validate address format
if not self.app.wallet_manager.validate_address(to):
review.update("[red]Invalid recipient address[/red]")
return
try:
amount = float(amount_str)
except ValueError:
review.update("[red]Invalid amount[/red]")
return
if amount <= 0:
review.update("[red]Amount must be greater than 0[/red]")
return
# Fee-aware balance check
fee = 0.000005
if amount + fee > self.current_balance:
review.update("[red]Insufficient balance (amount + fee)[/red]")
return
# Show the confirmation section
to_short = f"{to[:6]}...{to[-6:]}" if len(to) > 12 else to
summary = self.query_one("#confirm-summary", Static)
summary.update(
f"[bold yellow]Confirm Transaction[/bold yellow]\n"
f"[dim]──────────────────────[/dim]\n"
f"Send [bold cyan]{amount:.6f} SOL[/bold cyan]\n"
f"To [cyan]{to_short}[/cyan]\n"
f"Fee [dim]{fee:.6f} SOL[/dim]"
)
self.query_one("#confirm-container").display = True
self.query_one("#wallet-password", Input).focus()
self._confirming = True
def _hide_confirm_step(self) -> None:
"""Go back to the input form"""
self.query_one("#confirm-container").display = False
self.query_one("#wallet-password", Input).value = ""
self._confirming = False
def set_amount(self, amount: float) -> None:
self.query_one("#amount-input", Input).value = f"{amount:.9f}"
self.update_review()
def on_input_changed(self, event: Input.Changed) -> None:
if event.input.id in ("to-address", "amount-input"):
self.update_review()
def update_review(self) -> None:
review = self.query_one("#review-box", Static)
fee_info = self.query_one("#fee-info", Static)
try:
to = self.query_one("#to-address", Input).value.strip()
amount_str = self.query_one("#amount-input", Input).value.strip()
amount = float(amount_str) if amount_str else 0.0
fee = 0.000005
fee_info.update(f"Fee: ~{fee:.6f} SOL")
if to and amount > 0:
to_short = f"{to[:6]}...{to[-6:]}" if len(to) > 12 else to
review.update(
f"[bold cyan]{amount:.6f} SOL[/bold cyan]"
f" [dim]→[/dim] [cyan]{to_short}[/cyan]"
)
else:
review.update("[dim]Fill in address and amount below[/dim]")
except (ValueError, TypeError):
review.update("[red]Invalid amount[/red]")
def clear_form(self) -> None:
self._hide_confirm_step()
self.query_one("#to-address", Input).value = ""
self.query_one("#amount-input", Input).value = ""
self.query_one("#review-box", Static).update("[dim]Fill in address and amount below[/dim]")
self.query_one("#fee-info", Static).update("")
class SendRequested(Message):
"""User confirmed send - app handles signing + broadcast"""
pass
class LiveBottomBar(Static):
"""Bottom shortcuts bar"""
def render(self) -> Text:
text = Text()
text.append("TAB", style="bold #38bdf8")
text.append(" Navigate ", style="#64748b")
text.append("↑↓", style="bold #f59e0b")
text.append(" Select ", style="#64748b")
text.append("r", style="bold #4ade80")
text.append(" Refresh ", style="#64748b")
text.append("c", style="bold #a78bfa")
text.append(" Copy address ", style="#64748b")
text.append("x", style="bold #22c55e")
text.append(" Copy tx link ", style="#64748b")
text.append("u", style="bold #f59e0b")
text.append(" Unmount ", style="#64748b")
text.append("q", style="bold #ef4444")
text.append(" Quit", style="#64748b")
return text
class ColdstarLiveWallet(App):
"""Live Coldstar Wallet TUI"""
CSS = """
/* ── COLDSTAR THEME ── navy background, ice-blue accents, white text ── */
Screen {
background: #0a0e1a;
}
/* Top/bottom bars: slightly lighter navy strip */
LiveStatusBar, LiveInfoBar, LiveBottomBar {
dock: top;
height: 1;
background: #111827;
color: #e2e8f0;
padding: 0 1;
}
LiveBottomBar {
dock: bottom;
}
/* Panel containers */
LivePortfolioPanel, LiveSendPanel {
width: 1fr;
border: solid #1e3a5f;
background: #0d1526;
padding: 0;
margin: 0 1;
}
#left-column, #centre-column, #right-column {
width: 1fr;
height: 100%;
margin: 0 1;
}
LivePortfolioPanel {
height: 1fr;
}
TokenDetailsPanel, TokenSecurityPanel {
height: 1fr;
border: solid #1e3a5f;
background: #0d1526;
padding: 0;
}
TransactionHistoryPanel {
height: 1fr;
border: solid #1e3a5f;
background: #0d1526;
padding: 0;
margin-top: 1;
}
LiveSendPanel {
height: 1fr;
}
DevicePanel {
height: 5;
border: solid #1e3a5f;
background: #0d1526;
padding: 0;
margin: 0 1;
}
NetworkPanel {
height: 7;
border: solid #1e3a5f;
background: #0d1526;
padding: 0;
margin: 0 1;
}
#network-container {
padding: 1;
}
#airdrop-status {
margin: 1 0 0 0;
}
#device-list, #device-hint {
padding: 0 1;
}
ConfirmUnmountScreen {
align: center middle;
background: rgba(0, 0, 0, 0.6);
}
#confirm-container {
width: 50;
border: solid #f59e0b;
background: #0d1526;
padding: 1 2;
}
#confirm-text {
margin-bottom: 1;
}
TokenSecurityPanel {
margin-top: 1;
}
/* Focus: bright ice-blue border, subtle glow */
LivePortfolioPanel:focus {
border: heavy #38bdf8;
background: #0f1f35;
}
LivePortfolioPanel:focus-within {
border: heavy #38bdf8;
background: #0f1f35;
}
LiveSendPanel:focus-within {
border: heavy #38bdf8;
background: #0f1f35;
}
TokenDetailsPanel:focus-within {
border: heavy #38bdf8;
background: #0f1f35;
}
TransactionHistoryPanel:focus-within {
border: heavy #38bdf8;
background: #0f1f35;
}
TokenSecurityPanel:focus-within {
border: heavy #38bdf8;
background: #0f1f35;
}
/* Panel header bars — styled title strip */
.panel-header {
background: #1e3a5f;
color: #7dd3fc;
text-style: bold;
padding: 0 1;
height: 1;
dock: top;
}
/* Scrollable inner content gets padding */
ScrollableContainer {
padding: 0 1;
}
ScrollableContainer:focus-within {
border: none;
}
#send-container {
height: 1fr;
padding: 0;
align: left top;
}
#review-box, #fee-info, #balance-info {
height: 1;
margin-bottom: 0;
}
#send-buttons {
margin: 0 0 0 0;
}
/* Labels inside send form */
Label {
color: #7dd3fc;
text-style: bold;