starktop 0.8.1

A TUI block explorer for the Starknet blockchain
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
//! WebSocket subscription manager for real-time Starknet data.
//!
//! Maintains a single WebSocket connection that can hold multiple concurrent
//! subscriptions:
//!   - `starknet_subscribeNewHeads` — always active, replaces polling
//!   - `starknet_subscribeEvents` — per address, added when viewing an address
//!     (events the address *emits*, via the `from_address` filter)
//!   - `starknet_subscribeNewTransactions` — per account sender address
//!   - `starknet_subscribeEvents` (keyed `Transfer`) — per address, two extra
//!     subscriptions matching ERC-20 `Transfer` events where the address is the
//!     `to` or `from` key. This is the only way to see activity for a contract
//!     that moves tokens but emits no events of its own (the token contract is
//!     the emitter), so its `from_address` subscription stays silent.
//!
//! Uses starknet-rust types for serialization of subscribe requests and
//! deserialization of notification payloads. Raw connection management uses
//! tokio-tungstenite (starknet-rust has no WebSocket transport).
//!
//! The public entry point is [`spawn_ws_subscriber`], which returns a
//! [`WsSubscriptionManager`] for dynamically adding/removing subscriptions.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use futures::{SinkExt, StreamExt};
use serde::Deserialize;
use serde_json::Value;
use starknet::core::types::{
    AddressFilter, ConfirmedBlockId, EmittedEventWithFinality, Felt, L2TransactionFinalityStatus,
    L2TransactionStatus, SubscriptionId, Transaction,
    requests::{
        SubscribeEventsRequest, SubscribeNewHeadsRequest, SubscribeNewTransactionsRequest,
        UnsubscribeRequest,
    },
};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use tracing::{debug, error, info, warn};

use crate::app::actions::{Action, Source};
use crate::app::state::SourceStatus;
use crate::data::DataSource;
use crate::data::types::{AddressTxSummary, SnEvent};
use crate::utils::felt_to_u64;

/// Maximum reconnect delay (capped exponential backoff).
const MAX_RECONNECT_DELAY: Duration = Duration::from_secs(30);
/// Initial reconnect delay.
const INITIAL_RECONNECT_DELAY: Duration = Duration::from_secs(1);
/// Give up after this many consecutive connection failures.
const MAX_CONSECUTIVE_FAILURES: u32 = 5;
/// Timeout waiting for subscription confirmation.
const SUBSCRIBE_TIMEOUT: Duration = Duration::from_secs(10);
/// Heads and events arrive on separate subscriptions, so replay a few blocks
/// before the last head seen.
const RESUME_OVERLAP_BLOCKS: u64 = 5;
/// Stay inside the node's replay window (the spec caps it at 1024 blocks).
const MAX_RESUME_BLOCKS: u64 = 1000;

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Identifies what an active subscription is tracking.
#[derive(Debug, Clone)]
enum SubscriptionKind {
    NewHeads,
    Events {
        address: Felt,
    },
    Transactions {
        address: Felt,
    },
    /// ERC-20 `Transfer` events keyed by the viewed address (as `to` or
    /// `from`). Emitted by the token contract, not the viewed address, so
    /// these surface token flows a silent contract would otherwise hide.
    Transfers {
        address: Felt,
    },
}

/// Command sent to the WS task to manage subscriptions.
#[derive(Debug)]
pub enum WsCommand {
    /// Subscribe to events emitted by `address` (contract view).
    SubscribeEvents { address: Felt },
    /// Subscribe to new transactions sent by `address` (account view).
    SubscribeTransactions { address: Felt },
    /// Subscribe to ERC-20 `Transfer` events where `address` is the `to` or
    /// `from` key — token flows in/out of a (possibly event-silent) address.
    SubscribeTransfers { address: Felt },
    /// Remove all subscriptions for `address`.
    UnsubscribeAddress { address: Felt },
}

/// Handle for controlling the WS subscription manager from the UI thread.
///
/// `Send + Sync` because the inner `mpsc::UnboundedSender` is.
pub struct WsSubscriptionManager {
    cmd_tx: mpsc::UnboundedSender<WsCommand>,
}

impl WsSubscriptionManager {
    /// Subscribe to events emitted by `address` (use for contracts).
    pub fn subscribe_events(&self, address: Felt) {
        let _ = self.cmd_tx.send(WsCommand::SubscribeEvents { address });
    }

    /// Subscribe to new transactions sent from `address` (use for accounts).
    pub fn subscribe_transactions(&self, address: Felt) {
        let _ = self
            .cmd_tx
            .send(WsCommand::SubscribeTransactions { address });
    }

    /// Subscribe to events, transactions, and token transfers for `address`.
    /// Safe to call regardless of address type — the server will send
    /// whichever notifications match. The transfers subscription is what makes
    /// a token-moving but event-silent contract show live activity.
    pub fn subscribe_address(&self, address: Felt) {
        let _ = self.cmd_tx.send(WsCommand::SubscribeEvents { address });
        let _ = self
            .cmd_tx
            .send(WsCommand::SubscribeTransactions { address });
        let _ = self.cmd_tx.send(WsCommand::SubscribeTransfers { address });
    }

    /// Stop all subscriptions for `address`.
    pub fn unsubscribe_address(&self, address: Felt) {
        let _ = self.cmd_tx.send(WsCommand::UnsubscribeAddress { address });
    }
}

/// What a reconnect re-subscribes, and from which block. Outlives connections.
#[derive(Default)]
struct Resume {
    addresses: Vec<Felt>,
    last_head: Option<u64>,
}

impl Resume {
    fn add(&mut self, address: Felt) {
        if !self.addresses.contains(&address) {
            self.addresses.push(address);
        }
    }

    fn remove(&mut self, address: Felt) {
        self.addresses.retain(|a| *a != address);
    }

    /// Block to replay address events from after a reconnect; `None` means
    /// the tip. `tip` clamps the replay to the node's window.
    fn replay_from(&self, tip: Option<u64>) -> Option<u64> {
        let from = self.last_head?.saturating_sub(RESUME_OVERLAP_BLOCKS);
        Some(match tip {
            Some(tip) => from.max(tip.saturating_sub(MAX_RESUME_BLOCKS)),
            None => from,
        })
    }
}

/// Spawns the WebSocket subscription task.
///
/// Returns a join handle (runs indefinitely with auto-reconnect) and a
/// [`WsSubscriptionManager`] for dynamically adding/removing subscriptions.
pub fn spawn_ws_subscriber(
    ws_url: String,
    data_source: Arc<dyn DataSource>,
    response_tx: mpsc::UnboundedSender<Action>,
    head_block: Arc<super::HeadTracker>,
) -> (tokio::task::JoinHandle<()>, WsSubscriptionManager) {
    let (cmd_tx, cmd_rx) = mpsc::unbounded_channel::<WsCommand>();
    let manager = WsSubscriptionManager { cmd_tx };
    let (block_tx, block_rx) = mpsc::unbounded_channel::<Value>();
    tokio::spawn(fetch_new_blocks(
        block_rx,
        Arc::clone(&data_source),
        response_tx.clone(),
    ));

    let handle = tokio::spawn(async move {
        let mut delay = INITIAL_RECONNECT_DELAY;
        let mut consecutive_failures: u32 = 0;
        let mut cmd_rx = cmd_rx;
        let mut resume = Resume::default();

        loop {
            info!(url = %ws_url, "Connecting to WebSocket");
            let _ = response_tx.send(ws_source_update(SourceStatus::Configured));

            match connect_and_run(
                &ws_url,
                &data_source,
                &response_tx,
                &mut cmd_rx,
                &mut resume,
                &head_block,
                &block_tx,
            )
            .await
            {
                Ok(true) => {
                    info!("WsSubscriptionManager dropped, stopping WS task");
                    return;
                }
                Ok(false) => {
                    info!("WebSocket stream ended cleanly");
                    delay = INITIAL_RECONNECT_DELAY;
                    consecutive_failures = 0;
                }
                Err(e) => {
                    consecutive_failures += 1;
                    error!(error = %e, attempt = consecutive_failures, "WebSocket connection failed");
                    let _ = response_tx
                        .send(ws_source_update(SourceStatus::ConnectError(e.to_string())));

                    if consecutive_failures >= MAX_CONSECUTIVE_FAILURES {
                        error!(
                            "WebSocket gave up after {consecutive_failures} consecutive failures"
                        );
                        return;
                    }
                }
            }

            warn!(
                delay_secs = delay.as_secs(),
                "Reconnecting WebSocket after delay"
            );
            tokio::time::sleep(delay).await;
            delay = (delay * 2).min(MAX_RECONNECT_DELAY);
        }
    });

    (handle, manager)
}

fn ws_source_update(status: SourceStatus) -> Action {
    Action::SourceUpdate {
        source: Source::Ws,
        status,
    }
}

// ---------------------------------------------------------------------------
// Internal: connection state
// ---------------------------------------------------------------------------

/// State tracked for the lifetime of a single WS connection.
struct ConnectionState {
    /// Maps subscription ID string → what it tracks.
    subscriptions: HashMap<String, SubscriptionKind>,
    /// Maps address → list of subscription ID strings (for cleanup).
    address_subs: HashMap<Felt, Vec<String>>,
    /// Pending subscribe requests: JSON-RPC request id → kind being subscribed to.
    pending: HashMap<u64, SubscriptionKind>,
    /// Same request from the tip, re-sent if the node rejects a replay block.
    fallbacks: HashMap<u64, SubscribeEventsRequest>,
    /// Highest new-heads block received on this connection.
    last_head: Option<u64>,
    /// Next JSON-RPC request ID to use.
    next_id: u64,
}

impl ConnectionState {
    fn new() -> Self {
        Self {
            subscriptions: HashMap::new(),
            address_subs: HashMap::new(),
            pending: HashMap::new(),
            fallbacks: HashMap::new(),
            last_head: None,
            next_id: 2, // 1 is used for the initial NewHeads subscription
        }
    }

    fn next_id(&mut self) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    fn confirm_subscribe(&mut self, request_id: u64, sub_id: String) {
        if let Some(kind) = self.pending.remove(&request_id) {
            // Track address → sub_id mapping for cleanup
            if let Some(addr) = kind_address(&kind) {
                self.address_subs
                    .entry(addr)
                    .or_default()
                    .push(sub_id.clone());
            }
            self.subscriptions.insert(sub_id, kind);
        }
    }

    fn remove_address(&mut self, address: Felt) -> Vec<String> {
        self.address_subs
            .remove(&address)
            .unwrap_or_default()
            .into_iter()
            .inspect(|id| {
                self.subscriptions.remove(id);
            })
            .collect()
    }

    fn subscription_kind(&self, sub_id: &str) -> Option<&SubscriptionKind> {
        self.subscriptions.get(sub_id)
    }
}

fn kind_address(kind: &SubscriptionKind) -> Option<Felt> {
    match kind {
        SubscriptionKind::Events { address }
        | SubscriptionKind::Transactions { address }
        | SubscriptionKind::Transfers { address } => Some(*address),
        SubscriptionKind::NewHeads => None,
    }
}

// ---------------------------------------------------------------------------
// Raw JSON-RPC envelope types (minimal — avoids strict starknet-rust wrappers)
// ---------------------------------------------------------------------------

/// Generic JSON-RPC message: covers both responses (has `id`) and notifications (has `method`).
#[derive(Debug, Deserialize)]
struct RawMessage {
    #[allow(dead_code)]
    jsonrpc: Option<String>,
    id: Option<Value>,
    method: Option<String>,
    params: Option<RawParams>,
    result: Option<Value>,
    error: Option<JsonRpcError>,
}

/// Notification params: subscription ID + pushed result.
#[derive(Debug, Deserialize)]
struct RawParams {
    /// Spec uses `subscription_id`; Pathfinder uses `subscription`.
    #[serde(alias = "subscription", alias = "subscription_id")]
    subscription_id: Value,
    result: Value,
}

#[derive(Debug, Deserialize)]
struct JsonRpcError {
    #[allow(dead_code)]
    code: i64,
    message: String,
}

// ---------------------------------------------------------------------------
// Internal: connect, subscribe, and run the select! loop
// ---------------------------------------------------------------------------

/// Runs one connection until it drops. `Ok(true)` means the manager was
/// dropped (app shutdown) and the task should stop.
async fn connect_and_run(
    ws_url: &str,
    data_source: &Arc<dyn DataSource>,
    response_tx: &mpsc::UnboundedSender<Action>,
    cmd_rx: &mut mpsc::UnboundedReceiver<WsCommand>,
    resume: &mut Resume,
    head_block: &Arc<super::HeadTracker>,
    block_tx: &mpsc::UnboundedSender<Value>,
) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
    let (ws_stream, _) = tokio_tungstenite::connect_async(ws_url).await?;
    let (mut write, mut read) = ws_stream.split();

    let mut state = ConnectionState::new();

    // Always subscribe to new block headers first (id = 1)
    let heads_msg = build_subscribe_msg(
        1,
        "starknet_subscribeNewHeads",
        serde_json::to_value(SubscribeNewHeadsRequest { block_id: None })?,
    );
    write.send(Message::Text(heads_msg.into())).await?;
    state.pending.insert(1, SubscriptionKind::NewHeads);
    debug!("Sent starknet_subscribeNewHeads");

    // Re-subscribe the previous connection's addresses, replaying the blocks
    // the drop skipped so their events aren't lost.
    let (tip, age) = head_block.read();
    let from_block = resume.replay_from((tip > 0 && age < 300).then_some(tip));
    if !resume.addresses.is_empty() {
        info!(
            ?from_block,
            addresses = resume.addresses.len(),
            "Re-subscribing address streams"
        );
    }
    for &address in &resume.addresses {
        for cmd in [
            WsCommand::SubscribeEvents { address },
            WsCommand::SubscribeTransactions { address },
            WsCommand::SubscribeTransfers { address },
        ] {
            send_subscribe_cmd(&mut write, &mut state, &cmd, from_block).await?;
        }
    }

    let _ = response_tx.send(ws_source_update(SourceStatus::Live));

    // Main event loop: multiplex WS messages and manager commands
    loop {
        tokio::select! {
            // Incoming WS message
            msg = read.next() => {
                match msg {
                    Some(Ok(Message::Text(text))) => {
                        handle_message(&text, &mut write, &mut state, data_source, response_tx, head_block, block_tx).await;
                        if state.last_head > resume.last_head {
                            resume.last_head = state.last_head;
                        }
                    }
                    Some(Ok(Message::Ping(data))) => {
                        let _ = write.send(Message::Pong(data)).await;
                    }
                    Some(Ok(Message::Close(_))) => {
                        info!("WebSocket server sent close frame");
                        break;
                    }
                    Some(Ok(_)) => {} // Binary, Pong, etc.
                    Some(Err(e)) => {
                        return Err(format!("WS read error: {e}").into());
                    }
                    None => {
                        info!("WebSocket stream closed");
                        break;
                    }
                }
            }

            // Command from WsSubscriptionManager
            cmd = cmd_rx.recv() => {
                match cmd {
                    Some(WsCommand::UnsubscribeAddress { address }) => {
                        resume.remove(address);
                        let ids = state.remove_address(address);
                        for sub_id in ids {
                            let req_id = state.next_id();
                            let msg = build_subscribe_msg(
                                req_id,
                                "starknet_unsubscribe",
                                serde_json::to_value(UnsubscribeRequest {
                                    subscription_id: SubscriptionId(sub_id.clone()),
                                })?,
                            );
                            if write.send(Message::Text(msg.into())).await.is_err() {
                                break;
                            }
                            debug!(sub_id, "Sent unsubscribe");
                        }
                    }
                    Some(cmd) => {
                        if let Some(address) = command_address(&cmd) {
                            resume.add(address);
                        }
                        if let Err(e) = send_subscribe_cmd(&mut write, &mut state, &cmd, None).await {
                            warn!(error = %e, "Failed to send subscribe command");
                        }
                    }
                    None => return Ok(true),
                }
            }
        }
    }

    Ok(false)
}

fn command_address(cmd: &WsCommand) -> Option<Felt> {
    match cmd {
        WsCommand::SubscribeEvents { address }
        | WsCommand::SubscribeTransactions { address }
        | WsCommand::SubscribeTransfers { address } => Some(*address),
        WsCommand::UnsubscribeAddress { .. } => None,
    }
}

/// Build a JSON-RPC request string.
fn build_subscribe_msg(id: u64, method: &str, params: Value) -> String {
    serde_json::json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": method,
        "params": params,
    })
    .to_string()
}

/// Send a subscribe command over the WS write half and record it in state.
/// `from_block` replays event subscriptions from that block.
async fn send_subscribe_cmd(
    write: &mut (impl SinkExt<Message, Error = tokio_tungstenite::tungstenite::Error> + Unpin),
    state: &mut ConnectionState,
    cmd: &WsCommand,
    from_block: Option<u64>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let block_id = from_block.map(ConfirmedBlockId::Number);
    match cmd {
        WsCommand::SubscribeEvents { address } => {
            let req = SubscribeEventsRequest {
                from_address: Some(AddressFilter::Single(*address)),
                keys: None,
                block_id,
                finality_status: Some(L2TransactionFinalityStatus::AcceptedOnL2),
            };
            send_events_subscription(
                write,
                state,
                SubscriptionKind::Events { address: *address },
                req,
            )
            .await?;
            debug!(address = %format!("{:#x}", address), ?from_block, "Sent starknet_subscribeEvents");
        }
        WsCommand::SubscribeTransactions { address } => {
            let id = state.next_id();
            let req = SubscribeNewTransactionsRequest {
                sender_address: Some(vec![*address]),
                finality_status: Some(vec![L2TransactionStatus::AcceptedOnL2]),
                tags: None,
            };
            let msg = build_subscribe_msg(
                id,
                "starknet_subscribeNewTransactions",
                serde_json::to_value(req)?,
            );
            write.send(Message::Text(msg.into())).await?;
            state
                .pending
                .insert(id, SubscriptionKind::Transactions { address: *address });
            debug!(address = %format!("{:#x}", address), "Sent starknet_subscribeNewTransactions");
        }
        WsCommand::SubscribeTransfers { address } => {
            // Two keyed subscriptions: ERC-20 `Transfer` events where the
            // address is the `to` key (incoming) or the `from` key (outgoing).
            // `from_address` is left unset so the filter matches transfers
            // emitted by *any* token contract. Both are tracked under the same
            // `Transfers` kind/address so they re-subscribe and clean up
            // together; the shared `handle_event` path dedups by
            // `(tx_hash, event_index)`, so a tx with both legs still yields one
            // Calls row and two distinct Events rows.
            for keys in transfer_key_filters(*address) {
                let req = SubscribeEventsRequest {
                    from_address: None,
                    keys: Some(keys),
                    block_id,
                    finality_status: Some(L2TransactionFinalityStatus::AcceptedOnL2),
                };
                send_events_subscription(
                    write,
                    state,
                    SubscriptionKind::Transfers { address: *address },
                    req,
                )
                .await?;
            }
            debug!(address = %format!("{:#x}", address), ?from_block, "Sent keyed Transfer subscriptions (in+out)");
        }
        WsCommand::UnsubscribeAddress { .. } => {
            // Handled at the call site with access to state.remove_address()
        }
    }
    Ok(())
}

/// Send one `starknet_subscribeEvents`. A replaying request keeps a tip-only
/// copy so a rejected replay (e.g. too many blocks back) still subscribes.
async fn send_events_subscription(
    write: &mut (impl SinkExt<Message, Error = tokio_tungstenite::tungstenite::Error> + Unpin),
    state: &mut ConnectionState,
    kind: SubscriptionKind,
    req: SubscribeEventsRequest,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let id = state.next_id();
    let msg = build_subscribe_msg(id, "starknet_subscribeEvents", serde_json::to_value(&req)?);
    write.send(Message::Text(msg.into())).await?;
    state.pending.insert(id, kind);
    if req.block_id.is_some() {
        state.fallbacks.insert(
            id,
            SubscribeEventsRequest {
                block_id: None,
                ..req
            },
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Message handling: route by subscription ID
// ---------------------------------------------------------------------------

async fn handle_message(
    text: &str,
    write: &mut (impl SinkExt<Message, Error = tokio_tungstenite::tungstenite::Error> + Unpin),
    state: &mut ConnectionState,
    data_source: &Arc<dyn DataSource>,
    response_tx: &mpsc::UnboundedSender<Action>,
    head_block: &Arc<super::HeadTracker>,
    block_tx: &mpsc::UnboundedSender<Value>,
) {
    let raw: RawMessage = match serde_json::from_str(text) {
        Ok(m) => m,
        Err(e) => {
            warn!(error = %e, "Failed to parse WS message");
            return;
        }
    };

    // Handle responses to our subscribe/unsubscribe requests
    if let Some(id_val) = &raw.id {
        let req_id = id_val.as_u64().unwrap_or(0);
        if let Some(err) = &raw.error {
            let kind = state.pending.remove(&req_id);
            if let (Some(kind), Some(req)) = (kind, state.fallbacks.remove(&req_id)) {
                info!(req_id, error = %err.message, "Event replay rejected; subscribing from the tip");
                if let Err(e) = send_events_subscription(write, state, kind, req).await {
                    warn!(error = %e, "Failed to re-send event subscription");
                }
                return;
            }
            warn!(req_id, error = %err.message, "Subscribe/unsubscribe failed");
            return;
        }
        if let Some(result) = &raw.result {
            state.fallbacks.remove(&req_id);
            // Subscription confirmation: result is the subscription ID
            if let Ok(sub_id) = serde_json::from_value::<SubscriptionId>(result.clone()) {
                debug!(req_id, sub_id = %sub_id.0, "Subscription confirmed");
                state.confirm_subscribe(req_id, sub_id.0);
            }
            return;
        }
    }

    // Handle push notifications
    if let Some(method) = &raw.method
        && !method.starts_with("starknet_subscription")
    {
        debug!(method, "Ignoring non-subscription notification");
        return;
    }

    let params = match raw.params {
        Some(p) => p,
        None => return,
    };

    // Extract subscription ID as a canonical string (handles string or integer)
    let sub_id_str = match &params.subscription_id {
        Value::String(s) => s.clone(),
        Value::Number(n) => n.to_string(),
        other => {
            warn!(value = ?other, "Unexpected subscription_id type");
            return;
        }
    };

    let kind = match state.subscription_kind(&sub_id_str) {
        Some(k) => k.clone(),
        None => {
            // Unknown subscription ID — may be a race with confirmation
            debug!(
                sub_id = sub_id_str,
                "Notification for unknown subscription, ignoring"
            );
            return;
        }
    };

    match kind {
        SubscriptionKind::NewHeads => {
            if let Some(n) = handle_new_head(params.result, head_block, block_tx) {
                state.last_head = state.last_head.max(Some(n));
            }
        }
        SubscriptionKind::Events { address } => {
            handle_event(&params.result, address, data_source, response_tx);
        }
        SubscriptionKind::Transfers { address } => {
            // Same handler as `Events`: the Transfer notification has the
            // identical `EmittedEventWithFinality` shape. Routing it through
            // `handle_event` reuses the cache merge + single `AddressWsEvent`
            // broadcast, whose reducer dedups Calls by `tx_hash` and Events by
            // `(tx_hash, event_index)`. The token's `Transfer` is stored under
            // the viewed address so it surfaces in that address's tabs.
            handle_event(&params.result, address, data_source, response_tx);
        }
        SubscriptionKind::Transactions { address } => {
            handle_new_transaction(&params.result, address, response_tx);
        }
    }

    let _ = write; // suppress unused warning
}

// ---------------------------------------------------------------------------
// Per-notification-type handlers
// ---------------------------------------------------------------------------

/// Publish the head and queue its block fetch. Returns the block number.
fn handle_new_head(
    result: Value,
    head_block: &Arc<super::HeadTracker>,
    block_tx: &mpsc::UnboundedSender<Value>,
) -> Option<u64> {
    let Some(block_number) = result["block_number"].as_u64() else {
        warn!("NewHeads notification missing block_number: {result}");
        return None;
    };

    // Publish the head to shared state so other network-task sub-paths can
    // read it synchronously without an RPC round trip. The tracker also
    // records the timestamp so stale-detection works after a disconnect.
    head_block.update(block_number);

    info!(block_number, "New block header via WebSocket");
    let _ = block_tx.send(result);
    Some(block_number)
}

/// Fetch each new head's full block in arrival order, off the WS read loop:
/// a reader stalled on RPC gets its connection dropped by the node.
async fn fetch_new_blocks(
    mut block_rx: mpsc::UnboundedReceiver<Value>,
    data_source: Arc<dyn DataSource>,
    response_tx: mpsc::UnboundedSender<Action>,
) {
    while let Some(raw) = block_rx.recv().await {
        let Some(block_number) = raw["block_number"].as_u64() else {
            continue;
        };
        // WS header doesn't include tx data
        match data_source.get_block(block_number).await {
            Ok(block) => {
                let _ = response_tx.send(Action::NewBlock(block));
            }
            Err(e) => {
                // Fallback: build a minimal block from the notification fields
                warn!(block_number, error = %e, "Failed to fetch full block via RPC, using WS header");
                if let Some(block) = block_from_raw(&raw) {
                    let _ = response_tx.send(Action::NewBlock(block));
                }
            }
        }
    }
}

fn handle_event(
    result: &Value,
    address: Felt,
    data_source: &Arc<dyn DataSource>,
    response_tx: &mpsc::UnboundedSender<Action>,
) {
    let event: EmittedEventWithFinality = match serde_json::from_value(result.clone()) {
        Ok(e) => e,
        Err(e) => {
            warn!(error = %e, "Failed to deserialize event notification");
            return;
        }
    };

    let tx_hash = event.emitted_event.transaction_hash;
    let block_number = event.emitted_event.block_number.unwrap_or(0);
    // Carry the real `event_index` from the notification. This is essential
    // for the keyed Transfer subscriptions: a single tx can emit several
    // Transfers involving the viewed address (token in + token out, or
    // multi-hop). The Events-tab reducer dedups by `(tx_hash, event_index)`
    // and the cache merge by `(tx_hash, block_number, event_index)` — in both,
    // `event_index` is the field that distinguishes the legs. Hardcoding 0
    // here would collapse those distinct transfers into one (dropping legs)
    // and mis-merge events that arrive from overlapping subscriptions.
    // `EmittedEvent.event_index` is present on the subscription payload
    // (starknet-rust 0.19+).
    let sn_event = SnEvent {
        from_address: event.emitted_event.from_address,
        keys: event.emitted_event.keys.clone(),
        data: event.emitted_event.data.clone(),
        transaction_hash: tx_hash,
        block_number,
        event_index: event.emitted_event.event_index,
    };

    debug!(
        address = %format!("{:#x}", address),
        tx = %format!("{:#x}", tx_hash),
        block = block_number,
        "Received event via WS → cache + single broadcast"
    );

    // Persist off the read loop: a slow reader makes the node drop the connection.
    data_source.append_address_events(&address, std::slice::from_ref(&sn_event));

    // Single broadcast — the reducer fans out to Calls, MetaTxs classifier,
    // and Events tab. Avoids multiple per-tab streaming actions diverging.
    let _ = response_tx.send(Action::AddressWsEvent {
        address,
        event: sn_event,
    });
}

/// Cached `TRANSACTION_EXECUTED` selector as `Felt` (parsed once per process).
///
/// pub(crate) so the `AddressWsEvent` reducer can compare the first key of a
/// live event without re-parsing the hex string on every WS notification.
pub(crate) fn tx_executed_selector() -> Felt {
    use std::sync::OnceLock;
    static SELECTOR: OnceLock<Felt> = OnceLock::new();
    *SELECTOR.get_or_init(|| {
        Felt::from_hex(crate::data::pathfinder::TRANSACTION_EXECUTED_SELECTOR)
            .expect("TRANSACTION_EXECUTED_SELECTOR is a valid felt")
    })
}

/// Cached ERC-20 `Transfer` selector as `Felt` (parsed once per process).
/// Used to build the keyed `subscribeEvents` filter for the transfers
/// subscription.
fn transfer_selector() -> Felt {
    use std::sync::OnceLock;
    static SELECTOR: OnceLock<Felt> = OnceLock::new();
    *SELECTOR.get_or_init(|| {
        Felt::from_hex(crate::data::pathfinder::TRANSFER_SELECTOR)
            .expect("TRANSFER_SELECTOR is a valid felt")
    })
}

/// Build the two `subscribeEvents` keys-filters for `address`'s transfers
/// subscription: `[to == address, from == address]`. ERC-20 `Transfer` keys
/// are `[selector, from, to]`; an empty inner vec is a wildcard for that key
/// position. Both filters are written as explicit 3-slot lists matching that
/// layout — the incoming filter pins slot 2 (`to`) with slot 1 (`from`)
/// wildcarded, the outgoing filter pins slot 1 (`from`) with slot 2 (`to`)
/// wildcarded — rather than relying on the server treating a missing trailing
/// slot as a wildcard.
pub(crate) fn transfer_key_filters(address: Felt) -> [Vec<Vec<Felt>>; 2] {
    let sel = transfer_selector();
    [
        vec![vec![sel], vec![], vec![address]], // to == address, any from
        vec![vec![sel], vec![address], vec![]], // from == address, any to
    ]
}

fn handle_new_transaction(
    result: &Value,
    address: Felt,
    response_tx: &mpsc::UnboundedSender<Action>,
) {
    // Try to deserialize as a starknet-rust Transaction
    let summary = if let Ok(tx) = serde_json::from_value::<Transaction>(result.clone()) {
        tx_to_summary(&tx)
    } else {
        // Fall back to extracting from JSON directly
        tx_from_raw(result)
    };

    let summary = match summary {
        Some(s) => s,
        None => {
            debug!("Could not build summary from transaction notification");
            return;
        }
    };

    debug!(
        address = %format!("{:#x}", address),
        tx = %format!("{:#x}", summary.hash),
        "Received transaction via WS"
    );

    let _ = response_tx.send(Action::AddressTxsStreamed {
        address,
        source: Source::Ws,
        tx_summaries: vec![summary],
        complete: false,
    });
}

// ---------------------------------------------------------------------------
// Conversion helpers
// ---------------------------------------------------------------------------

/// Build an `AddressTxSummary` from a starknet-rust `Transaction`.
fn tx_to_summary(tx: &Transaction) -> Option<AddressTxSummary> {
    let (hash, nonce, tx_type, sender) = match tx {
        Transaction::Invoke(invoke) => match invoke {
            starknet::core::types::InvokeTransaction::V0(t) => {
                (t.transaction_hash, 0u64, "INVOKE", None::<Felt>)
            }
            starknet::core::types::InvokeTransaction::V1(t) => (
                t.transaction_hash,
                felt_to_u64(&t.nonce),
                "INVOKE",
                Some(t.sender_address),
            ),
            starknet::core::types::InvokeTransaction::V3(t) => (
                t.transaction_hash,
                felt_to_u64(&t.nonce),
                "INVOKE",
                Some(t.sender_address),
            ),
        },
        Transaction::Declare(declare) => match declare {
            starknet::core::types::DeclareTransaction::V0(t) => {
                (t.transaction_hash, 0u64, "DECLARE", Some(t.sender_address))
            }
            starknet::core::types::DeclareTransaction::V1(t) => (
                t.transaction_hash,
                felt_to_u64(&t.nonce),
                "DECLARE",
                Some(t.sender_address),
            ),
            starknet::core::types::DeclareTransaction::V2(t) => (
                t.transaction_hash,
                felt_to_u64(&t.nonce),
                "DECLARE",
                Some(t.sender_address),
            ),
            starknet::core::types::DeclareTransaction::V3(t) => (
                t.transaction_hash,
                felt_to_u64(&t.nonce),
                "DECLARE",
                Some(t.sender_address),
            ),
        },
        Transaction::DeployAccount(deploy_acc) => match deploy_acc {
            starknet::core::types::DeployAccountTransaction::V1(t) => {
                (t.transaction_hash, 0u64, "DEPLOY_ACCOUNT", None)
            }
            starknet::core::types::DeployAccountTransaction::V3(t) => {
                (t.transaction_hash, 0u64, "DEPLOY_ACCOUNT", None)
            }
        },
        Transaction::Deploy(t) => (t.transaction_hash, 0u64, "DEPLOY", None),
        Transaction::L1Handler(t) => (t.transaction_hash, 0u64, "L1_HANDLER", None),
    };

    Some(AddressTxSummary {
        hash,
        nonce,
        block_number: 0, // Not in pending tx notification
        timestamp: 0,
        endpoint_names: String::new(),
        total_fee_fri: 0,
        tip: 0,
        tx_type: tx_type.to_string(),
        status: "?".to_string(), // Pending — enrichment will update
        sender,
        called_contracts: Vec::new(),
    })
}

/// Extract minimal AddressTxSummary from raw JSON value (fallback).
fn tx_from_raw(v: &Value) -> Option<AddressTxSummary> {
    let hash_str = v["transaction_hash"].as_str()?;
    let hash = Felt::from_hex(hash_str).ok()?;
    let nonce = v["nonce"]
        .as_str()
        .and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok())
        .unwrap_or(0);
    let tx_type = v["type"].as_str().unwrap_or("INVOKE").to_string();
    let sender = v["sender_address"]
        .as_str()
        .and_then(|s| Felt::from_hex(s).ok());

    Some(AddressTxSummary {
        hash,
        nonce,
        block_number: 0,
        timestamp: 0,
        endpoint_names: String::new(),
        total_fee_fri: 0,
        tip: 0,
        tx_type,
        status: "?".to_string(),
        sender,
        called_contracts: Vec::new(),
    })
}

/// Build a minimal `SnBlock` from a raw WS notification result value.
fn block_from_raw(v: &Value) -> Option<crate::data::types::SnBlock> {
    let block_number = v["block_number"].as_u64()?;
    let block_hash = Felt::from_hex(v["block_hash"].as_str()?).ok()?;
    let parent_hash = Felt::from_hex(v["parent_hash"].as_str().unwrap_or("0x0")).ok()?;
    let timestamp = v["timestamp"].as_u64().unwrap_or(0);
    let sequencer_address =
        Felt::from_hex(v["sequencer_address"].as_str().unwrap_or("0x0")).ok()?;
    let starknet_version = v["starknet_version"].as_str().unwrap_or("").to_string();
    let transaction_count = v["transaction_count"].as_u64().unwrap_or(0) as usize;

    let gas_fri = |field: &str| -> u128 {
        v[field]["price_in_fri"]
            .as_str()
            .and_then(|s| u128::from_str_radix(s.trim_start_matches("0x"), 16).ok())
            .unwrap_or(0)
    };
    let gas_wei = |field: &str| -> u128 {
        v[field]["price_in_wei"]
            .as_str()
            .and_then(|s| u128::from_str_radix(s.trim_start_matches("0x"), 16).ok())
            .unwrap_or(0)
    };

    Some(crate::data::types::SnBlock {
        number: block_number,
        hash: block_hash,
        parent_hash,
        timestamp,
        sequencer_address,
        transaction_count,
        l1_gas_price_fri: gas_fri("l1_gas_price"),
        l1_gas_price_wei: gas_wei("l1_gas_price"),
        l2_gas_price_fri: gas_fri("l2_gas_price"),
        l1_data_gas_price_fri: gas_fri("l1_data_gas_price"),
        starknet_version,
        // A freshly streamed head block is ACCEPTED_ON_L2; honour an explicit
        // status if the payload carries one. Non-final, so it is re-probed and
        // advances to ACCEPTED_ON_L1 on a later view.
        status: v["status"].as_str().unwrap_or("ACCEPTED_ON_L2").to_string(),
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::types::{SnBlock, SnReceipt, SnTransaction};
    use async_trait::async_trait;
    use starknet::core::types::{AddressFilter, ContractClass};

    /// Minimal DataSource stub for `handle_event` tests. The handler only
    /// calls `append_address_events` (default trait impl is a no-op) — all
    /// other methods are unused here.
    struct TestDataSource;

    #[async_trait]
    impl DataSource for TestDataSource {
        async fn get_latest_block_number(&self) -> crate::error::Result<u64> {
            unimplemented!()
        }
        async fn get_block(&self, _number: u64) -> crate::error::Result<SnBlock> {
            unimplemented!()
        }
        async fn get_block_by_hash(&self, _hash: Felt) -> crate::error::Result<u64> {
            unimplemented!()
        }
        async fn get_block_with_txs(
            &self,
            _number: u64,
        ) -> crate::error::Result<(SnBlock, Vec<SnTransaction>)> {
            unimplemented!()
        }
        async fn get_transaction(&self, _hash: Felt) -> crate::error::Result<SnTransaction> {
            unimplemented!()
        }
        async fn get_receipt(&self, _hash: Felt) -> crate::error::Result<SnReceipt> {
            unimplemented!()
        }
        async fn get_nonce(&self, _address: Felt) -> crate::error::Result<Felt> {
            unimplemented!()
        }
        async fn get_class_hash(&self, _address: Felt) -> crate::error::Result<Felt> {
            unimplemented!()
        }
        async fn get_class(&self, _class_hash: Felt) -> crate::error::Result<ContractClass> {
            unimplemented!()
        }
        async fn get_trace(
            &self,
            _hash: Felt,
        ) -> crate::error::Result<starknet::core::types::TransactionTrace> {
            unimplemented!()
        }
        async fn get_recent_blocks(&self, _count: usize) -> crate::error::Result<Vec<SnBlock>> {
            unimplemented!()
        }
        async fn get_events_for_address(
            &self,
            _address: Felt,
            _from_block: Option<u64>,
            _to_block: Option<u64>,
            _limit: usize,
        ) -> crate::error::Result<Vec<SnEvent>> {
            unimplemented!()
        }
        async fn call_contract(
            &self,
            _contract_address: Felt,
            _selector: Felt,
            _calldata: Vec<Felt>,
        ) -> crate::error::Result<Vec<Felt>> {
            unimplemented!()
        }
    }

    fn test_data_source() -> Arc<dyn DataSource> {
        Arc::new(TestDataSource)
    }

    #[test]
    fn build_subscribe_new_heads_msg() {
        let params = serde_json::to_value(SubscribeNewHeadsRequest { block_id: None }).unwrap();
        let msg = build_subscribe_msg(1, "starknet_subscribeNewHeads", params);
        let v: Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(v["jsonrpc"], "2.0");
        assert_eq!(v["id"], 1);
        assert_eq!(v["method"], "starknet_subscribeNewHeads");
    }

    #[test]
    fn build_subscribe_events_msg_serializes_address() {
        let address = Felt::from_hex_unchecked(
            "0x04270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f",
        );
        let req = SubscribeEventsRequest {
            from_address: Some(AddressFilter::Single(address)),
            keys: None,
            block_id: None,
            finality_status: Some(L2TransactionFinalityStatus::AcceptedOnL2),
        };
        let params = serde_json::to_value(req).unwrap();
        let msg = build_subscribe_msg(2, "starknet_subscribeEvents", params);
        let v: Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(v["method"], "starknet_subscribeEvents");
        // from_address should be serialized as a hex string (AddressFilter::Single)
        assert!(v["params"]["from_address"].is_string());
    }

    #[test]
    fn build_subscribe_transactions_msg_serializes_sender() {
        let address = Felt::from_hex_unchecked(
            "0x01176a1bd84444c89232ec27754698e5d2e7e1a7f1539f12027f28b23ec9f3d8",
        );
        let req = SubscribeNewTransactionsRequest {
            sender_address: Some(vec![address]),
            finality_status: Some(vec![L2TransactionStatus::AcceptedOnL2]),
            tags: None,
        };
        let params = serde_json::to_value(req).unwrap();
        let msg = build_subscribe_msg(3, "starknet_subscribeNewTransactions", params);
        let v: Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(v["method"], "starknet_subscribeNewTransactions");
        assert!(v["params"]["sender_address"].is_array());
    }

    /// The keyed Transfer subscriptions must pin the Transfer selector in key
    /// slot 0, the address in slot 2 (`to`) for the incoming filter, and in
    /// slot 1 (`from`) for the outgoing filter — matching the on-chain
    /// `[selector, from, to]` layout. Serializing through
    /// `SubscribeEventsRequest` with `from_address: None` must produce a
    /// keys-only filter (so transfers from *any* token contract match).
    #[test]
    fn transfer_key_filters_pin_to_and_from_slots() {
        let address = Felt::from_hex_unchecked(
            "0x03a496b92d292386ad70dab94ae181a06d289440e3b632a2435721b4280874c4",
        );
        let sel = transfer_selector();
        // Guard the hardcoded constant: a wrong selector would make the
        // subscription silently never match. Pin it to `sn_keccak("Transfer")`.
        assert_eq!(
            sel,
            starknet::core::utils::get_selector_from_name("Transfer").unwrap(),
            "TRANSFER_SELECTOR must equal sn_keccak(\"Transfer\")"
        );
        let [incoming, outgoing] = transfer_key_filters(address);

        // incoming: [[selector], [], [address]] → to == address, any from
        assert_eq!(incoming, vec![vec![sel], vec![], vec![address]]);
        // outgoing: [[selector], [address], []] → from == address, any to
        assert_eq!(outgoing, vec![vec![sel], vec![address], vec![]]);

        // Serialized request is keys-only (no from_address) so it matches any
        // emitting token contract.
        let req = SubscribeEventsRequest {
            from_address: None,
            keys: Some(incoming),
            block_id: None,
            finality_status: Some(L2TransactionFinalityStatus::AcceptedOnL2),
        };
        let v = serde_json::to_value(req).unwrap();
        assert!(v.get("from_address").is_none() || v["from_address"].is_null());
        assert_eq!(v["keys"][0][0], format!("{sel:#x}"));
        assert_eq!(v["keys"][2][0], format!("{address:#x}"));
    }

    /// Dedup linchpin: a WS event must be broadcast carrying its *real*
    /// `event_index`, not a hardcoded 0. Two distinct Transfers in one tx
    /// (token in at idx 6, token out at idx 7) must yield distinct
    /// `(tx_hash, event_index)` keys so the cache / Events tab keep both and
    /// the Calls tab still collapses them to one row by `tx_hash`.
    #[test]
    fn handle_event_carries_real_event_index() {
        use crate::app::actions::Action;
        use tokio::sync::mpsc;

        let address = Felt::from_hex_unchecked(
            "0x03a496b92d292386ad70dab94ae181a06d289440e3b632a2435721b4280874c4",
        );
        let transfer = crate::data::pathfinder::TRANSFER_SELECTOR;
        // Same tx, two transfer events at indices 6 (in) and 7 (out), emitted
        // by two different token contracts.
        let mk = |from_token: &str, idx: u64| {
            format!(
                r#"{{
                    "from_address": "{from_token}",
                    "keys": ["{transfer}", "0xsomefrom", "{address:#x}"],
                    "data": ["0x2f2c5624", "0x0"],
                    "block_hash": "0xabc",
                    "block_number": 11117243,
                    "transaction_hash": "0x21a4",
                    "transaction_index": 0,
                    "event_index": {idx},
                    "finality_status": "ACCEPTED_ON_L2"
                }}"#
            )
            .replace(
                "0xsomefrom",
                "0x1b6f560def289b32e2a7b0920909615531a4d9d5636ca509045843559dc23d5",
            )
        };

        let (tx, mut rx) = mpsc::unbounded_channel();
        let ds = test_data_source();
        // Two different token contracts emit the two transfers (ETH in, STRK
        // out) — distinct `from_address`, same tx, distinct `event_index`.
        let eth = "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7";
        let strk = "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d";
        let r6: Value = serde_json::from_str(&mk(eth, 6)).unwrap();
        let r7: Value = serde_json::from_str(&mk(strk, 7)).unwrap();
        super::handle_event(&r6, address, &ds, &tx);
        super::handle_event(&r7, address, &ds, &tx);

        let mut indices: Vec<u64> = Vec::new();
        while let Ok(a) = rx.try_recv() {
            if let Action::AddressWsEvent { event, .. } = a {
                assert_eq!(event.transaction_hash, Felt::from_hex_unchecked("0x21a4"));
                indices.push(event.event_index);
            }
        }
        indices.sort_unstable();
        assert_eq!(
            indices,
            vec![6, 7],
            "both transfers must broadcast with their real, distinct event_index"
        );
    }

    #[test]
    fn parse_subscription_confirmation() {
        let json = r#"{"jsonrpc":"2.0","result":"0xdeadbeef","id":1}"#;
        let raw: RawMessage = serde_json::from_str(json).unwrap();
        assert!(raw.id.is_some());
        assert!(raw.error.is_none());
        let sub_id: SubscriptionId = serde_json::from_value(raw.result.unwrap()).unwrap();
        assert_eq!(sub_id.0, "0xdeadbeef");
    }

    #[test]
    fn parse_subscription_error() {
        let json =
            r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found"},"id":1}"#;
        let raw: RawMessage = serde_json::from_str(json).unwrap();
        assert!(raw.result.is_none());
        assert_eq!(raw.error.unwrap().message, "Method not found");
    }

    #[test]
    fn parse_event_notification_pathfinder_style() {
        // Pathfinder sends "subscription" instead of "subscription_id"
        let json = r#"{
            "jsonrpc": "2.0",
            "method": "starknet_subscriptionEvents",
            "params": {
                "subscription": "0x1",
                "result": {
                    "from_address": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
                    "keys": ["0x99cd8bde557814842a3121e8ddfd433a539b8c9f14bf31ebf108d12e6196e9"],
                    "data": ["0x0", "0x1"],
                    "block_hash": "0xabc",
                    "block_number": 100,
                    "transaction_hash": "0xdef",
                    "transaction_index": 0,
                    "event_index": 0,
                    "finality_status": "ACCEPTED_ON_L2"
                }
            }
        }"#;
        let raw: RawMessage = serde_json::from_str(json).unwrap();
        assert_eq!(raw.method.as_deref(), Some("starknet_subscriptionEvents"));
        let params = raw.params.unwrap();
        assert_eq!(params.subscription_id, serde_json::json!("0x1"));

        let event: EmittedEventWithFinality = serde_json::from_value(params.result).unwrap();
        assert_eq!(
            event.emitted_event.from_address,
            Felt::from_hex_unchecked(
                "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"
            )
        );
        assert_eq!(event.emitted_event.block_number, Some(100));
    }

    #[test]
    fn parse_event_notification_spec_style() {
        // Spec uses "subscription_id"
        let json = r#"{
            "jsonrpc": "2.0",
            "method": "starknet_subscription",
            "params": {
                "subscription_id": "0x42",
                "result": {
                    "from_address": "0x1",
                    "keys": ["0x2"],
                    "data": [],
                    "block_hash": "0x3",
                    "block_number": 200,
                    "transaction_hash": "0x4",
                    "transaction_index": 0,
                    "event_index": 1,
                    "finality_status": "ACCEPTED_ON_L2"
                }
            }
        }"#;
        let raw: RawMessage = serde_json::from_str(json).unwrap();
        let params = raw.params.unwrap();
        assert_eq!(params.subscription_id, serde_json::json!("0x42"));
        let event: EmittedEventWithFinality = serde_json::from_value(params.result).unwrap();
        assert_eq!(event.emitted_event.block_number, Some(200));
    }

    #[test]
    fn block_from_raw_extracts_fields() {
        let json = serde_json::json!({
            "block_number": 12345,
            "block_hash": "0xabc",
            "parent_hash": "0xdef",
            "timestamp": 1700000000u64,
            "sequencer_address": "0x1",
            "starknet_version": "0.13.4",
            "transaction_count": 42,
            "l1_gas_price": { "price_in_fri": "0x100", "price_in_wei": "0x200" },
            "l2_gas_price": { "price_in_fri": "0x50" },
            "l1_data_gas_price": { "price_in_fri": "0x10" }
        });
        let block = block_from_raw(&json).expect("block");
        assert_eq!(block.number, 12345);
        assert_eq!(block.transaction_count, 42);
        assert_eq!(block.l1_gas_price_fri, 0x100);
        assert_eq!(block.l1_gas_price_wei, 0x200);
        assert_eq!(block.starknet_version, "0.13.4");
    }

    #[test]
    fn connection_state_tracks_subscriptions() {
        let mut state = ConnectionState::new();
        let addr = Felt::from_hex_unchecked("0x123");
        state
            .pending
            .insert(1, SubscriptionKind::Events { address: addr });
        state
            .pending
            .insert(2, SubscriptionKind::Transactions { address: addr });

        state.confirm_subscribe(1, "sub_events".to_string());
        state.confirm_subscribe(2, "sub_txs".to_string());

        assert!(state.subscriptions.contains_key("sub_events"));
        assert!(state.subscriptions.contains_key("sub_txs"));
        assert_eq!(state.address_subs[&addr].len(), 2);

        let removed = state.remove_address(addr);
        assert_eq!(removed.len(), 2);
        assert!(state.subscriptions.is_empty());
    }

    /// Bug-guard (address-view live updates): when a `TRANSACTION_EXECUTED`
    /// event arrives via WS for the viewed account, `handle_event` must
    /// emit a single `AddressWsEvent` broadcast carrying the event. The
    /// reducer fans this out to the Calls tab and the meta-tx classifier;
    /// this test pins the emission at the handler boundary.
    #[test]
    fn handle_event_tx_executed_broadcasts_ws_event() {
        use crate::app::actions::Action;
        use tokio::sync::mpsc;

        let address = Felt::from_hex_unchecked(
            "0x03a496b92d292386ad70dab94ae181a06d289440e3b632a2435721b4280874c4",
        );
        let tx_hash_hex = "0x0136e683b9f88958252cc44987fabb06483ead59d65b86a8521886637a5bd08d";
        let selector = crate::data::pathfinder::TRANSACTION_EXECUTED_SELECTOR;

        let event_json = format!(
            r#"{{
                "from_address": "{address:#x}",
                "keys": ["{sel}"],
                "data": [],
                "block_hash": "0xabc",
                "block_number": 8914198,
                "transaction_hash": "{tx}",
                "transaction_index": 0,
                "event_index": 0,
                "finality_status": "ACCEPTED_ON_L2"
            }}"#,
            sel = selector,
            tx = tx_hash_hex,
        );
        let result: Value = serde_json::from_str(&event_json).unwrap();

        let (tx, mut rx) = mpsc::unbounded_channel();
        let ds = test_data_source();
        super::handle_event(&result, address, &ds, &tx);

        let mut actions: Vec<Action> = Vec::new();
        while let Ok(a) = rx.try_recv() {
            actions.push(a);
        }

        let ws_event = actions.iter().find_map(|a| match a {
            Action::AddressWsEvent { address: ca, event } if *ca == address => Some(event),
            _ => None,
        });
        let ev = ws_event.expect("TRANSACTION_EXECUTED must emit AddressWsEvent");
        assert_eq!(
            ev.keys.first().copied(),
            Some(super::tx_executed_selector()),
            "first key must be TRANSACTION_EXECUTED selector so the reducer \
             dispatches ClassifyPotentialMetaTx"
        );
        assert_eq!(ev.transaction_hash, Felt::from_hex_unchecked(tx_hash_hex));
        assert_eq!(ev.block_number, 8914198);
    }

    /// Bug-guard: a non-`TRANSACTION_EXECUTED` event still emits the broadcast,
    /// but its first key must not equal the TRANSACTION_EXECUTED selector —
    /// the reducer uses that check to skip meta-tx classification.
    #[test]
    fn handle_event_non_tx_executed_broadcasts_with_other_key() {
        use crate::app::actions::Action;
        use tokio::sync::mpsc;

        let address = Felt::from_hex_unchecked(
            "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
        );
        // Some arbitrary non-TRANSACTION_EXECUTED selector (Transfer).
        let other_selector = "0x0099cd8bde557814842a3121e8ddfd433a539b8c9f14bf31ebf108d12e6196e9";

        let event_json = format!(
            r#"{{
                "from_address": "{address:#x}",
                "keys": ["{sel}"],
                "data": [],
                "block_hash": "0xabc",
                "block_number": 100,
                "transaction_hash": "0xdef",
                "transaction_index": 0,
                "event_index": 0,
                "finality_status": "ACCEPTED_ON_L2"
            }}"#,
            sel = other_selector,
        );
        let result: Value = serde_json::from_str(&event_json).unwrap();

        let (tx, mut rx) = mpsc::unbounded_channel();
        let ds = test_data_source();
        super::handle_event(&result, address, &ds, &tx);

        let mut actions: Vec<Action> = Vec::new();
        while let Ok(a) = rx.try_recv() {
            actions.push(a);
        }

        let ws_event = actions.iter().find_map(|a| match a {
            Action::AddressWsEvent { address: ca, event } if *ca == address => Some(event),
            _ => None,
        });
        let ev = ws_event.expect("non-TRANSACTION_EXECUTED event must still emit AddressWsEvent");
        assert_ne!(
            ev.keys.first().copied(),
            Some(super::tx_executed_selector()),
            "first key must NOT match TRANSACTION_EXECUTED selector"
        );
    }

    #[test]
    fn resume_replays_from_last_head_within_node_window() {
        let mut r = Resume::default();
        assert_eq!(r.replay_from(Some(1_000)), None, "nothing seen yet → tip");

        r.last_head = Some(10_000);
        assert_eq!(r.replay_from(None), Some(10_000 - RESUME_OVERLAP_BLOCKS));
        assert_eq!(
            r.replay_from(Some(10_100)),
            Some(10_000 - RESUME_OVERLAP_BLOCKS)
        );
        // A long outage is clamped to the replay window the node accepts.
        assert_eq!(
            r.replay_from(Some(50_000)),
            Some(50_000 - MAX_RESUME_BLOCKS)
        );

        let a = Felt::from(1_u64);
        r.add(a);
        r.add(a);
        assert_eq!(r.addresses, vec![a]);
        r.remove(a);
        assert!(r.addresses.is_empty());
    }

    /// In-memory write half: records every frame sent.
    fn test_sink() -> (
        impl SinkExt<Message, Error = tokio_tungstenite::tungstenite::Error> + Unpin,
        futures::channel::mpsc::UnboundedReceiver<Message>,
    ) {
        let (tx, rx) = futures::channel::mpsc::unbounded::<Message>();
        let sink = tx.sink_map_err(|_| tokio_tungstenite::tungstenite::Error::ConnectionClosed);
        (sink, rx)
    }

    fn sent_json(rx: &mut futures::channel::mpsc::UnboundedReceiver<Message>) -> Value {
        match rx.try_recv().expect("a frame was sent") {
            Message::Text(t) => serde_json::from_str(&t).unwrap(),
            other => panic!("unexpected frame {other:?}"),
        }
    }

    #[tokio::test]
    async fn replay_subscribe_carries_block_id() {
        let (mut sink, mut rx) = test_sink();
        let mut state = ConnectionState::new();
        let address = Felt::from(0x49d_u64);
        send_subscribe_cmd(
            &mut sink,
            &mut state,
            &WsCommand::SubscribeTransfers { address },
            Some(123),
        )
        .await
        .unwrap();

        for _ in 0..2 {
            let v = sent_json(&mut rx);
            assert_eq!(v["params"]["block_id"]["block_number"], 123);
        }
        assert_eq!(
            state.fallbacks.len(),
            2,
            "each replaying request keeps a fallback"
        );

        // A plain subscribe has no block_id and no fallback.
        let mut fresh = ConnectionState::new();
        send_subscribe_cmd(
            &mut sink,
            &mut fresh,
            &WsCommand::SubscribeEvents { address },
            None,
        )
        .await
        .unwrap();
        assert!(sent_json(&mut rx)["params"].get("block_id").is_none());
        assert!(fresh.fallbacks.is_empty());
    }

    #[tokio::test]
    async fn rejected_replay_resubscribes_from_tip() {
        let (mut sink, mut rx) = test_sink();
        let mut state = ConnectionState::new();
        let address = Felt::from(0x49d_u64);
        send_subscribe_cmd(
            &mut sink,
            &mut state,
            &WsCommand::SubscribeEvents { address },
            Some(123),
        )
        .await
        .unwrap();
        let req_id = sent_json(&mut rx)["id"].as_u64().unwrap();

        let (resp_tx, _resp_rx) = tokio::sync::mpsc::unbounded_channel();
        let (block_tx, _block_rx) = tokio::sync::mpsc::unbounded_channel();
        let head = Arc::new(crate::network::HeadTracker::new());
        let err = format!(
            r#"{{"jsonrpc":"2.0","error":{{"code":68,"message":"Cannot go back more than 1024 blocks"}},"id":{req_id}}}"#
        );
        handle_message(
            &err,
            &mut sink,
            &mut state,
            &test_data_source(),
            &resp_tx,
            &head,
            &block_tx,
        )
        .await;

        let retry = sent_json(&mut rx);
        assert_eq!(retry["method"], "starknet_subscribeEvents");
        assert!(retry["params"].get("block_id").is_none());
        let retry_id = retry["id"].as_u64().unwrap();
        assert!(matches!(
            state.pending.get(&retry_id),
            Some(SubscriptionKind::Events { address: a }) if *a == address
        ));
        assert!(
            state.fallbacks.is_empty(),
            "the tip retry has no further fallback"
        );
    }
}