simulator-client 0.26.0

Async WebSocket client for the Solana simulator backtest API
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
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
use std::{future::Future, time::Duration};

use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
use solana_account_decoder::{UiAccount, UiAccountData, UiAccountEncoding};
use solana_client::{
    nonblocking::pubsub_client::PubsubClient,
    rpc_response::{Response, RpcLogsResponse},
};
use solana_commitment_config::CommitmentConfig;
use solana_rpc_client_api::config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
use thiserror::Error;
use tokio::{
    sync::{oneshot, watch},
    task::JoinHandle,
};
use tokio_tungstenite::tungstenite::Message;

use crate::urls::{UrlError, http_to_ws_url};

/// Error establishing a PubSub log subscription.
#[derive(Debug, Error)]
pub enum SubscriptionError {
    #[error(transparent)]
    InvalidUrl(#[from] UrlError),

    #[error("pubsub connect to {url} failed: {source}")]
    Connect {
        url: String,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    #[error("logs_subscribe failed: {source}")]
    Subscribe {
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    #[error("subscription task exited unexpectedly before signaling ready")]
    TaskDropped,

    #[error("session has no rpc_endpoint (was the session created?)")]
    NoRpcEndpoint,
}

#[derive(Debug, Error)]
pub enum SubscriptionRuntimeError {
    #[error("{kind} subscription for {target} closed unexpectedly")]
    Closed { kind: &'static str, target: String },

    #[error("{kind} subscription callback worker for {target} failed: {source}")]
    CallbackWorker {
        kind: &'static str,
        target: String,
        #[source]
        source: tokio::task::JoinError,
    },
}

const SUBSCRIPTION_DRAIN_IDLE_TIMEOUT: Duration = Duration::from_millis(250);
const SUBSCRIPTION_DRAIN_MAX_DURATION: Duration = Duration::from_secs(5);

type SubscriptionTaskHandle = JoinHandle<Result<(), SubscriptionRuntimeError>>;
type AccountDiffWs =
    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;

/// A unified subscription handle that can represent any subscription type.
pub struct SubscriptionHandle {
    pub join_handle: SubscriptionTaskHandle,
    pub stop: watch::Sender<bool>,
}

impl From<LogSubscriptionHandle> for SubscriptionHandle {
    fn from(h: LogSubscriptionHandle) -> Self {
        Self {
            join_handle: h.join_handle,
            stop: h.stop,
        }
    }
}

impl From<AccountDiffSubscriptionHandle> for SubscriptionHandle {
    fn from(h: AccountDiffSubscriptionHandle) -> Self {
        Self {
            join_handle: h.join_handle,
            stop: h.stop,
        }
    }
}

impl From<ActionSubscriptionHandle> for SubscriptionHandle {
    fn from(h: ActionSubscriptionHandle) -> Self {
        Self {
            join_handle: h.join_handle,
            stop: h.stop,
        }
    }
}

impl From<DiagnosticSubscriptionHandle> for SubscriptionHandle {
    fn from(h: DiagnosticSubscriptionHandle) -> Self {
        Self {
            join_handle: h.join_handle,
            stop: h.stop,
        }
    }
}

/// Handle for a running log subscription background task.
pub struct LogSubscriptionHandle {
    /// Background task that drives the subscription and spawns per-notification callbacks.
    ///
    /// Resolves after `stop.send(true)` is called, remaining buffered
    /// notifications are drained, and all spawned callback tasks complete.
    pub join_handle: SubscriptionTaskHandle,

    /// Send `true` to signal the background task to stop accepting new
    /// notifications, drain remaining buffered ones, and exit cleanly.
    pub stop: watch::Sender<bool>,
}

/// Subscribe to program log notifications and invoke a callback for each one.
///
/// Spawns a background task that:
/// 1. Connects to the PubSub endpoint derived from `rpc_endpoint`.
/// 2. Subscribes to logs mentioning `program_id`.
/// 3. For each notification, spawns `on_notification(notification)` as a Tokio task.
/// 4. When `handle.stop.send(true)` is called, drains remaining buffered
///    notifications (up to 1s), waits for all spawned tasks, then returns.
///
/// Returns after the subscription is established. If setup fails, an error is
/// returned before any background task is left running.
///
/// ## Example
///
/// ```no_run
/// use std::sync::{Arc, Mutex};
/// use simulator_client::subscribe_program_logs;
/// use solana_commitment_config::CommitmentConfig;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let handle = subscribe_program_logs(
///     "https://api.mainnet-beta.solana.com",
///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
///     CommitmentConfig::confirmed(),
///     |notification| async move {
///         println!("sig: {}", notification.value.signature);
///     },
/// )
/// .await?;
///
/// // ... do other work ...
///
/// handle.stop.send(true).ok();
/// handle.join_handle.await.ok();
/// # Ok(())
/// # }
/// ```
pub async fn subscribe_program_logs<F, Fut>(
    rpc_endpoint: &str,
    program_id: &str,
    commitment: CommitmentConfig,
    on_notification: F,
) -> Result<LogSubscriptionHandle, SubscriptionError>
where
    F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    let ws_url = http_to_ws_url(rpc_endpoint)?;
    let program_id = program_id.to_string();

    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
    let (stop_tx, mut stop_rx) = watch::channel(false);

    // PubsubClient::logs_subscribe borrows &self, so both the client and the
    // stream must live inside the spawned task. We report setup success/failure
    // back through a oneshot channel before entering the notification loop.
    let join_handle = tokio::spawn(async move {
        let client = match PubsubClient::new(&ws_url).await {
            Ok(c) => c,
            Err(e) => {
                let _ = ready_tx.send(Err(SubscriptionError::Connect {
                    url: ws_url,
                    source: Box::new(e),
                }));
                return Ok(());
            }
        };

        let (mut stream, _unsubscribe) = match client
            .logs_subscribe(
                RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
                RpcTransactionLogsConfig {
                    commitment: Some(commitment),
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => {
                let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
                    source: Box::new(e),
                }));
                return Ok(());
            }
        };

        let _ = ready_tx.send(Ok(()));

        let mut tasks: Vec<JoinHandle<()>> = Vec::new();
        let kind = "program logs";

        loop {
            if *stop_rx.borrow() {
                let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
                while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
                    drain_deadline,
                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
                )
                .await
                {
                    tasks.push(tokio::spawn(on_notification(notification)));
                }
                break;
            }

            let notification = tokio::select! {
                n = stream.next() => n,
                _ = stop_rx.changed() => continue,
            };

            match notification {
                Some(n) => tasks.push(tokio::spawn(on_notification(n))),
                None => return Err(subscription_runtime_closed(kind, &program_id)),
            }
        }

        // Wait for all in-flight callback tasks to complete.
        for task in tasks {
            if let Err(source) = task.await {
                return Err(callback_worker_failed(kind, &program_id, source));
            }
        }

        Ok(())
    });

    match ready_rx.await {
        Ok(Ok(())) => Ok(LogSubscriptionHandle {
            join_handle,
            stop: stop_tx,
        }),
        Ok(Err(e)) => {
            join_handle.abort();
            Err(e)
        }
        Err(_) => {
            join_handle.abort();
            Err(SubscriptionError::TaskDropped)
        }
    }
}

// ── Account diff subscription ────────────────────────────────────────────────

/// Slot context included in every account diff notification.
#[derive(Debug, Clone, Deserialize)]
pub struct AccountDiffContext {
    pub slot: u64,
}

/// A single account diff notification delivered by `accountDiffSubscribe`.
#[derive(Debug, Clone, Deserialize)]
pub struct AccountDiffNotification {
    pub context: AccountDiffContext,
    /// The address of the account that changed.
    pub account: Option<String>,
    /// Signature of the transaction that triggered this change, if known.
    pub signature: Option<String>,
    /// Position of the transaction within its slot, if known.
    #[serde(default)]
    pub tx_index: Option<u32>,
    /// Unix-seconds block time of the slot, if known.
    #[serde(default)]
    pub block_time: Option<i64>,
    /// Account state before the change (absent for newly created accounts).
    pub pre: Option<serde_json::Value>,
    /// Account state after the change (absent for deleted accounts).
    pub post: Option<serde_json::Value>,
}

impl AccountDiffNotification {
    /// Decode the post-state into the wire [`AccountData`] shape, when present.
    pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
        self.post.as_ref().map(account_data_from_ui)
    }
}

/// Error decoding a serialized [`UiAccount`] into the wire [`AccountData`] shape.
#[derive(Debug, Error)]
pub enum UiAccountConversionError {
    #[error("payload is not a UiAccount: {0}")]
    NotAUiAccount(#[from] serde_json::Error),

    #[error("unsupported ui-account data encoding, expected base64")]
    UnsupportedEncoding,

    #[error("decoding base64 account data: {0}")]
    Data(#[from] base64::DecodeError),

    #[error("parsing owner address: {0}")]
    Owner(#[from] solana_address::error::ParseAddressError),
}

/// Decode a serde-serialized [`UiAccount`] (the `pre`/`post` payload shape) into
/// the wire [`AccountData`] shape. Only base64 data is supported; `space` falls
/// back to the decoded data length when absent.
pub fn account_data_from_ui(
    value: &serde_json::Value,
) -> Result<AccountData, UiAccountConversionError> {
    let ui = UiAccount::deserialize(value)?;
    let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
        return Err(UiAccountConversionError::UnsupportedEncoding);
    };
    let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
    let space = match ui.space {
        Some(space) => space,
        None => encoded.decode()?.len() as u64,
    };
    Ok(AccountData {
        data: encoded,
        executable: ui.executable,
        lamports: ui.lamports,
        owner: ui.owner.parse()?,
        space,
    })
}

#[derive(Debug, Clone, Deserialize)]
pub struct ActionResultContext {
    pub slot: u64,
}

/// One scheduled-action result delivered by `actionSubscribe`.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionResultNotification {
    pub context: ActionResultContext,
    pub slot: u64,
    /// Batch the action fired at; `None` for slot-boundary actions.
    #[serde(default)]
    pub batch_index: Option<u32>,
    /// The matched transaction's index in its slot's block, the index Solana reports for it;
    /// `None` for slot-boundary actions and from a session that predates it.
    #[serde(default)]
    pub tx_index: Option<u32>,
    /// Index of the action in the session's `actions` list.
    pub action_index: u32,
    #[serde(default)]
    pub label: Option<String>,
    pub committed: bool,
    /// One per transaction in the action's sequence, in order. A failing
    /// transaction is the last entry; later transactions don't run.
    #[serde(default)]
    pub transaction_outcomes: Vec<ActionTransactionOutcome>,
    /// Post-execution `UiAccount` JSON per `return_accounts` address, positional;
    /// cumulative state after the final transaction.
    #[serde(default)]
    pub accounts: Vec<Option<serde_json::Value>>,
    /// Encoded transaction whose discovery-filter match triggered this action;
    /// absent for slot-boundary actions. Decode with [`EncodedBinary::decode`]
    /// (base64 bincode of `TxWithMeta`) to inspect the matching transaction.
    #[serde(default)]
    pub matched: Option<EncodedBinary>,
}

/// One transaction's result within a scheduled action's sequence.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionTransactionOutcome {
    /// Transaction failure message; `None` on success.
    #[serde(default)]
    pub err: Option<String>,
    #[serde(default)]
    pub logs: Vec<String>,
    pub units_consumed: u64,
    #[serde(default)]
    pub fee: Option<u64>,
    /// Program return data (`{programId, data}`), if any.
    #[serde(default)]
    pub return_data: Option<serde_json::Value>,
}

/// A routed account diff notification tied to the subscribed account that produced it.
#[derive(Debug, Clone)]
pub struct RoutedAccountDiffNotification {
    pub account: String,
    pub notification: AccountDiffNotification,
}

/// Handle for a running account diff subscription background task.
///
/// Send `true` on `stop` to request a clean shutdown, then await `join_handle`.
pub struct AccountDiffSubscriptionHandle {
    pub join_handle: SubscriptionTaskHandle,
    pub stop: watch::Sender<bool>,
}

fn subscription_runtime_closed(
    kind: &'static str,
    target: impl Into<String>,
) -> SubscriptionRuntimeError {
    SubscriptionRuntimeError::Closed {
        kind,
        target: target.into(),
    }
}

fn callback_worker_failed(
    kind: &'static str,
    target: impl Into<String>,
    source: tokio::task::JoinError,
) -> SubscriptionRuntimeError {
    SubscriptionRuntimeError::CallbackWorker {
        kind,
        target: target.into(),
        source,
    }
}

/// Subscribe to account diff notifications and invoke a callback for each one.
///
/// Spawns a background task that:
/// 1. Connects to the WebSocket endpoint derived from `rpc_endpoint`.
/// 2. Subscribes to account diffs for the given filter (account or program).
/// 3. For each notification, spawns `on_notification(notification)` as a Tokio task.
/// 4. When `handle.stop.send(true)` is called, drains remaining buffered
///    notifications (up to 1s), waits for all spawned tasks, then returns.
///
/// ## Example
///
/// ```no_run
/// use simulator_client::subscribe_account_diffs;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let handle = subscribe_account_diffs(
///     "http://localhost:8900/session/abc",
///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
///     |notification| async move {
///         println!("slot={} sig={:?}", notification.context.slot, notification.signature);
///     },
/// )
/// .await?;
///
/// handle.stop.send(true).ok();
/// handle.join_handle.await.ok();
/// # Ok(())
/// # }
/// ```
pub async fn subscribe_account_diffs<F, Fut>(
    rpc_endpoint: &str,
    account: &str,
    on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
    F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
        on_notification(notification.notification)
    })
    .await
}

/// Subscribe to account diff notifications for many accounts over a single websocket.
///
/// All requested subscriptions must be acknowledged before this returns. Once the
/// stream is live, any websocket disconnect is treated as a fatal completeness
/// error instead of silently reconnecting and risking dropped notifications.
pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
    rpc_endpoint: &str,
    accounts: I,
    on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
    F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    let ws_url = http_to_ws_url(rpc_endpoint)?;
    let accounts = dedup_accounts(accounts);
    if accounts.is_empty() {
        let (stop_tx, stop_rx) = watch::channel(false);
        return Ok(AccountDiffSubscriptionHandle {
            join_handle: tokio::spawn(async move {
                let _ = stop_rx;
                Ok(())
            }),
            stop: stop_tx,
        });
    }

    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
    let (stop_tx, mut stop_rx) = watch::channel(false);
    let target = format!("{} accounts", accounts.len());

    let join_handle = tokio::spawn(async move {
        let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
        let callback_handle = tokio::spawn(async move {
            while let Some(notification) = notification_rx.recv().await {
                on_notification(notification).await;
            }
        });

        let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
            Ok(connection) => connection,
            Err(e) => {
                let _ = ready_tx.send(Err(SubscriptionError::Connect {
                    url: ws_url,
                    source: Box::new(e),
                }));
                return Ok(());
            }
        };

        let subscriptions =
            match send_account_diff_subscribe_many(&mut ws, &accounts, &notification_tx).await {
                Ok(subscriptions) => subscriptions,
                Err(error) => {
                    let _ = ready_tx.send(Err(error));
                    return Ok(());
                }
            };

        let _ = ready_tx.send(Ok(()));

        if let Err(error) =
            drive_account_diff_stream_many(&mut ws, &subscriptions, &notification_tx, &mut stop_rx)
                .await
        {
            drop(notification_tx);
            if let Err(source) = callback_handle.await {
                return Err(callback_worker_failed("account diff", target, source));
            }
            return Err(error);
        }

        drop(notification_tx);
        if let Err(source) = callback_handle.await {
            return Err(callback_worker_failed("account diff", target, source));
        }

        Ok(())
    });

    match ready_rx.await {
        Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
            join_handle,
            stop: stop_tx,
        }),
        Ok(Err(e)) => {
            join_handle.abort();
            Err(e)
        }
        Err(_) => {
            join_handle.abort();
            Err(SubscriptionError::TaskDropped)
        }
    }
}

#[derive(Deserialize)]
struct AccountDiffMessage {
    method: String,
    params: AccountDiffParams,
}

#[derive(Deserialize)]
struct AccountDiffParams {
    subscription: u64,
    result: AccountDiffNotification,
}

async fn send_account_diff_subscribe_many(
    ws: &mut AccountDiffWs,
    accounts: &[String],
    notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
) -> Result<std::collections::HashMap<u64, String>, SubscriptionError> {
    #[derive(Deserialize)]
    struct SubscriptionConfirmation {
        id: u64,
        result: Option<u64>,
    }

    let mut pending: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
    let mut subscriptions = std::collections::HashMap::with_capacity(accounts.len());

    for (index, account) in accounts.iter().enumerate() {
        let request_id = (index + 1) as u64;
        let req = serde_json::json!({
            "jsonrpc": "2.0",
            "id": request_id,
            "method": "accountDiffSubscribe",
            "params": [account]
        });
        ws.send(Message::Text(req.to_string()))
            .await
            .map_err(|source| SubscriptionError::Subscribe {
                source: Box::new(source),
            })?;
        pending.insert(request_id, account.clone());
    }

    while !pending.is_empty() {
        match ws.next().await {
            Some(Ok(Message::Text(text))) => {
                if let Ok(confirmation) = serde_json::from_str::<SubscriptionConfirmation>(&text) {
                    let Some(account) = pending.remove(&confirmation.id) else {
                        continue;
                    };
                    let Some(subscription_id) = confirmation.result else {
                        return Err(SubscriptionError::TaskDropped);
                    };
                    subscriptions.insert(subscription_id, account);
                    continue;
                }

                if let Some(notification) =
                    parse_routed_account_diff_notification(&text, &subscriptions)
                {
                    let _ = notification_tx.send(notification);
                }
            }
            Some(Ok(_)) => {}
            _ => return Err(SubscriptionError::TaskDropped),
        }
    }

    Ok(subscriptions)
}

async fn drive_account_diff_stream_many(
    ws: &mut AccountDiffWs,
    subscriptions: &std::collections::HashMap<u64, String>,
    notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
    stop_rx: &mut watch::Receiver<bool>,
) -> Result<(), SubscriptionRuntimeError> {
    loop {
        if *stop_rx.borrow() {
            let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
            loop {
                match tokio::time::timeout_at(
                    drain_deadline,
                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
                )
                .await
                {
                    Ok(Ok(Some(Ok(Message::Text(text))))) => {
                        if let Some(notification) =
                            parse_routed_account_diff_notification(&text, subscriptions)
                        {
                            let _ = notification_tx.send(notification);
                        }
                    }
                    _ => return Ok(()),
                }
            }
        }

        let msg = tokio::select! {
            m = ws.next() => m,
            _ = stop_rx.changed() => continue,
        };

        match msg {
            Some(Ok(Message::Text(text))) => {
                if let Some(notification) =
                    parse_routed_account_diff_notification(&text, subscriptions)
                {
                    let _ = notification_tx.send(notification);
                }
            }
            Some(Ok(_)) => {}
            _ => {
                return Err(subscription_runtime_closed(
                    "account diff",
                    format!("{} accounts", subscriptions.len()),
                ));
            }
        }
    }
}

fn parse_account_diff_message(text: &str) -> Option<AccountDiffMessage> {
    let msg: AccountDiffMessage = serde_json::from_str(text).ok()?;
    (msg.method == "accountDiffNotification").then_some(msg)
}

fn parse_routed_account_diff_notification(
    text: &str,
    subscriptions: &std::collections::HashMap<u64, String>,
) -> Option<RoutedAccountDiffNotification> {
    let msg = parse_account_diff_message(text)?;
    let account = subscriptions.get(&msg.params.subscription)?.clone();
    Some(RoutedAccountDiffNotification {
        account,
        notification: msg.params.result,
    })
}

fn dedup_accounts<I, S>(accounts: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    let mut unique = std::collections::BTreeSet::new();
    accounts
        .into_iter()
        .map(Into::into)
        .filter(|account| unique.insert(account.clone()))
        .collect()
}

// ── Program account diff subscription ────────────────────────────────────────

/// Subscribe to account diff notifications for all accounts owned by a program.
///
/// Uses the server-side program filter (`{"address_type": "program"}`), so no
/// RPC prefetch of program accounts is required.  The callback receives one
/// [`AccountDiffNotification`] per changed account.
///
/// A websocket disconnect is treated as a fatal error — the handle's
/// `join_handle` resolves with a [`SubscriptionRuntimeError`].
///
/// ## Example
///
/// ```no_run
/// use simulator_client::subscribe_program_diffs;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let handle = subscribe_program_diffs(
///     "http://localhost:8900/session/abc",
///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
///     |notification| async move {
///         let account = notification.account.unwrap_or_default();
///         println!("account={account} slot={}", notification.context.slot);
///     },
/// )
/// .await?;
///
/// handle.stop.send(true).ok();
/// handle.join_handle.await.ok();
/// # Ok(())
/// # }
/// ```
pub async fn subscribe_program_diffs<F, Fut>(
    rpc_endpoint: &str,
    program_id: &str,
    on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
    F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    let ws_url = http_to_ws_url(rpc_endpoint)?;
    let program_id = program_id.to_string();

    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
    let (stop_tx, mut stop_rx) = watch::channel(false);

    let join_handle = tokio::spawn(async move {
        let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
        let callback_handle = tokio::spawn(async move {
            while let Some(notification) = notification_rx.recv().await {
                on_notification(notification).await;
            }
        });

        let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
            Ok(connection) => connection,
            Err(e) => {
                let _ = ready_tx.send(Err(SubscriptionError::Connect {
                    url: ws_url,
                    source: Box::new(e),
                }));
                return Ok(());
            }
        };

        if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
            let _ = ready_tx.send(Err(error));
            return Ok(());
        }

        let _ = ready_tx.send(Ok(()));

        if let Err(error) =
            drive_program_diff_stream(&mut ws, &notification_tx, &mut stop_rx, &program_id).await
        {
            drop(notification_tx);
            if let Err(source) = callback_handle.await {
                return Err(callback_worker_failed(
                    "program account diff",
                    &program_id,
                    source,
                ));
            }
            return Err(error);
        }

        drop(notification_tx);
        if let Err(source) = callback_handle.await {
            return Err(callback_worker_failed(
                "program account diff",
                &program_id,
                source,
            ));
        }

        Ok(())
    });

    match ready_rx.await {
        Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
            join_handle,
            stop: stop_tx,
        }),
        Ok(Err(e)) => {
            join_handle.abort();
            Err(e)
        }
        Err(_) => {
            join_handle.abort();
            Err(SubscriptionError::TaskDropped)
        }
    }
}

async fn send_program_diff_subscribe(
    ws: &mut AccountDiffWs,
    program_id: &str,
) -> Result<(), SubscriptionError> {
    #[derive(Deserialize)]
    struct SubscriptionConfirmation {
        result: Option<u64>,
    }

    let req = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "accountDiffSubscribe",
        "params": [program_id, {"address_type": "program"}]
    });
    ws.send(Message::Text(req.to_string()))
        .await
        .map_err(|source| SubscriptionError::Subscribe {
            source: Box::new(source),
        })?;

    loop {
        match ws.next().await {
            Some(Ok(Message::Text(text))) => {
                match serde_json::from_str::<SubscriptionConfirmation>(&text) {
                    Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
                    Ok(_) => continue,
                    Err(source) => {
                        return Err(SubscriptionError::Subscribe {
                            source: Box::new(source),
                        });
                    }
                }
            }
            Some(Ok(_)) => continue,
            _ => return Err(SubscriptionError::TaskDropped),
        }
    }
}

async fn drive_program_diff_stream(
    ws: &mut AccountDiffWs,
    notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
    stop_rx: &mut watch::Receiver<bool>,
    program_id: &str,
) -> Result<(), SubscriptionRuntimeError> {
    loop {
        if *stop_rx.borrow() {
            let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
            loop {
                match tokio::time::timeout_at(
                    drain_deadline,
                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
                )
                .await
                {
                    Ok(Ok(Some(Ok(Message::Text(text))))) => {
                        if let Some(msg) = parse_account_diff_message(&text) {
                            let _ = notification_tx.send(msg.params.result);
                        }
                    }
                    _ => return Ok(()),
                }
            }
        }

        let msg = tokio::select! {
            m = ws.next() => m,
            _ = stop_rx.changed() => continue,
        };

        match msg {
            Some(Ok(Message::Text(text))) => {
                if let Some(msg) = parse_account_diff_message(&text) {
                    let _ = notification_tx.send(msg.params.result);
                }
            }
            Some(Ok(_)) => {}
            _ => {
                return Err(subscription_runtime_closed(
                    "program account diff",
                    program_id,
                ));
            }
        }
    }
}

// ── Keyless notification streams ─────────────────────────────────────────────

/// The strings that distinguish one keyless notification stream from another.
#[derive(Clone, Copy)]
struct NotificationStream {
    subscribe_method: &'static str,
    notification_method: &'static str,
    /// Singular label used in runtime errors.
    kind: &'static str,
    /// Plural label used in runtime errors.
    target: &'static str,
}

const ACTION_STREAM: NotificationStream = NotificationStream {
    subscribe_method: "actionSubscribe",
    notification_method: "actionNotification",
    kind: "action",
    target: "actions",
};

const REPLACEMENT_STREAM: NotificationStream = NotificationStream {
    subscribe_method: "replacementSubscribe",
    notification_method: "replacementNotification",
    kind: "replacement",
    target: "replacements",
};

const DIAGNOSTIC_STREAM: NotificationStream = NotificationStream {
    subscribe_method: "diagnosticSubscribe",
    notification_method: "diagnosticNotification",
    kind: "diagnostic",
    target: "diagnostics",
};

#[derive(Deserialize)]
struct NotificationMessage<N> {
    method: String,
    params: NotificationParams<N>,
}

#[derive(Deserialize)]
struct NotificationParams<N> {
    #[allow(dead_code)]
    subscription: u64,
    result: N,
}

fn parse_notification_message<N: DeserializeOwned>(
    text: &str,
    notification_method: &str,
) -> Option<N> {
    let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
    (msg.method == notification_method).then_some(msg.params.result)
}

fn is_subscription_complete_message(text: &str) -> bool {
    #[derive(Deserialize)]
    struct SubscriptionCompleteMessage {
        method: String,
    }

    serde_json::from_str::<SubscriptionCompleteMessage>(text)
        .is_ok_and(|msg| msg.method == "subscriptionComplete")
}

/// Drive a keyless notification stream, invoking `on_notification` for each payload.
///
/// Implements the protocol every single-stream subscription shares; once `stop` is set, drains
/// whatever the server has already queued before resolving.
async fn subscribe_notifications<N, F, Fut>(
    rpc_endpoint: &str,
    stream: NotificationStream,
    on_notification: F,
) -> Result<SubscriptionHandle, SubscriptionError>
where
    N: DeserializeOwned + Send + 'static,
    F: Fn(N) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    let ws_url = http_to_ws_url(rpc_endpoint)?;

    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
    let (stop_tx, mut stop_rx) = watch::channel(false);

    let join_handle = tokio::spawn(async move {
        let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
        let callback_handle = tokio::spawn(async move {
            while let Some(notification) = notification_rx.recv().await {
                on_notification(notification).await;
            }
        });

        let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
            Ok(connection) => connection,
            Err(e) => {
                let _ = ready_tx.send(Err(SubscriptionError::Connect {
                    url: ws_url,
                    source: Box::new(e),
                }));
                return Ok(());
            }
        };

        if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
            let _ = ready_tx.send(Err(error));
            return Ok(());
        }

        let _ = ready_tx.send(Ok(()));

        if let Err(error) =
            drive_notification_stream::<N>(&mut ws, stream, &notification_tx, &mut stop_rx).await
        {
            drop(notification_tx);
            if let Err(source) = callback_handle.await {
                return Err(callback_worker_failed(stream.kind, stream.target, source));
            }
            return Err(error);
        }

        drop(notification_tx);
        if let Err(source) = callback_handle.await {
            return Err(callback_worker_failed(stream.kind, stream.target, source));
        }

        Ok(())
    });

    match ready_rx.await {
        Ok(Ok(())) => Ok(SubscriptionHandle {
            join_handle,
            stop: stop_tx,
        }),
        Ok(Err(e)) => {
            join_handle.abort();
            Err(e)
        }
        Err(_) => {
            join_handle.abort();
            Err(SubscriptionError::TaskDropped)
        }
    }
}

async fn send_stream_subscribe(
    ws: &mut AccountDiffWs,
    subscribe_method: &str,
) -> Result<(), SubscriptionError> {
    #[derive(Deserialize)]
    struct SubscriptionConfirmation {
        result: Option<u64>,
    }

    // Keyless: index 0 is an unused placeholder, index 1 the (empty) config object.
    let req = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": subscribe_method,
        "params": [serde_json::Value::Null, {}]
    });

    ws.send(Message::Text(req.to_string()))
        .await
        .map_err(|source| SubscriptionError::Subscribe {
            source: Box::new(source),
        })?;

    loop {
        match ws.next().await {
            Some(Ok(Message::Text(text))) => {
                match serde_json::from_str::<SubscriptionConfirmation>(&text) {
                    Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
                    Ok(_) => continue,
                    Err(source) => {
                        return Err(SubscriptionError::Subscribe {
                            source: Box::new(source),
                        });
                    }
                }
            }
            Some(Ok(_)) => continue,
            _ => return Err(SubscriptionError::TaskDropped),
        }
    }
}

async fn drive_notification_stream<N: DeserializeOwned>(
    ws: &mut AccountDiffWs,
    stream: NotificationStream,
    notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
    stop_rx: &mut watch::Receiver<bool>,
) -> Result<(), SubscriptionRuntimeError> {
    loop {
        if *stop_rx.borrow() {
            let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
            loop {
                match tokio::time::timeout_at(
                    drain_deadline,
                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
                )
                .await
                {
                    Ok(Ok(Some(Ok(Message::Text(text))))) => {
                        if is_subscription_complete_message(&text) {
                            return Ok(());
                        }
                        if let Some(result) =
                            parse_notification_message::<N>(&text, stream.notification_method)
                        {
                            let _ = notification_tx.send(result);
                        }
                    }
                    _ => return Ok(()),
                }
            }
        }

        let msg = tokio::select! {
            m = ws.next() => m,
            _ = stop_rx.changed() => continue,
        };

        match msg {
            Some(Ok(Message::Text(text))) => {
                if is_subscription_complete_message(&text) {
                    return Ok(());
                }
                if let Some(result) =
                    parse_notification_message::<N>(&text, stream.notification_method)
                {
                    let _ = notification_tx.send(result);
                }
            }
            Some(Ok(_)) => {}
            _ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
        }
    }
}

// ── Action subscription ──────────────────────────────────────────────────────

/// Handle for a running scheduled-action subscription background task.
///
/// Send `true` on `stop` to request a clean shutdown, then await `join_handle`.
pub struct ActionSubscriptionHandle {
    pub join_handle: SubscriptionTaskHandle,
    pub stop: watch::Sender<bool>,
}

/// Subscribe to scheduled-action results streamed over `actionSubscribe`.
///
/// The session automatically runs the `ScheduledAction`s registered at creation;
/// each result is delivered to `on_notification` as an [`ActionResultNotification`].
/// This is a single, keyless subscription — every action shares one stream, so the
/// callback distinguishes them via `action_index` / `label`.
///
/// A websocket disconnect is treated as a fatal error — the handle's `join_handle`
/// resolves with a [`SubscriptionRuntimeError`].
///
/// ## Example
///
/// ```no_run
/// use simulator_client::subscribe_actions;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let handle = subscribe_actions(
///     "http://localhost:8900/session/abc",
///     |result| async move {
///         println!("slot={} label={:?}", result.slot, result.label);
///     },
/// )
/// .await?;
///
/// handle.stop.send(true).ok();
/// handle.join_handle.await.ok();
/// # Ok(())
/// # }
/// ```
pub async fn subscribe_actions<F, Fut>(
    rpc_endpoint: &str,
    on_notification: F,
) -> Result<ActionSubscriptionHandle, SubscriptionError>
where
    F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    let SubscriptionHandle { join_handle, stop } =
        subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
    Ok(ActionSubscriptionHandle { join_handle, stop })
}

// ── Diagnostic subscription ──────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticContext {
    pub slot: u64,
}

/// One market's `/diagnostic` sample at one size, delivered by `diagnosticSubscribe`: the
/// router's own pricing, not a fill the venue produced.
///
/// [`Serialize`] so a run can be recorded as it streams and read back as this same type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticNotification {
    pub context: DiagnosticContext,
    /// The replayed slot the probe fired at the end of.
    pub slot: u64,
    /// Index of the probe in the session's `diagnosticProbes` list.
    pub probe_index: u32,
    #[serde(default)]
    pub label: Option<String>,
    pub market: String,
    pub usd_value: u32,
    /// The router's ingest slot when it answered. Lags `slot` by whatever the stream has yet to
    /// drain, so a consumer needing the two aligned must check rather than assume.
    #[serde(default)]
    pub router_slot: Option<u64>,
    /// `swapInfoResults` verbatim: both directions priced at `usd_value`.
    #[serde(default)]
    pub results: Option<serde_json::Value>,
    /// One per backing account the router priced from, in the order it sent them.
    #[serde(default)]
    pub account_hashes: Vec<String>,
    /// Why this probe produced no sample; `None` on success.
    #[serde(default)]
    pub err: Option<String>,
}

pub struct DiagnosticSubscriptionHandle {
    pub join_handle: SubscriptionTaskHandle,
    pub stop: watch::Sender<bool>,
}

/// Subscribe to `/diagnostic` samples. Probes are registered in `CreateSessionParams`; this only
/// attaches the consumer.
pub async fn subscribe_diagnostics<F, Fut>(
    rpc_endpoint: &str,
    on_notification: F,
) -> Result<DiagnosticSubscriptionHandle, SubscriptionError>
where
    F: Fn(DiagnosticNotification) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    let SubscriptionHandle { join_handle, stop } =
        subscribe_notifications(rpc_endpoint, DIAGNOSTIC_STREAM, on_notification).await?;
    Ok(DiagnosticSubscriptionHandle { join_handle, stop })
}

// ── Replacement subscription ─────────────────────────────────────────────────

// The wire contract itself, not a mirror of it: one declaration both sides build against, so a
// field the server adds cannot go missing here. Restating it by hand is how `outcome`,
// `category` and `err` came to be dropped.
pub use simulator_api::replacement::{
    DirectFillNotification, L1Score, OriginalNotification, ProbedHop, ReplacementContext,
    ReplacementCore, ReplacementNotification, RequoteNotification, RerouteLegNotification,
};

/// Subscribe to replacement results streamed over `replacementSubscribe`.
///
/// Each requote simulation or direct-fill probe is delivered to `on_notification` as a
/// [`ReplacementNotification`]; branch on its variant, or hand the stream to
/// [`crate::reroute_report::from_stream`] / [`crate::reroute_report::probes_from_stream`]. Single
/// and keyless — every result shares one stream, distinguished by `slot` / `batch_index` /
/// `original_signature`.
///
/// A websocket disconnect is treated as a fatal error — the handle's `join_handle` resolves with
/// a [`SubscriptionRuntimeError`].
///
/// ## Example
///
/// ```no_run
/// use simulator_client::{ReplacementNotification, subscribe_replacements};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let handle = subscribe_replacements(
///     "http://localhost:8900/session/abc",
///     |result| async move {
///         match result {
///             ReplacementNotification::Requote(requote) => {
///                 println!("slot={} sig={}", requote.core.slot, requote.core.original_signature);
///             }
///             ReplacementNotification::DirectFill(probe) => {
///                 println!("template={} sig={}", probe.template, probe.core.original_signature);
///             }
///         }
///     },
/// )
/// .await?;
///
/// handle.stop.send(true).ok();
/// handle.join_handle.await.ok();
/// # Ok(())
/// # }
/// ```
pub async fn subscribe_replacements<F, Fut>(
    rpc_endpoint: &str,
    on_notification: F,
) -> Result<SubscriptionHandle, SubscriptionError>
where
    F: Fn(ReplacementNotification) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    subscribe_notifications(rpc_endpoint, REPLACEMENT_STREAM, on_notification).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_account_diff_notification_ignores_other_messages() {
        let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
        assert!(parse_account_diff_message(confirmation).is_none());
    }

    #[test]
    fn parse_account_diff_notification_extracts_payload() {
        let text = r#"{
            "jsonrpc":"2.0",
            "method":"accountDiffNotification",
            "params":{
                "subscription":7,
                "result":{
                    "context":{"slot":123},
                    "signature":"sig",
                    "pre":{"a":1},
                    "post":{"a":2}
                }
            }
        }"#;

        let notification = parse_account_diff_message(text)
            .expect("notification")
            .params
            .result;
        assert_eq!(notification.context.slot, 123);
        assert_eq!(notification.signature.as_deref(), Some("sig"));
        assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
        assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
    }

    #[test]
    fn parse_routed_account_diff_notification_extracts_subscription_account() {
        let text = r#"{
            "jsonrpc":"2.0",
            "method":"accountDiffNotification",
            "params":{
                "subscription":42,
                "result":{
                    "context":{"slot":456},
                    "signature":"sig",
                    "pre":null,
                    "post":{"a":2}
                }
            }
        }"#;
        let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);

        let notification =
            parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
        assert_eq!(notification.account, "acct");
        assert_eq!(notification.notification.context.slot, 456);
    }

    #[test]
    fn converts_ui_account_json() {
        let value = serde_json::json!({
            "lamports": 5,
            "data": ["AQID", "base64"],
            "owner": "11111111111111111111111111111111",
            "executable": false,
            "rentEpoch": 0,
        });
        let account = account_data_from_ui(&value).unwrap();
        assert_eq!(account.lamports, 5);
        assert_eq!(account.space, 3);
        assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
    }

    #[test]
    fn rejects_non_base64_encodings() {
        let value = serde_json::json!({
            "lamports": 5,
            "data": ["{}", "jsonParsed"],
            "owner": "11111111111111111111111111111111",
            "executable": false,
            "rentEpoch": 0,
        });
        assert!(matches!(
            account_data_from_ui(&value),
            Err(UiAccountConversionError::UnsupportedEncoding)
        ));
    }

    #[test]
    fn dedup_accounts_preserves_first_seen_order() {
        let accounts = dedup_accounts([
            "b".to_string(),
            "a".to_string(),
            "b".to_string(),
            "c".to_string(),
        ]);
        assert_eq!(accounts, vec!["b", "a", "c"]);
    }

    /// The signature every fixture names. Typed on the core, so it has to be real base58.
    fn fixture_signature() -> String {
        simulator_api::replacement::Signature::default().to_string()
    }

    /// `set` overrides its `swapInfo`; every other field is explicitly null.
    fn route_hop(set: serde_json::Value, program: serde_json::Value) -> serde_json::Value {
        use serde_json::json;

        let mut swap_info = json!({
            "label": null, "ammKey": null, "inputMint": null,
            "inAmount": null, "outputMint": null, "outAmount": null,
        });
        for (key, value) in set.as_object().expect("an object") {
            swap_info[key] = value.clone();
        }
        json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
    }

    /// A wire-shaped fixture rather than a constructed value: a field serializing under a
    /// different name than it deserializes would still round-trip through a struct.
    #[test]
    fn a_requote_notification_round_trips_through_its_own_encoding() {
        use serde_json::{Value, json};

        let wire = serde_json::json!({
            "kind": "requote",
            "context": {"slot": 42},
            "slot": 42,
            "batchIndex": 3,
            "originalSignature": fixture_signature(),
            "originalFailed": false,
            "outcome": "filled",
            "legs": [{
                "inputMint": simulator_api::mints::SOL.to_string(),
                "outputMint": simulator_api::mints::USDC.to_string(),
                "amount": 1_000,
                "swapMode": "ExactIn",
                "originalQuotedOut": 990,
                "metisQuotedOut": 1_010,
                "routeSummary": "SolFi",
                // Unset fields are written as null: the recording path decodes positionally.
                "routePlan": [route_hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
                "originalRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
                "realizedRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
            }],
            "routedTransaction": {"data": "AA==", "encoding": "base64"},
            "logs": ["Program log: swap"],
            "computeUnitsConsumed": 123_456,
            "fee": 5_000,
            "realizedOutputAmount": 1_009,
            "originalRealizedOutputAmount": 991,
        });

        let notification: ReplacementNotification =
            serde_json::from_value(wire.clone()).expect("wire decodes");
        let recorded = serde_json::to_value(&notification).expect("notification encodes");
        assert_eq!(recorded, wire);

        let ReplacementNotification::Requote(read_back) =
            serde_json::from_value::<ReplacementNotification>(recorded).expect("recording decodes")
        else {
            panic!("kind=requote must decode to the Requote variant");
        };
        assert_eq!(read_back.core.batch_index, 3);
        assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
        assert_eq!(read_back.original_realized_output_amount, Some(991));
        // The routed plan is the fill and `route_plan` is the quote; a reader that conflated them
        // would compare a projection against an outcome.
        assert!(
            read_back
                .legs
                .iter()
                .all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
        );
    }

    /// The adapter keys filled-ness on `outcome`; `category` carries only the revert reason.
    #[test]
    fn a_direct_fill_notification_round_trips_through_its_own_encoding() {
        let wire = serde_json::json!({
            "kind": "directFill",
            "context": {"slot": 7},
            "slot": 7,
            "batchIndex": 1,
            "originalSignature": fixture_signature(),
            "originalFailed": false,
            "template": "Tempest",
            "program": simulator_api::mints::USDC.to_string(),
            "hop": {
                "slot": 9,
                "blockTime": 1_767_225_600i64,
                "txIndex": 4,
                "ixIndex": 0,
                "legIndex": 0,
                "program": simulator_api::mints::SOL.to_string(),
                "inputAmount": 1_000,
                "outputAmount": 1_000,
                "replayInputAmount": 1_000,
                "replayOutputAmount": 1_005,
            },
            "quoteTxIndex": 1,
            "quoteLagBlocks": 2,
            "inputMint": simulator_api::mints::SOL.to_string(),
            "outputMint": simulator_api::mints::USDC.to_string(),
            "amount": 1_000,
            "swapMode": "ExactIn",
            "templateFill": 1_010,
            "l1Fill": 1_000,
            "changeVsL1Bps": 100,
            "outcome": "filled",
        });

        let notification: ReplacementNotification =
            serde_json::from_value(wire.clone()).expect("wire decodes");
        let recorded = serde_json::to_value(&notification).expect("notification encodes");
        assert_eq!(recorded, wire);

        let ReplacementNotification::DirectFill(read_back) = notification else {
            panic!("kind=directFill must decode to the DirectFill variant");
        };
        assert_eq!(read_back.template, "Tempest");
        assert_eq!(read_back.template_fill, Some(1_010));
        assert_eq!(read_back.comparison.l1_fill, Some(1_000));
        assert_eq!(read_back.comparison.change_vs_l1_bps, Some(100));
        assert!(
            read_back.core.category.is_none(),
            "a filled probe carries no category"
        );
    }

    /// The server emits one of these for every admitted transaction. Until this variant existed
    /// client-side, `parse_notification_message` turned the unknown tag into `Ok(None)` and the
    /// caller dropped it with no `else` — a silent discard, once per original, in every reroute
    /// session. Nothing logged it and nothing counted it, so only a decode test catches the next
    /// time the hand-written mirror drifts from the server's shape.
    #[test]
    fn an_original_notification_round_trips_through_its_own_encoding() {
        let wire = serde_json::json!({
            "kind": "original",
            "context": {"slot": 9},
            "slot": 9,
            "batchIndex": 2,
            "originalSignature": fixture_signature(),
            "originalFailed": false,
            "l1Fill": 2_000,
            "changeVsL1Bps": -25,
            "computeUnitsConsumed": 31_400,
            "fee": 5_000,
            "simulatedOutputAmount": 1_995,
            "outcome": "filled",
        });

        let notification: ReplacementNotification =
            serde_json::from_value(wire.clone()).expect("wire decodes");

        let ReplacementNotification::Original(read_back) = notification else {
            panic!("kind=original must decode to the Original variant");
        };
        assert_eq!(read_back.core.slot, 9);
        assert_eq!(
            read_back.core.original_signature.to_string(),
            fixture_signature()
        );
        assert_eq!(read_back.comparison.l1_fill, Some(2_000));
        assert_eq!(read_back.comparison.change_vs_l1_bps, Some(-25));
        assert_eq!(read_back.cost.compute_units_consumed, 31_400);
        assert_eq!(read_back.simulated_output_amount, Some(1_995));
        assert_eq!(read_back.core.outcome, "filled");
    }

    /// A payload with no `kind` tag: an internally-tagged enum needs one to pick a variant, so
    /// this must fail loudly rather than silently misparse into either shape.
    #[test]
    fn an_untagged_old_format_payload_fails_to_deserialize() {
        let old_wire = serde_json::json!({
            "context": {"slot": 42},
            "slot": 42,
            "batchIndex": 3,
            "originalSignature": fixture_signature(),
            "legs": [],
            "routedTransaction": {"data": "AA==", "encoding": "base64"},
            "err": serde_json::Value::Null,
            "logs": [],
            "computeUnitsConsumed": 0,
            "fee": serde_json::Value::Null,
            "realizedOutputAmount": serde_json::Value::Null,
            "originalRealizedOutputAmount": serde_json::Value::Null,
            "originalFailed": false,
        });

        let err = serde_json::from_value::<ReplacementNotification>(old_wire).expect_err(
            "an untagged old-format payload must not deserialize as a ReplacementNotification",
        );
        assert!(
            err.to_string().contains("kind"),
            "must fail on the missing tag, not misparse into either variant: {err}"
        );
    }
}