1use std::{future::Future, time::Duration};
23
24use futures::{SinkExt, StreamExt};
25use serde::{Deserialize, Serialize, de::DeserializeOwned};
26use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
27use solana_account_decoder::{UiAccount, UiAccountData, UiAccountEncoding};
28use solana_client::{
29 nonblocking::pubsub_client::PubsubClient,
30 rpc_response::{Response, RpcLogsResponse},
31};
32use solana_commitment_config::CommitmentConfig;
33use solana_rpc_client_api::config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
34use solana_transaction::versioned::VersionedTransaction;
35use thiserror::Error;
36use tokio::{
37 sync::{oneshot, watch},
38 task::JoinHandle,
39};
40use tokio_tungstenite::tungstenite::Message;
41
42use crate::{
43 endpoint::without_query,
44 tx::{TxDecodeError, decode_transaction},
45 urls::{UrlError, http_to_ws_url},
46};
47
48#[derive(Debug, Error)]
51#[allow(missing_docs)]
52pub enum SubscriptionError {
53 #[error(transparent)]
56 InvalidUrl(#[from] UrlError),
57
58 #[error("pubsub connect to {url} failed: {source}")]
62 Connect {
63 url: String,
65 #[source]
66 source: Box<dyn std::error::Error + Send + Sync>,
67 },
68
69 #[error("logs_subscribe failed: {source}")]
72 Subscribe {
73 #[source]
75 source: Box<dyn std::error::Error + Send + Sync>,
76 },
77
78 #[error("subscription task exited unexpectedly before signaling ready")]
81 TaskDropped,
82}
83
84impl SubscriptionError {
85 fn connect(ws_url: &str, source: impl std::error::Error + Send + Sync + 'static) -> Self {
86 Self::Connect {
87 url: without_query(ws_url).to_owned(),
88 source: Box::new(source),
89 }
90 }
91}
92
93#[derive(Debug, Error)]
98pub enum SubscriptionRuntimeError {
99 #[error("{kind} subscription for {target} closed unexpectedly")]
104 Closed {
105 kind: &'static str,
107 target: String,
109 },
110
111 #[error("{kind} subscription callback worker for {target} failed: {source}")]
114 CallbackWorker {
115 kind: &'static str,
117 target: String,
119 #[source]
121 source: tokio::task::JoinError,
122 },
123
124 #[error("subscription task failed: {0}")]
127 Task(#[from] tokio::task::JoinError),
128}
129
130const SUBSCRIPTION_DRAIN_IDLE_TIMEOUT: Duration = Duration::from_millis(250);
131const SUBSCRIPTION_DRAIN_MAX_DURATION: Duration = Duration::from_secs(5);
132
133type SubscriptionTaskHandle = JoinHandle<Result<(), SubscriptionRuntimeError>>;
134type AccountDiffWs =
135 tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
136
137pub struct SubscriptionHandle {
142 pub join_handle: SubscriptionTaskHandle,
145 pub stop: watch::Sender<bool>,
148}
149
150impl SubscriptionHandle {
151 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
160 self.stop.send_replace(true);
162 self.join_handle.await?
163 }
164}
165
166impl LogSubscriptionHandle {
167 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
169 SubscriptionHandle::from(self).shutdown().await
170 }
171}
172
173impl From<LogSubscriptionHandle> for SubscriptionHandle {
174 fn from(h: LogSubscriptionHandle) -> Self {
175 Self {
176 join_handle: h.join_handle,
177 stop: h.stop,
178 }
179 }
180}
181
182impl AccountDiffSubscriptionHandle {
183 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
185 SubscriptionHandle::from(self).shutdown().await
186 }
187}
188
189impl From<AccountDiffSubscriptionHandle> for SubscriptionHandle {
190 fn from(h: AccountDiffSubscriptionHandle) -> Self {
191 Self {
192 join_handle: h.join_handle,
193 stop: h.stop,
194 }
195 }
196}
197
198impl ActionSubscriptionHandle {
199 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
201 SubscriptionHandle::from(self).shutdown().await
202 }
203}
204
205impl From<ActionSubscriptionHandle> for SubscriptionHandle {
206 fn from(h: ActionSubscriptionHandle) -> Self {
207 Self {
208 join_handle: h.join_handle,
209 stop: h.stop,
210 }
211 }
212}
213
214impl DiagnosticSubscriptionHandle {
215 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
217 SubscriptionHandle::from(self).shutdown().await
218 }
219}
220
221impl From<DiagnosticSubscriptionHandle> for SubscriptionHandle {
222 fn from(h: DiagnosticSubscriptionHandle) -> Self {
223 Self {
224 join_handle: h.join_handle,
225 stop: h.stop,
226 }
227 }
228}
229
230pub struct LogSubscriptionHandle {
235 pub join_handle: SubscriptionTaskHandle,
238
239 pub stop: watch::Sender<bool>,
242}
243
244pub async fn subscribe_program_logs<F, Fut>(
283 rpc_endpoint: &str,
284 program_id: &str,
285 commitment: CommitmentConfig,
286 on_notification: F,
287) -> Result<LogSubscriptionHandle, SubscriptionError>
288where
289 F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
290 Fut: Future<Output = ()> + Send + 'static,
291{
292 let ws_url = http_to_ws_url(rpc_endpoint)?;
293 let program_id = program_id.to_string();
294
295 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
296 let (stop_tx, mut stop_rx) = watch::channel(false);
297
298 let join_handle = tokio::spawn(async move {
302 let client = match PubsubClient::new(&ws_url).await {
303 Ok(c) => c,
304 Err(e) => {
305 let _ = ready_tx.send(Err(SubscriptionError::connect(&ws_url, e)));
306 return Ok(());
307 }
308 };
309
310 let (mut stream, _unsubscribe) = match client
311 .logs_subscribe(
312 RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
313 RpcTransactionLogsConfig {
314 commitment: Some(commitment),
315 },
316 )
317 .await
318 {
319 Ok(s) => s,
320 Err(e) => {
321 let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
322 source: Box::new(e),
323 }));
324 return Ok(());
325 }
326 };
327
328 let _ = ready_tx.send(Ok(()));
329
330 let mut tasks: Vec<JoinHandle<()>> = Vec::new();
331 let kind = "program logs";
332
333 loop {
334 if *stop_rx.borrow() {
335 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
336 while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
337 drain_deadline,
338 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
339 )
340 .await
341 {
342 tasks.push(tokio::spawn(on_notification(notification)));
343 }
344 break;
345 }
346
347 let notification = tokio::select! {
348 n = stream.next() => n,
349 _ = stop_rx.changed() => continue,
350 };
351
352 match notification {
353 Some(n) => tasks.push(tokio::spawn(on_notification(n))),
354 None => return Err(subscription_runtime_closed(kind, &program_id)),
355 }
356 }
357
358 for task in tasks {
360 if let Err(source) = task.await {
361 return Err(callback_worker_failed(kind, &program_id, source));
362 }
363 }
364
365 Ok(())
366 });
367
368 match ready_rx.await {
369 Ok(Ok(())) => Ok(LogSubscriptionHandle {
370 join_handle,
371 stop: stop_tx,
372 }),
373 Ok(Err(e)) => {
374 join_handle.abort();
375 Err(e)
376 }
377 Err(_) => {
378 join_handle.abort();
379 Err(SubscriptionError::TaskDropped)
380 }
381 }
382}
383
384#[derive(Debug, Clone, Deserialize)]
388pub struct AccountDiffContext {
389 #[allow(missing_docs)]
390 pub slot: u64,
391}
392
393#[derive(Debug, Clone, Deserialize)]
398pub struct AccountDiffNotification {
399 #[allow(missing_docs)]
400 pub context: AccountDiffContext,
401 pub account: Option<String>,
403 pub signature: Option<String>,
405 #[serde(default)]
407 pub tx_index: Option<u32>,
408 #[serde(default)]
410 pub block_time: Option<i64>,
411 pub pre: Option<serde_json::Value>,
413 pub post: Option<serde_json::Value>,
415}
416
417impl AccountDiffNotification {
418 pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
420 self.post.as_ref().map(account_data_from_ui)
421 }
422}
423
424#[derive(Debug, Error)]
426pub enum UiAccountConversionError {
427 #[error("payload is not a UiAccount: {0}")]
429 NotAUiAccount(#[from] serde_json::Error),
430
431 #[error("unsupported ui-account data encoding, expected base64")]
433 UnsupportedEncoding,
434
435 #[error("decoding base64 account data: {0}")]
437 Data(#[from] base64::DecodeError),
438
439 #[error("parsing owner address: {0}")]
441 Owner(#[from] solana_address::error::ParseAddressError),
442}
443
444pub fn account_data_from_ui(
452 value: &serde_json::Value,
453) -> Result<AccountData, UiAccountConversionError> {
454 let ui = UiAccount::deserialize(value)?;
455 let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
456 return Err(UiAccountConversionError::UnsupportedEncoding);
457 };
458 let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
459 let space = match ui.space {
460 Some(space) => space,
461 None => encoded.decode()?.len() as u64,
462 };
463 Ok(AccountData {
464 data: encoded,
465 executable: ui.executable,
466 lamports: ui.lamports,
467 owner: ui.owner.parse()?,
468 space,
469 })
470}
471
472#[derive(Debug, Clone, Deserialize)]
474pub struct ActionResultContext {
475 pub slot: u64,
477}
478
479#[derive(Debug, Clone, Deserialize)]
481#[serde(rename_all = "camelCase")]
482pub struct ActionResultNotification {
483 #[allow(missing_docs)]
484 pub context: ActionResultContext,
485 pub slot: u64,
487 #[serde(default)]
489 pub batch_index: Option<u32>,
490 #[serde(default)]
493 pub tx_index: Option<u32>,
494 #[serde(default)]
496 pub batch_last_tx_index: Option<u32>,
497 #[serde(default)]
499 pub block_time: Option<i64>,
500 pub action_index: u32,
502 #[serde(default)]
504 pub label: Option<String>,
505 pub committed: bool,
508 #[serde(default)]
511 pub transaction_outcomes: Vec<ActionTransactionOutcome>,
512 #[serde(default)]
515 pub accounts: Vec<Option<serde_json::Value>>,
516 #[serde(default)]
520 pub matched: Option<EncodedBinary>,
521}
522
523impl ActionResultNotification {
524 pub fn failure(&self) -> Option<&ActionTransactionOutcome> {
526 self.transaction_outcomes.last().filter(|o| o.err.is_some())
528 }
529
530 pub fn returned_account(
533 &self,
534 index: usize,
535 ) -> Option<Result<AccountData, UiAccountConversionError>> {
536 self.accounts.get(index)?.as_ref().map(account_data_from_ui)
537 }
538
539 pub fn matched_transaction(&self) -> Option<Result<VersionedTransaction, TxDecodeError>> {
541 self.matched.as_ref().map(decode_transaction)
542 }
543}
544
545#[derive(Debug, Clone, Deserialize)]
547#[serde(rename_all = "camelCase")]
548pub struct ActionTransactionOutcome {
549 #[serde(default)]
551 pub err: Option<String>,
552 #[serde(default)]
553 #[allow(missing_docs)]
554 pub logs: Vec<String>,
555 #[allow(missing_docs)]
556 pub units_consumed: u64,
557 #[serde(default)]
559 pub fee: Option<u64>,
560 #[serde(default)]
562 pub return_data: Option<serde_json::Value>,
563 #[serde(default)]
566 pub unresolved: bool,
567}
568
569#[derive(Debug, Clone)]
572pub struct RoutedAccountDiffNotification {
573 pub account: String,
575 #[allow(missing_docs)]
576 pub notification: AccountDiffNotification,
577}
578
579pub struct AccountDiffSubscriptionHandle {
584 pub join_handle: SubscriptionTaskHandle,
586 pub stop: watch::Sender<bool>,
588}
589
590fn subscription_runtime_closed(
591 kind: &'static str,
592 target: impl Into<String>,
593) -> SubscriptionRuntimeError {
594 SubscriptionRuntimeError::Closed {
595 kind,
596 target: target.into(),
597 }
598}
599
600fn callback_worker_failed(
601 kind: &'static str,
602 target: impl Into<String>,
603 source: tokio::task::JoinError,
604) -> SubscriptionRuntimeError {
605 SubscriptionRuntimeError::CallbackWorker {
606 kind,
607 target: target.into(),
608 source,
609 }
610}
611
612pub async fn subscribe_account_diffs<F, Fut>(
643 rpc_endpoint: &str,
644 account: &str,
645 on_notification: F,
646) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
647where
648 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
649 Fut: Future<Output = ()> + Send + 'static,
650{
651 subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
652 on_notification(notification.notification)
653 })
654 .await
655}
656
657pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
668 rpc_endpoint: &str,
669 accounts: I,
670 on_notification: F,
671) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
672where
673 F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
674 Fut: Future<Output = ()> + Send + 'static,
675 I: IntoIterator<Item = S>,
676 S: Into<String>,
677{
678 let ws_url = http_to_ws_url(rpc_endpoint)?;
679 let accounts = dedup_accounts(accounts);
680 if accounts.is_empty() {
681 let (stop_tx, stop_rx) = watch::channel(false);
682 return Ok(AccountDiffSubscriptionHandle {
683 join_handle: tokio::spawn(async move {
684 let _ = stop_rx;
685 Ok(())
686 }),
687 stop: stop_tx,
688 });
689 }
690
691 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
692 let (stop_tx, mut stop_rx) = watch::channel(false);
693 let target = format!("{} accounts", accounts.len());
694
695 let join_handle = tokio::spawn(async move {
696 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
697 let callback_handle = tokio::spawn(async move {
698 while let Some(notification) = notification_rx.recv().await {
699 on_notification(notification).await;
700 }
701 });
702
703 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
704 Ok(connection) => connection,
705 Err(e) => {
706 let _ = ready_tx.send(Err(SubscriptionError::connect(&ws_url, e)));
707 return Ok(());
708 }
709 };
710
711 let subscriptions =
712 match send_account_diff_subscribe_many(&mut ws, &accounts, ¬ification_tx).await {
713 Ok(subscriptions) => subscriptions,
714 Err(error) => {
715 let _ = ready_tx.send(Err(error));
716 return Ok(());
717 }
718 };
719
720 let _ = ready_tx.send(Ok(()));
721
722 if let Err(error) =
723 drive_account_diff_stream_many(&mut ws, &subscriptions, ¬ification_tx, &mut stop_rx)
724 .await
725 {
726 drop(notification_tx);
727 if let Err(source) = callback_handle.await {
728 return Err(callback_worker_failed("account diff", target, source));
729 }
730 return Err(error);
731 }
732
733 drop(notification_tx);
734 if let Err(source) = callback_handle.await {
735 return Err(callback_worker_failed("account diff", target, source));
736 }
737
738 Ok(())
739 });
740
741 match ready_rx.await {
742 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
743 join_handle,
744 stop: stop_tx,
745 }),
746 Ok(Err(e)) => {
747 join_handle.abort();
748 Err(e)
749 }
750 Err(_) => {
751 join_handle.abort();
752 Err(SubscriptionError::TaskDropped)
753 }
754 }
755}
756
757#[derive(Deserialize)]
758struct AccountDiffMessage {
759 method: String,
760 params: AccountDiffParams,
761}
762
763#[derive(Deserialize)]
764struct AccountDiffParams {
765 subscription: u64,
766 result: AccountDiffNotification,
767}
768
769async fn send_account_diff_subscribe_many(
770 ws: &mut AccountDiffWs,
771 accounts: &[String],
772 notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
773) -> Result<std::collections::HashMap<u64, String>, SubscriptionError> {
774 #[derive(Deserialize)]
775 struct SubscriptionConfirmation {
776 id: u64,
777 result: Option<u64>,
778 }
779
780 let mut pending: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
781 let mut subscriptions = std::collections::HashMap::with_capacity(accounts.len());
782
783 for (index, account) in accounts.iter().enumerate() {
784 let request_id = (index + 1) as u64;
785 let req = serde_json::json!({
786 "jsonrpc": "2.0",
787 "id": request_id,
788 "method": "accountDiffSubscribe",
789 "params": [account]
790 });
791 ws.send(Message::Text(req.to_string()))
792 .await
793 .map_err(|source| SubscriptionError::Subscribe {
794 source: Box::new(source),
795 })?;
796 pending.insert(request_id, account.clone());
797 }
798
799 while !pending.is_empty() {
800 match ws.next().await {
801 Some(Ok(Message::Text(text))) => {
802 if let Ok(confirmation) = serde_json::from_str::<SubscriptionConfirmation>(&text) {
803 let Some(account) = pending.remove(&confirmation.id) else {
804 continue;
805 };
806 let Some(subscription_id) = confirmation.result else {
807 return Err(SubscriptionError::TaskDropped);
808 };
809 subscriptions.insert(subscription_id, account);
810 continue;
811 }
812
813 if let Some(notification) =
814 parse_routed_account_diff_notification(&text, &subscriptions)
815 {
816 let _ = notification_tx.send(notification);
817 }
818 }
819 Some(Ok(_)) => {}
820 _ => return Err(SubscriptionError::TaskDropped),
821 }
822 }
823
824 Ok(subscriptions)
825}
826
827async fn drive_account_diff_stream_many(
828 ws: &mut AccountDiffWs,
829 subscriptions: &std::collections::HashMap<u64, String>,
830 notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
831 stop_rx: &mut watch::Receiver<bool>,
832) -> Result<(), SubscriptionRuntimeError> {
833 loop {
834 if *stop_rx.borrow() {
835 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
836 loop {
837 match tokio::time::timeout_at(
838 drain_deadline,
839 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
840 )
841 .await
842 {
843 Ok(Ok(Some(Ok(Message::Text(text))))) => {
844 if let Some(notification) =
845 parse_routed_account_diff_notification(&text, subscriptions)
846 {
847 let _ = notification_tx.send(notification);
848 }
849 }
850 _ => return Ok(()),
851 }
852 }
853 }
854
855 let msg = tokio::select! {
856 m = ws.next() => m,
857 _ = stop_rx.changed() => continue,
858 };
859
860 match msg {
861 Some(Ok(Message::Text(text))) => {
862 if let Some(notification) =
863 parse_routed_account_diff_notification(&text, subscriptions)
864 {
865 let _ = notification_tx.send(notification);
866 }
867 }
868 Some(Ok(_)) => {}
869 _ => {
870 return Err(subscription_runtime_closed(
871 "account diff",
872 format!("{} accounts", subscriptions.len()),
873 ));
874 }
875 }
876 }
877}
878
879fn parse_account_diff_message(text: &str) -> Option<AccountDiffMessage> {
880 let msg: AccountDiffMessage = serde_json::from_str(text).ok()?;
881 (msg.method == "accountDiffNotification").then_some(msg)
882}
883
884fn parse_routed_account_diff_notification(
885 text: &str,
886 subscriptions: &std::collections::HashMap<u64, String>,
887) -> Option<RoutedAccountDiffNotification> {
888 let msg = parse_account_diff_message(text)?;
889 let account = subscriptions.get(&msg.params.subscription)?.clone();
890 Some(RoutedAccountDiffNotification {
891 account,
892 notification: msg.params.result,
893 })
894}
895
896fn dedup_accounts<I, S>(accounts: I) -> Vec<String>
897where
898 I: IntoIterator<Item = S>,
899 S: Into<String>,
900{
901 let mut unique = std::collections::BTreeSet::new();
902 accounts
903 .into_iter()
904 .map(Into::into)
905 .filter(|account| unique.insert(account.clone()))
906 .collect()
907}
908
909pub async fn subscribe_program_diffs<F, Fut>(
943 rpc_endpoint: &str,
944 program_id: &str,
945 on_notification: F,
946) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
947where
948 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
949 Fut: Future<Output = ()> + Send + 'static,
950{
951 let ws_url = http_to_ws_url(rpc_endpoint)?;
952 let program_id = program_id.to_string();
953
954 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
955 let (stop_tx, mut stop_rx) = watch::channel(false);
956
957 let join_handle = tokio::spawn(async move {
958 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
959 let callback_handle = tokio::spawn(async move {
960 while let Some(notification) = notification_rx.recv().await {
961 on_notification(notification).await;
962 }
963 });
964
965 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
966 Ok(connection) => connection,
967 Err(e) => {
968 let _ = ready_tx.send(Err(SubscriptionError::connect(&ws_url, e)));
969 return Ok(());
970 }
971 };
972
973 if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
974 let _ = ready_tx.send(Err(error));
975 return Ok(());
976 }
977
978 let _ = ready_tx.send(Ok(()));
979
980 if let Err(error) =
981 drive_program_diff_stream(&mut ws, ¬ification_tx, &mut stop_rx, &program_id).await
982 {
983 drop(notification_tx);
984 if let Err(source) = callback_handle.await {
985 return Err(callback_worker_failed(
986 "program account diff",
987 &program_id,
988 source,
989 ));
990 }
991 return Err(error);
992 }
993
994 drop(notification_tx);
995 if let Err(source) = callback_handle.await {
996 return Err(callback_worker_failed(
997 "program account diff",
998 &program_id,
999 source,
1000 ));
1001 }
1002
1003 Ok(())
1004 });
1005
1006 match ready_rx.await {
1007 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
1008 join_handle,
1009 stop: stop_tx,
1010 }),
1011 Ok(Err(e)) => {
1012 join_handle.abort();
1013 Err(e)
1014 }
1015 Err(_) => {
1016 join_handle.abort();
1017 Err(SubscriptionError::TaskDropped)
1018 }
1019 }
1020}
1021
1022async fn send_program_diff_subscribe(
1023 ws: &mut AccountDiffWs,
1024 program_id: &str,
1025) -> Result<(), SubscriptionError> {
1026 #[derive(Deserialize)]
1027 struct SubscriptionConfirmation {
1028 result: Option<u64>,
1029 }
1030
1031 let req = serde_json::json!({
1032 "jsonrpc": "2.0",
1033 "id": 1,
1034 "method": "accountDiffSubscribe",
1035 "params": [program_id, {"address_type": "program"}]
1036 });
1037 ws.send(Message::Text(req.to_string()))
1038 .await
1039 .map_err(|source| SubscriptionError::Subscribe {
1040 source: Box::new(source),
1041 })?;
1042
1043 loop {
1044 match ws.next().await {
1045 Some(Ok(Message::Text(text))) => {
1046 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1047 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1048 Ok(_) => continue,
1049 Err(source) => {
1050 return Err(SubscriptionError::Subscribe {
1051 source: Box::new(source),
1052 });
1053 }
1054 }
1055 }
1056 Some(Ok(_)) => continue,
1057 _ => return Err(SubscriptionError::TaskDropped),
1058 }
1059 }
1060}
1061
1062async fn drive_program_diff_stream(
1063 ws: &mut AccountDiffWs,
1064 notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
1065 stop_rx: &mut watch::Receiver<bool>,
1066 program_id: &str,
1067) -> Result<(), SubscriptionRuntimeError> {
1068 loop {
1069 if *stop_rx.borrow() {
1070 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1071 loop {
1072 match tokio::time::timeout_at(
1073 drain_deadline,
1074 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1075 )
1076 .await
1077 {
1078 Ok(Ok(Some(Ok(Message::Text(text))))) => {
1079 if let Some(msg) = parse_account_diff_message(&text) {
1080 let _ = notification_tx.send(msg.params.result);
1081 }
1082 }
1083 _ => return Ok(()),
1084 }
1085 }
1086 }
1087
1088 let msg = tokio::select! {
1089 m = ws.next() => m,
1090 _ = stop_rx.changed() => continue,
1091 };
1092
1093 match msg {
1094 Some(Ok(Message::Text(text))) => {
1095 if let Some(msg) = parse_account_diff_message(&text) {
1096 let _ = notification_tx.send(msg.params.result);
1097 }
1098 }
1099 Some(Ok(_)) => {}
1100 _ => {
1101 return Err(subscription_runtime_closed(
1102 "program account diff",
1103 program_id,
1104 ));
1105 }
1106 }
1107 }
1108}
1109
1110#[derive(Clone, Copy)]
1114struct NotificationStream {
1115 subscribe_method: &'static str,
1116 notification_method: &'static str,
1117 kind: &'static str,
1119 target: &'static str,
1121}
1122
1123const ACTION_STREAM: NotificationStream = NotificationStream {
1124 subscribe_method: "actionSubscribe",
1125 notification_method: "actionNotification",
1126 kind: "action",
1127 target: "actions",
1128};
1129
1130const REPLACEMENT_STREAM: NotificationStream = NotificationStream {
1131 subscribe_method: "replacementSubscribe",
1132 notification_method: "replacementNotification",
1133 kind: "replacement",
1134 target: "replacements",
1135};
1136
1137const DIAGNOSTIC_STREAM: NotificationStream = NotificationStream {
1138 subscribe_method: "diagnosticSubscribe",
1139 notification_method: "diagnosticNotification",
1140 kind: "diagnostic",
1141 target: "diagnostics",
1142};
1143
1144#[derive(Deserialize)]
1145struct NotificationMessage<N> {
1146 method: String,
1147 params: NotificationParams<N>,
1148}
1149
1150#[derive(Deserialize)]
1151struct NotificationParams<N> {
1152 #[allow(dead_code)]
1153 subscription: u64,
1154 result: N,
1155}
1156
1157fn parse_notification_message<N: DeserializeOwned>(
1158 text: &str,
1159 notification_method: &str,
1160) -> Option<N> {
1161 let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
1162 (msg.method == notification_method).then_some(msg.params.result)
1163}
1164
1165fn is_subscription_complete_message(text: &str) -> bool {
1166 #[derive(Deserialize)]
1167 struct SubscriptionCompleteMessage {
1168 method: String,
1169 }
1170
1171 serde_json::from_str::<SubscriptionCompleteMessage>(text)
1172 .is_ok_and(|msg| msg.method == "subscriptionComplete")
1173}
1174
1175async fn subscribe_notifications<N, F, Fut>(
1180 rpc_endpoint: &str,
1181 stream: NotificationStream,
1182 on_notification: F,
1183) -> Result<SubscriptionHandle, SubscriptionError>
1184where
1185 N: DeserializeOwned + Send + 'static,
1186 F: Fn(N) -> Fut + Send + Sync + 'static,
1187 Fut: Future<Output = ()> + Send + 'static,
1188{
1189 let ws_url = http_to_ws_url(rpc_endpoint)?;
1190
1191 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
1192 let (stop_tx, mut stop_rx) = watch::channel(false);
1193
1194 let join_handle = tokio::spawn(async move {
1195 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
1196 let callback_handle = tokio::spawn(async move {
1197 while let Some(notification) = notification_rx.recv().await {
1198 on_notification(notification).await;
1199 }
1200 });
1201
1202 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
1203 Ok(connection) => connection,
1204 Err(e) => {
1205 let _ = ready_tx.send(Err(SubscriptionError::connect(&ws_url, e)));
1206 return Ok(());
1207 }
1208 };
1209
1210 if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
1211 let _ = ready_tx.send(Err(error));
1212 return Ok(());
1213 }
1214
1215 let _ = ready_tx.send(Ok(()));
1216
1217 if let Err(error) =
1218 drive_notification_stream::<N>(&mut ws, stream, ¬ification_tx, &mut stop_rx).await
1219 {
1220 drop(notification_tx);
1221 if let Err(source) = callback_handle.await {
1222 return Err(callback_worker_failed(stream.kind, stream.target, source));
1223 }
1224 return Err(error);
1225 }
1226
1227 drop(notification_tx);
1228 if let Err(source) = callback_handle.await {
1229 return Err(callback_worker_failed(stream.kind, stream.target, source));
1230 }
1231
1232 Ok(())
1233 });
1234
1235 match ready_rx.await {
1236 Ok(Ok(())) => Ok(SubscriptionHandle {
1237 join_handle,
1238 stop: stop_tx,
1239 }),
1240 Ok(Err(e)) => {
1241 join_handle.abort();
1242 Err(e)
1243 }
1244 Err(_) => {
1245 join_handle.abort();
1246 Err(SubscriptionError::TaskDropped)
1247 }
1248 }
1249}
1250
1251async fn send_stream_subscribe(
1252 ws: &mut AccountDiffWs,
1253 subscribe_method: &str,
1254) -> Result<(), SubscriptionError> {
1255 #[derive(Deserialize)]
1256 struct SubscriptionConfirmation {
1257 result: Option<u64>,
1258 }
1259
1260 let req = serde_json::json!({
1262 "jsonrpc": "2.0",
1263 "id": 1,
1264 "method": subscribe_method,
1265 "params": [serde_json::Value::Null, {}]
1266 });
1267
1268 ws.send(Message::Text(req.to_string()))
1269 .await
1270 .map_err(|source| SubscriptionError::Subscribe {
1271 source: Box::new(source),
1272 })?;
1273
1274 loop {
1275 match ws.next().await {
1276 Some(Ok(Message::Text(text))) => {
1277 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1278 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1279 Ok(_) => continue,
1280 Err(source) => {
1281 return Err(SubscriptionError::Subscribe {
1282 source: Box::new(source),
1283 });
1284 }
1285 }
1286 }
1287 Some(Ok(_)) => continue,
1288 _ => return Err(SubscriptionError::TaskDropped),
1289 }
1290 }
1291}
1292
1293async fn drive_notification_stream<N: DeserializeOwned>(
1294 ws: &mut AccountDiffWs,
1295 stream: NotificationStream,
1296 notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
1297 stop_rx: &mut watch::Receiver<bool>,
1298) -> Result<(), SubscriptionRuntimeError> {
1299 loop {
1300 if *stop_rx.borrow() {
1301 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1302 loop {
1303 match tokio::time::timeout_at(
1304 drain_deadline,
1305 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1306 )
1307 .await
1308 {
1309 Ok(Ok(Some(Ok(Message::Text(text))))) => {
1310 if is_subscription_complete_message(&text) {
1311 return Ok(());
1312 }
1313 if let Some(result) =
1314 parse_notification_message::<N>(&text, stream.notification_method)
1315 {
1316 let _ = notification_tx.send(result);
1317 }
1318 }
1319 _ => return Ok(()),
1320 }
1321 }
1322 }
1323
1324 let msg = tokio::select! {
1325 m = ws.next() => m,
1326 _ = stop_rx.changed() => continue,
1327 };
1328
1329 match msg {
1330 Some(Ok(Message::Text(text))) => {
1331 if is_subscription_complete_message(&text) {
1332 return Ok(());
1333 }
1334 if let Some(result) =
1335 parse_notification_message::<N>(&text, stream.notification_method)
1336 {
1337 let _ = notification_tx.send(result);
1338 }
1339 }
1340 Some(Ok(_)) => {}
1341 _ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
1342 }
1343 }
1344}
1345
1346pub struct ActionSubscriptionHandle {
1353 pub join_handle: SubscriptionTaskHandle,
1355 pub stop: watch::Sender<bool>,
1357}
1358
1359pub async fn subscribe_actions<F, Fut>(
1390 rpc_endpoint: &str,
1391 on_notification: F,
1392) -> Result<ActionSubscriptionHandle, SubscriptionError>
1393where
1394 F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
1395 Fut: Future<Output = ()> + Send + 'static,
1396{
1397 let SubscriptionHandle { join_handle, stop } =
1398 subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
1399 Ok(ActionSubscriptionHandle { join_handle, stop })
1400}
1401
1402#[derive(Debug, Clone, Serialize, Deserialize)]
1406pub struct DiagnosticContext {
1407 pub slot: u64,
1409}
1410
1411#[derive(Debug, Clone, Serialize, Deserialize)]
1416#[serde(rename_all = "camelCase")]
1417pub struct DiagnosticNotification {
1418 #[allow(missing_docs)]
1419 pub context: DiagnosticContext,
1420 pub slot: u64,
1422 pub probe_index: u32,
1424 #[serde(default)]
1426 pub label: Option<String>,
1427 pub market: String,
1429 pub usd_value: u32,
1431 #[serde(default)]
1433 pub pairs: Vec<[String; 2]>,
1434 #[serde(default)]
1437 pub router_slot: Option<u64>,
1438 #[serde(default)]
1440 pub results: Option<serde_json::Value>,
1441 #[serde(default)]
1443 pub account_hashes: Vec<String>,
1444 #[serde(default)]
1446 pub err: Option<String>,
1447}
1448
1449pub struct DiagnosticSubscriptionHandle {
1454 pub join_handle: SubscriptionTaskHandle,
1456 pub stop: watch::Sender<bool>,
1458}
1459
1460pub async fn subscribe_diagnostics<F, Fut>(
1470 rpc_endpoint: &str,
1471 on_notification: F,
1472) -> Result<DiagnosticSubscriptionHandle, SubscriptionError>
1473where
1474 F: Fn(DiagnosticNotification) -> Fut + Send + Sync + 'static,
1475 Fut: Future<Output = ()> + Send + 'static,
1476{
1477 let SubscriptionHandle { join_handle, stop } =
1478 subscribe_notifications(rpc_endpoint, DIAGNOSTIC_STREAM, on_notification).await?;
1479 Ok(DiagnosticSubscriptionHandle { join_handle, stop })
1480}
1481
1482pub use simulator_api::replacement::{
1488 L1Score, OriginalNotification, ProbedHop, ReplacementContext, ReplacementCore,
1489 ReplacementNotification, RequoteNotification, RerouteLegNotification, VenueNotification,
1490};
1491
1492pub async fn subscribe_replacements<F, Fut>(
1534 rpc_endpoint: &str,
1535 on_notification: F,
1536) -> Result<SubscriptionHandle, SubscriptionError>
1537where
1538 F: Fn(ReplacementNotification) -> Fut + Send + Sync + 'static,
1539 Fut: Future<Output = ()> + Send + 'static,
1540{
1541 subscribe_notifications(rpc_endpoint, REPLACEMENT_STREAM, on_notification).await
1542}
1543
1544#[cfg(test)]
1545mod tests {
1546 use rstest::rstest;
1547
1548 use super::*;
1549
1550 #[test]
1551 fn parse_account_diff_notification_ignores_other_messages() {
1552 let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
1553 assert!(parse_account_diff_message(confirmation).is_none());
1554 }
1555
1556 #[test]
1557 fn parse_account_diff_notification_extracts_payload() {
1558 let text = r#"{
1559 "jsonrpc":"2.0",
1560 "method":"accountDiffNotification",
1561 "params":{
1562 "subscription":7,
1563 "result":{
1564 "context":{"slot":123},
1565 "signature":"sig",
1566 "pre":{"a":1},
1567 "post":{"a":2}
1568 }
1569 }
1570 }"#;
1571
1572 let notification = parse_account_diff_message(text)
1573 .expect("notification")
1574 .params
1575 .result;
1576 assert_eq!(notification.context.slot, 123);
1577 assert_eq!(notification.signature.as_deref(), Some("sig"));
1578 assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
1579 assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
1580 }
1581
1582 #[test]
1583 fn parse_routed_account_diff_notification_extracts_subscription_account() {
1584 let text = r#"{
1585 "jsonrpc":"2.0",
1586 "method":"accountDiffNotification",
1587 "params":{
1588 "subscription":42,
1589 "result":{
1590 "context":{"slot":456},
1591 "signature":"sig",
1592 "pre":null,
1593 "post":{"a":2}
1594 }
1595 }
1596 }"#;
1597 let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
1598
1599 let notification =
1600 parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
1601 assert_eq!(notification.account, "acct");
1602 assert_eq!(notification.notification.context.slot, 456);
1603 }
1604
1605 #[test]
1606 fn converts_ui_account_json() {
1607 let value = serde_json::json!({
1608 "lamports": 5,
1609 "data": ["AQID", "base64"],
1610 "owner": "11111111111111111111111111111111",
1611 "executable": false,
1612 "rentEpoch": 0,
1613 });
1614 let account = account_data_from_ui(&value).unwrap();
1615 assert_eq!(account.lamports, 5);
1616 assert_eq!(account.space, 3);
1617 assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
1618 }
1619
1620 #[test]
1621 fn rejects_non_base64_encodings() {
1622 let value = serde_json::json!({
1623 "lamports": 5,
1624 "data": ["{}", "jsonParsed"],
1625 "owner": "11111111111111111111111111111111",
1626 "executable": false,
1627 "rentEpoch": 0,
1628 });
1629 assert!(matches!(
1630 account_data_from_ui(&value),
1631 Err(UiAccountConversionError::UnsupportedEncoding)
1632 ));
1633 }
1634
1635 fn action_result(
1636 errors: &[Option<&str>],
1637 accounts: Vec<Option<serde_json::Value>>,
1638 ) -> ActionResultNotification {
1639 ActionResultNotification {
1640 context: ActionResultContext { slot: 0 },
1641 slot: 0,
1642 batch_index: None,
1643 tx_index: None,
1644 batch_last_tx_index: None,
1645 block_time: None,
1646 action_index: 0,
1647 label: None,
1648 committed: false,
1649 transaction_outcomes: errors
1650 .iter()
1651 .map(|err| ActionTransactionOutcome {
1652 err: err.map(str::to_owned),
1653 logs: Vec::new(),
1654 units_consumed: 0,
1655 fee: None,
1656 return_data: None,
1657 unresolved: false,
1658 })
1659 .collect(),
1660 accounts,
1661 matched: None,
1662 }
1663 }
1664
1665 #[rstest]
1666 #[case::no_outcomes(&[], None)]
1667 #[case::one_ok(&[None], None)]
1668 #[case::all_ok(&[None, None], None)]
1669 #[case::one_err(&[Some("boom")], Some("boom"))]
1670 #[case::second_hop_err(&[None, Some("hop2")], Some("hop2"))]
1671 fn action_failure_is_the_last_failing_outcome(
1672 #[case] errors: &[Option<&str>],
1673 #[case] expected: Option<&str>,
1674 ) {
1675 let result = action_result(errors, Vec::new());
1676 assert_eq!(result.failure().and_then(|o| o.err.as_deref()), expected);
1677 }
1678
1679 #[rstest]
1680 #[case::base64(0, Some(Ok(5)))]
1681 #[case::missing_account(1, None)]
1682 #[case::json_parsed(2, Some(Err(UiAccountConversionError::UnsupportedEncoding.to_string())))]
1683 #[case::past_return_accounts(3, None)]
1684 fn returned_account_reads_positional_entries(
1685 #[case] index: usize,
1686 #[case] expected: Option<Result<u64, String>>,
1687 ) {
1688 let ui_account = |data| {
1689 serde_json::json!({
1690 "lamports": 5,
1691 "data": data,
1692 "owner": "11111111111111111111111111111111",
1693 "executable": false,
1694 "rentEpoch": 0,
1695 })
1696 };
1697 let result = action_result(
1698 &[],
1699 vec![
1700 Some(ui_account(serde_json::json!(["AQID", "base64"]))),
1701 None,
1702 Some(ui_account(serde_json::json!(["{}", "jsonParsed"]))),
1703 ],
1704 );
1705 let lamports = result
1706 .returned_account(index)
1707 .map(|account| account.map(|a| a.lamports).map_err(|e| e.to_string()));
1708 assert_eq!(lamports, expected);
1709 }
1710
1711 #[test]
1712 fn dedup_accounts_preserves_first_seen_order() {
1713 let accounts = dedup_accounts([
1714 "b".to_string(),
1715 "a".to_string(),
1716 "b".to_string(),
1717 "c".to_string(),
1718 ]);
1719 assert_eq!(accounts, vec!["b", "a", "c"]);
1720 }
1721
1722 fn fixture_signature() -> String {
1724 simulator_api::replacement::Signature::default().to_string()
1725 }
1726
1727 fn route_hop(set: serde_json::Value, program: serde_json::Value) -> serde_json::Value {
1729 use serde_json::json;
1730
1731 let mut swap_info = json!({
1732 "label": null, "ammKey": null, "inputMint": null,
1733 "inAmount": null, "outputMint": null, "outAmount": null,
1734 });
1735 for (key, value) in set.as_object().expect("an object") {
1736 swap_info[key] = value.clone();
1737 }
1738 json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
1739 }
1740
1741 #[test]
1744 fn a_requote_notification_round_trips_through_its_own_encoding() {
1745 use serde_json::{Value, json};
1746
1747 let wire = serde_json::json!({
1748 "kind": "requote",
1749 "context": {"slot": 42},
1750 "slot": 42,
1751 "batchIndex": 3,
1752 "originalSignature": fixture_signature(),
1753 "originalFailed": false,
1754 "outcome": "filled",
1755 "legs": [{
1756 "inputMint": simulator_api::mints::SOL.to_string(),
1757 "outputMint": simulator_api::mints::USDC.to_string(),
1758 "amount": 1_000,
1759 "swapMode": "ExactIn",
1760 "originalQuotedOut": 990,
1761 "metisQuotedOut": 1_010,
1762 "routeSummary": "SolFi",
1763 "routePlan": [route_hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
1765 "originalRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
1766 "realizedRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
1767 }],
1768 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1769 "logs": ["Program log: swap"],
1770 "computeUnitsConsumed": 123_456,
1771 "fee": 5_000,
1772 "realizedOutputAmount": 1_009,
1773 "originalRealizedOutputAmount": 991,
1774 });
1775
1776 let notification: ReplacementNotification =
1777 serde_json::from_value(wire.clone()).expect("wire decodes");
1778 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1779 assert_eq!(recorded, wire);
1780
1781 let ReplacementNotification::Requote(read_back) =
1782 serde_json::from_value::<ReplacementNotification>(recorded).expect("recording decodes")
1783 else {
1784 panic!("kind=requote must decode to the Requote variant");
1785 };
1786 assert_eq!(read_back.core.batch_index, 3);
1787 assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
1788 assert_eq!(read_back.original_realized_output_amount, Some(991));
1789 assert!(
1792 read_back
1793 .legs
1794 .iter()
1795 .all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
1796 );
1797 }
1798
1799 #[test]
1801 fn a_venue_notification_round_trips_through_its_own_encoding() {
1802 let wire = serde_json::json!({
1803 "kind": "directFill",
1804 "context": {"slot": 7},
1805 "slot": 7,
1806 "batchIndex": 1,
1807 "originalSignature": fixture_signature(),
1808 "originalFailed": false,
1809 "template": "venue-a",
1810 "program": simulator_api::mints::USDC.to_string(),
1811 "hop": {
1812 "slot": 9,
1813 "blockTime": 1_767_225_600i64,
1814 "txIndex": 4,
1815 "ixIndex": 0,
1816 "legIndex": 0,
1817 "program": simulator_api::mints::SOL.to_string(),
1818 "inputAmount": 1_000,
1819 "outputAmount": 1_000,
1820 "replayInputAmount": 1_000,
1821 "replayOutputAmount": 1_005,
1822 },
1823 "quoteTxIndex": 1,
1824 "quoteLagBlocks": 2,
1825 "inputMint": simulator_api::mints::SOL.to_string(),
1826 "outputMint": simulator_api::mints::USDC.to_string(),
1827 "amount": 1_000,
1828 "swapMode": "ExactIn",
1829 "templateFill": 1_010,
1830 "l1Fill": 1_000,
1831 "changeVsL1Bps": 100,
1832 "outcome": "filled",
1833 });
1834
1835 let notification: ReplacementNotification =
1836 serde_json::from_value(wire.clone()).expect("wire decodes");
1837 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1838 assert_eq!(recorded, wire);
1839
1840 let ReplacementNotification::Venue(read_back) = notification else {
1841 panic!("kind=directFill must decode to the Venue variant");
1842 };
1843 assert_eq!(read_back.template, "venue-a");
1844 assert_eq!(read_back.template_fill, Some(1_010));
1845 assert_eq!(read_back.comparison.l1_fill, Some(1_000));
1846 assert_eq!(read_back.comparison.change_vs_l1_bps, Some(100));
1847 assert!(
1848 read_back.core.category.is_none(),
1849 "a filled probe carries no category"
1850 );
1851 }
1852
1853 #[test]
1859 fn an_original_notification_round_trips_through_its_own_encoding() {
1860 let wire = serde_json::json!({
1861 "kind": "original",
1862 "context": {"slot": 9},
1863 "slot": 9,
1864 "batchIndex": 2,
1865 "originalSignature": fixture_signature(),
1866 "originalFailed": false,
1867 "l1Fill": 2_000,
1868 "changeVsL1Bps": -25,
1869 "computeUnitsConsumed": 31_400,
1870 "fee": 5_000,
1871 "simulatedOutputAmount": 1_995,
1872 "outcome": "filled",
1873 });
1874
1875 let notification: ReplacementNotification =
1876 serde_json::from_value(wire.clone()).expect("wire decodes");
1877
1878 let ReplacementNotification::Original(read_back) = notification else {
1879 panic!("kind=original must decode to the Original variant");
1880 };
1881 assert_eq!(read_back.core.slot, 9);
1882 assert_eq!(
1883 read_back.core.original_signature.to_string(),
1884 fixture_signature()
1885 );
1886 assert_eq!(read_back.comparison.l1_fill, Some(2_000));
1887 assert_eq!(read_back.comparison.change_vs_l1_bps, Some(-25));
1888 assert_eq!(read_back.cost.compute_units_consumed, 31_400);
1889 assert_eq!(read_back.simulated_output_amount, Some(1_995));
1890 assert_eq!(read_back.core.outcome, "filled");
1891 }
1892
1893 #[test]
1896 fn an_untagged_old_format_payload_fails_to_deserialize() {
1897 let old_wire = serde_json::json!({
1898 "context": {"slot": 42},
1899 "slot": 42,
1900 "batchIndex": 3,
1901 "originalSignature": fixture_signature(),
1902 "legs": [],
1903 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1904 "err": serde_json::Value::Null,
1905 "logs": [],
1906 "computeUnitsConsumed": 0,
1907 "fee": serde_json::Value::Null,
1908 "realizedOutputAmount": serde_json::Value::Null,
1909 "originalRealizedOutputAmount": serde_json::Value::Null,
1910 "originalFailed": false,
1911 });
1912
1913 let err = serde_json::from_value::<ReplacementNotification>(old_wire).expect_err(
1914 "an untagged old-format payload must not deserialize as a ReplacementNotification",
1915 );
1916 assert!(
1917 err.to_string().contains("kind"),
1918 "must fail on the missing tag, not misparse into either variant: {err}"
1919 );
1920 }
1921}