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 tx::{TxDecodeError, decode_transaction},
44 urls::{UrlError, http_to_ws_url},
45};
46
47#[derive(Debug, Error)]
50#[allow(missing_docs)]
51pub enum SubscriptionError {
52 #[error(transparent)]
55 InvalidUrl(#[from] UrlError),
56
57 #[error("pubsub connect to {url} failed: {source}")]
61 Connect {
62 url: String,
64 #[source]
65 source: Box<dyn std::error::Error + Send + Sync>,
66 },
67
68 #[error("logs_subscribe failed: {source}")]
71 Subscribe {
72 #[source]
74 source: Box<dyn std::error::Error + Send + Sync>,
75 },
76
77 #[error("subscription task exited unexpectedly before signaling ready")]
80 TaskDropped,
81
82 #[error("session has no rpc_endpoint (was the session created?)")]
84 NoRpcEndpoint,
85}
86
87#[derive(Debug, Error)]
92pub enum SubscriptionRuntimeError {
93 #[error("{kind} subscription for {target} closed unexpectedly")]
98 Closed {
99 kind: &'static str,
101 target: String,
103 },
104
105 #[error("{kind} subscription callback worker for {target} failed: {source}")]
108 CallbackWorker {
109 kind: &'static str,
111 target: String,
113 #[source]
115 source: tokio::task::JoinError,
116 },
117
118 #[error("subscription task failed: {0}")]
121 Task(#[from] tokio::task::JoinError),
122}
123
124const SUBSCRIPTION_DRAIN_IDLE_TIMEOUT: Duration = Duration::from_millis(250);
125const SUBSCRIPTION_DRAIN_MAX_DURATION: Duration = Duration::from_secs(5);
126
127type SubscriptionTaskHandle = JoinHandle<Result<(), SubscriptionRuntimeError>>;
128type AccountDiffWs =
129 tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
130
131pub struct SubscriptionHandle {
136 pub join_handle: SubscriptionTaskHandle,
139 pub stop: watch::Sender<bool>,
142}
143
144impl SubscriptionHandle {
145 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
154 self.stop.send_replace(true);
156 self.join_handle.await?
157 }
158}
159
160impl LogSubscriptionHandle {
161 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
163 SubscriptionHandle::from(self).shutdown().await
164 }
165}
166
167impl From<LogSubscriptionHandle> for SubscriptionHandle {
168 fn from(h: LogSubscriptionHandle) -> Self {
169 Self {
170 join_handle: h.join_handle,
171 stop: h.stop,
172 }
173 }
174}
175
176impl AccountDiffSubscriptionHandle {
177 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
179 SubscriptionHandle::from(self).shutdown().await
180 }
181}
182
183impl From<AccountDiffSubscriptionHandle> for SubscriptionHandle {
184 fn from(h: AccountDiffSubscriptionHandle) -> Self {
185 Self {
186 join_handle: h.join_handle,
187 stop: h.stop,
188 }
189 }
190}
191
192impl ActionSubscriptionHandle {
193 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
195 SubscriptionHandle::from(self).shutdown().await
196 }
197}
198
199impl From<ActionSubscriptionHandle> for SubscriptionHandle {
200 fn from(h: ActionSubscriptionHandle) -> Self {
201 Self {
202 join_handle: h.join_handle,
203 stop: h.stop,
204 }
205 }
206}
207
208impl DiagnosticSubscriptionHandle {
209 pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
211 SubscriptionHandle::from(self).shutdown().await
212 }
213}
214
215impl From<DiagnosticSubscriptionHandle> for SubscriptionHandle {
216 fn from(h: DiagnosticSubscriptionHandle) -> Self {
217 Self {
218 join_handle: h.join_handle,
219 stop: h.stop,
220 }
221 }
222}
223
224pub struct LogSubscriptionHandle {
229 pub join_handle: SubscriptionTaskHandle,
232
233 pub stop: watch::Sender<bool>,
236}
237
238pub async fn subscribe_program_logs<F, Fut>(
277 rpc_endpoint: &str,
278 program_id: &str,
279 commitment: CommitmentConfig,
280 on_notification: F,
281) -> Result<LogSubscriptionHandle, SubscriptionError>
282where
283 F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
284 Fut: Future<Output = ()> + Send + 'static,
285{
286 let ws_url = http_to_ws_url(rpc_endpoint)?;
287 let program_id = program_id.to_string();
288
289 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
290 let (stop_tx, mut stop_rx) = watch::channel(false);
291
292 let join_handle = tokio::spawn(async move {
296 let client = match PubsubClient::new(&ws_url).await {
297 Ok(c) => c,
298 Err(e) => {
299 let _ = ready_tx.send(Err(SubscriptionError::Connect {
300 url: ws_url,
301 source: Box::new(e),
302 }));
303 return Ok(());
304 }
305 };
306
307 let (mut stream, _unsubscribe) = match client
308 .logs_subscribe(
309 RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
310 RpcTransactionLogsConfig {
311 commitment: Some(commitment),
312 },
313 )
314 .await
315 {
316 Ok(s) => s,
317 Err(e) => {
318 let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
319 source: Box::new(e),
320 }));
321 return Ok(());
322 }
323 };
324
325 let _ = ready_tx.send(Ok(()));
326
327 let mut tasks: Vec<JoinHandle<()>> = Vec::new();
328 let kind = "program logs";
329
330 loop {
331 if *stop_rx.borrow() {
332 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
333 while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
334 drain_deadline,
335 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
336 )
337 .await
338 {
339 tasks.push(tokio::spawn(on_notification(notification)));
340 }
341 break;
342 }
343
344 let notification = tokio::select! {
345 n = stream.next() => n,
346 _ = stop_rx.changed() => continue,
347 };
348
349 match notification {
350 Some(n) => tasks.push(tokio::spawn(on_notification(n))),
351 None => return Err(subscription_runtime_closed(kind, &program_id)),
352 }
353 }
354
355 for task in tasks {
357 if let Err(source) = task.await {
358 return Err(callback_worker_failed(kind, &program_id, source));
359 }
360 }
361
362 Ok(())
363 });
364
365 match ready_rx.await {
366 Ok(Ok(())) => Ok(LogSubscriptionHandle {
367 join_handle,
368 stop: stop_tx,
369 }),
370 Ok(Err(e)) => {
371 join_handle.abort();
372 Err(e)
373 }
374 Err(_) => {
375 join_handle.abort();
376 Err(SubscriptionError::TaskDropped)
377 }
378 }
379}
380
381#[derive(Debug, Clone, Deserialize)]
385pub struct AccountDiffContext {
386 #[allow(missing_docs)]
387 pub slot: u64,
388}
389
390#[derive(Debug, Clone, Deserialize)]
395pub struct AccountDiffNotification {
396 #[allow(missing_docs)]
397 pub context: AccountDiffContext,
398 pub account: Option<String>,
400 pub signature: Option<String>,
402 #[serde(default)]
404 pub tx_index: Option<u32>,
405 #[serde(default)]
407 pub block_time: Option<i64>,
408 pub pre: Option<serde_json::Value>,
410 pub post: Option<serde_json::Value>,
412}
413
414impl AccountDiffNotification {
415 pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
417 self.post.as_ref().map(account_data_from_ui)
418 }
419}
420
421#[derive(Debug, Error)]
423pub enum UiAccountConversionError {
424 #[error("payload is not a UiAccount: {0}")]
426 NotAUiAccount(#[from] serde_json::Error),
427
428 #[error("unsupported ui-account data encoding, expected base64")]
430 UnsupportedEncoding,
431
432 #[error("decoding base64 account data: {0}")]
434 Data(#[from] base64::DecodeError),
435
436 #[error("parsing owner address: {0}")]
438 Owner(#[from] solana_address::error::ParseAddressError),
439}
440
441pub fn account_data_from_ui(
449 value: &serde_json::Value,
450) -> Result<AccountData, UiAccountConversionError> {
451 let ui = UiAccount::deserialize(value)?;
452 let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
453 return Err(UiAccountConversionError::UnsupportedEncoding);
454 };
455 let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
456 let space = match ui.space {
457 Some(space) => space,
458 None => encoded.decode()?.len() as u64,
459 };
460 Ok(AccountData {
461 data: encoded,
462 executable: ui.executable,
463 lamports: ui.lamports,
464 owner: ui.owner.parse()?,
465 space,
466 })
467}
468
469#[derive(Debug, Clone, Deserialize)]
471pub struct ActionResultContext {
472 pub slot: u64,
474}
475
476#[derive(Debug, Clone, Deserialize)]
478#[serde(rename_all = "camelCase")]
479pub struct ActionResultNotification {
480 #[allow(missing_docs)]
481 pub context: ActionResultContext,
482 pub slot: u64,
484 #[serde(default)]
486 pub batch_index: Option<u32>,
487 #[serde(default)]
490 pub tx_index: Option<u32>,
491 #[serde(default)]
493 pub batch_last_tx_index: Option<u32>,
494 #[serde(default)]
496 pub block_time: Option<i64>,
497 pub action_index: u32,
499 #[serde(default)]
501 pub label: Option<String>,
502 pub committed: bool,
505 #[serde(default)]
508 pub transaction_outcomes: Vec<ActionTransactionOutcome>,
509 #[serde(default)]
512 pub accounts: Vec<Option<serde_json::Value>>,
513 #[serde(default)]
517 pub matched: Option<EncodedBinary>,
518}
519
520impl ActionResultNotification {
521 pub fn failure(&self) -> Option<&ActionTransactionOutcome> {
523 self.transaction_outcomes.last().filter(|o| o.err.is_some())
525 }
526
527 pub fn returned_account(
530 &self,
531 index: usize,
532 ) -> Option<Result<AccountData, UiAccountConversionError>> {
533 self.accounts.get(index)?.as_ref().map(account_data_from_ui)
534 }
535
536 pub fn matched_transaction(&self) -> Option<Result<VersionedTransaction, TxDecodeError>> {
538 self.matched.as_ref().map(decode_transaction)
539 }
540}
541
542#[derive(Debug, Clone, Deserialize)]
544#[serde(rename_all = "camelCase")]
545pub struct ActionTransactionOutcome {
546 #[serde(default)]
548 pub err: Option<String>,
549 #[serde(default)]
550 #[allow(missing_docs)]
551 pub logs: Vec<String>,
552 #[allow(missing_docs)]
553 pub units_consumed: u64,
554 #[serde(default)]
556 pub fee: Option<u64>,
557 #[serde(default)]
559 pub return_data: Option<serde_json::Value>,
560 #[serde(default)]
563 pub unresolved: bool,
564}
565
566#[derive(Debug, Clone)]
569pub struct RoutedAccountDiffNotification {
570 pub account: String,
572 #[allow(missing_docs)]
573 pub notification: AccountDiffNotification,
574}
575
576pub struct AccountDiffSubscriptionHandle {
581 pub join_handle: SubscriptionTaskHandle,
583 pub stop: watch::Sender<bool>,
585}
586
587fn subscription_runtime_closed(
588 kind: &'static str,
589 target: impl Into<String>,
590) -> SubscriptionRuntimeError {
591 SubscriptionRuntimeError::Closed {
592 kind,
593 target: target.into(),
594 }
595}
596
597fn callback_worker_failed(
598 kind: &'static str,
599 target: impl Into<String>,
600 source: tokio::task::JoinError,
601) -> SubscriptionRuntimeError {
602 SubscriptionRuntimeError::CallbackWorker {
603 kind,
604 target: target.into(),
605 source,
606 }
607}
608
609pub async fn subscribe_account_diffs<F, Fut>(
640 rpc_endpoint: &str,
641 account: &str,
642 on_notification: F,
643) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
644where
645 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
646 Fut: Future<Output = ()> + Send + 'static,
647{
648 subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
649 on_notification(notification.notification)
650 })
651 .await
652}
653
654pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
665 rpc_endpoint: &str,
666 accounts: I,
667 on_notification: F,
668) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
669where
670 F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
671 Fut: Future<Output = ()> + Send + 'static,
672 I: IntoIterator<Item = S>,
673 S: Into<String>,
674{
675 let ws_url = http_to_ws_url(rpc_endpoint)?;
676 let accounts = dedup_accounts(accounts);
677 if accounts.is_empty() {
678 let (stop_tx, stop_rx) = watch::channel(false);
679 return Ok(AccountDiffSubscriptionHandle {
680 join_handle: tokio::spawn(async move {
681 let _ = stop_rx;
682 Ok(())
683 }),
684 stop: stop_tx,
685 });
686 }
687
688 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
689 let (stop_tx, mut stop_rx) = watch::channel(false);
690 let target = format!("{} accounts", accounts.len());
691
692 let join_handle = tokio::spawn(async move {
693 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
694 let callback_handle = tokio::spawn(async move {
695 while let Some(notification) = notification_rx.recv().await {
696 on_notification(notification).await;
697 }
698 });
699
700 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
701 Ok(connection) => connection,
702 Err(e) => {
703 let _ = ready_tx.send(Err(SubscriptionError::Connect {
704 url: ws_url,
705 source: Box::new(e),
706 }));
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 {
969 url: ws_url,
970 source: Box::new(e),
971 }));
972 return Ok(());
973 }
974 };
975
976 if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
977 let _ = ready_tx.send(Err(error));
978 return Ok(());
979 }
980
981 let _ = ready_tx.send(Ok(()));
982
983 if let Err(error) =
984 drive_program_diff_stream(&mut ws, ¬ification_tx, &mut stop_rx, &program_id).await
985 {
986 drop(notification_tx);
987 if let Err(source) = callback_handle.await {
988 return Err(callback_worker_failed(
989 "program account diff",
990 &program_id,
991 source,
992 ));
993 }
994 return Err(error);
995 }
996
997 drop(notification_tx);
998 if let Err(source) = callback_handle.await {
999 return Err(callback_worker_failed(
1000 "program account diff",
1001 &program_id,
1002 source,
1003 ));
1004 }
1005
1006 Ok(())
1007 });
1008
1009 match ready_rx.await {
1010 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
1011 join_handle,
1012 stop: stop_tx,
1013 }),
1014 Ok(Err(e)) => {
1015 join_handle.abort();
1016 Err(e)
1017 }
1018 Err(_) => {
1019 join_handle.abort();
1020 Err(SubscriptionError::TaskDropped)
1021 }
1022 }
1023}
1024
1025async fn send_program_diff_subscribe(
1026 ws: &mut AccountDiffWs,
1027 program_id: &str,
1028) -> Result<(), SubscriptionError> {
1029 #[derive(Deserialize)]
1030 struct SubscriptionConfirmation {
1031 result: Option<u64>,
1032 }
1033
1034 let req = serde_json::json!({
1035 "jsonrpc": "2.0",
1036 "id": 1,
1037 "method": "accountDiffSubscribe",
1038 "params": [program_id, {"address_type": "program"}]
1039 });
1040 ws.send(Message::Text(req.to_string()))
1041 .await
1042 .map_err(|source| SubscriptionError::Subscribe {
1043 source: Box::new(source),
1044 })?;
1045
1046 loop {
1047 match ws.next().await {
1048 Some(Ok(Message::Text(text))) => {
1049 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1050 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1051 Ok(_) => continue,
1052 Err(source) => {
1053 return Err(SubscriptionError::Subscribe {
1054 source: Box::new(source),
1055 });
1056 }
1057 }
1058 }
1059 Some(Ok(_)) => continue,
1060 _ => return Err(SubscriptionError::TaskDropped),
1061 }
1062 }
1063}
1064
1065async fn drive_program_diff_stream(
1066 ws: &mut AccountDiffWs,
1067 notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
1068 stop_rx: &mut watch::Receiver<bool>,
1069 program_id: &str,
1070) -> Result<(), SubscriptionRuntimeError> {
1071 loop {
1072 if *stop_rx.borrow() {
1073 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1074 loop {
1075 match tokio::time::timeout_at(
1076 drain_deadline,
1077 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1078 )
1079 .await
1080 {
1081 Ok(Ok(Some(Ok(Message::Text(text))))) => {
1082 if let Some(msg) = parse_account_diff_message(&text) {
1083 let _ = notification_tx.send(msg.params.result);
1084 }
1085 }
1086 _ => return Ok(()),
1087 }
1088 }
1089 }
1090
1091 let msg = tokio::select! {
1092 m = ws.next() => m,
1093 _ = stop_rx.changed() => continue,
1094 };
1095
1096 match msg {
1097 Some(Ok(Message::Text(text))) => {
1098 if let Some(msg) = parse_account_diff_message(&text) {
1099 let _ = notification_tx.send(msg.params.result);
1100 }
1101 }
1102 Some(Ok(_)) => {}
1103 _ => {
1104 return Err(subscription_runtime_closed(
1105 "program account diff",
1106 program_id,
1107 ));
1108 }
1109 }
1110 }
1111}
1112
1113#[derive(Clone, Copy)]
1117struct NotificationStream {
1118 subscribe_method: &'static str,
1119 notification_method: &'static str,
1120 kind: &'static str,
1122 target: &'static str,
1124}
1125
1126const ACTION_STREAM: NotificationStream = NotificationStream {
1127 subscribe_method: "actionSubscribe",
1128 notification_method: "actionNotification",
1129 kind: "action",
1130 target: "actions",
1131};
1132
1133const REPLACEMENT_STREAM: NotificationStream = NotificationStream {
1134 subscribe_method: "replacementSubscribe",
1135 notification_method: "replacementNotification",
1136 kind: "replacement",
1137 target: "replacements",
1138};
1139
1140const DIAGNOSTIC_STREAM: NotificationStream = NotificationStream {
1141 subscribe_method: "diagnosticSubscribe",
1142 notification_method: "diagnosticNotification",
1143 kind: "diagnostic",
1144 target: "diagnostics",
1145};
1146
1147#[derive(Deserialize)]
1148struct NotificationMessage<N> {
1149 method: String,
1150 params: NotificationParams<N>,
1151}
1152
1153#[derive(Deserialize)]
1154struct NotificationParams<N> {
1155 #[allow(dead_code)]
1156 subscription: u64,
1157 result: N,
1158}
1159
1160fn parse_notification_message<N: DeserializeOwned>(
1161 text: &str,
1162 notification_method: &str,
1163) -> Option<N> {
1164 let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
1165 (msg.method == notification_method).then_some(msg.params.result)
1166}
1167
1168fn is_subscription_complete_message(text: &str) -> bool {
1169 #[derive(Deserialize)]
1170 struct SubscriptionCompleteMessage {
1171 method: String,
1172 }
1173
1174 serde_json::from_str::<SubscriptionCompleteMessage>(text)
1175 .is_ok_and(|msg| msg.method == "subscriptionComplete")
1176}
1177
1178async fn subscribe_notifications<N, F, Fut>(
1183 rpc_endpoint: &str,
1184 stream: NotificationStream,
1185 on_notification: F,
1186) -> Result<SubscriptionHandle, SubscriptionError>
1187where
1188 N: DeserializeOwned + Send + 'static,
1189 F: Fn(N) -> Fut + Send + Sync + 'static,
1190 Fut: Future<Output = ()> + Send + 'static,
1191{
1192 let ws_url = http_to_ws_url(rpc_endpoint)?;
1193
1194 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
1195 let (stop_tx, mut stop_rx) = watch::channel(false);
1196
1197 let join_handle = tokio::spawn(async move {
1198 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
1199 let callback_handle = tokio::spawn(async move {
1200 while let Some(notification) = notification_rx.recv().await {
1201 on_notification(notification).await;
1202 }
1203 });
1204
1205 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
1206 Ok(connection) => connection,
1207 Err(e) => {
1208 let _ = ready_tx.send(Err(SubscriptionError::Connect {
1209 url: ws_url,
1210 source: Box::new(e),
1211 }));
1212 return Ok(());
1213 }
1214 };
1215
1216 if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
1217 let _ = ready_tx.send(Err(error));
1218 return Ok(());
1219 }
1220
1221 let _ = ready_tx.send(Ok(()));
1222
1223 if let Err(error) =
1224 drive_notification_stream::<N>(&mut ws, stream, ¬ification_tx, &mut stop_rx).await
1225 {
1226 drop(notification_tx);
1227 if let Err(source) = callback_handle.await {
1228 return Err(callback_worker_failed(stream.kind, stream.target, source));
1229 }
1230 return Err(error);
1231 }
1232
1233 drop(notification_tx);
1234 if let Err(source) = callback_handle.await {
1235 return Err(callback_worker_failed(stream.kind, stream.target, source));
1236 }
1237
1238 Ok(())
1239 });
1240
1241 match ready_rx.await {
1242 Ok(Ok(())) => Ok(SubscriptionHandle {
1243 join_handle,
1244 stop: stop_tx,
1245 }),
1246 Ok(Err(e)) => {
1247 join_handle.abort();
1248 Err(e)
1249 }
1250 Err(_) => {
1251 join_handle.abort();
1252 Err(SubscriptionError::TaskDropped)
1253 }
1254 }
1255}
1256
1257async fn send_stream_subscribe(
1258 ws: &mut AccountDiffWs,
1259 subscribe_method: &str,
1260) -> Result<(), SubscriptionError> {
1261 #[derive(Deserialize)]
1262 struct SubscriptionConfirmation {
1263 result: Option<u64>,
1264 }
1265
1266 let req = serde_json::json!({
1268 "jsonrpc": "2.0",
1269 "id": 1,
1270 "method": subscribe_method,
1271 "params": [serde_json::Value::Null, {}]
1272 });
1273
1274 ws.send(Message::Text(req.to_string()))
1275 .await
1276 .map_err(|source| SubscriptionError::Subscribe {
1277 source: Box::new(source),
1278 })?;
1279
1280 loop {
1281 match ws.next().await {
1282 Some(Ok(Message::Text(text))) => {
1283 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1284 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1285 Ok(_) => continue,
1286 Err(source) => {
1287 return Err(SubscriptionError::Subscribe {
1288 source: Box::new(source),
1289 });
1290 }
1291 }
1292 }
1293 Some(Ok(_)) => continue,
1294 _ => return Err(SubscriptionError::TaskDropped),
1295 }
1296 }
1297}
1298
1299async fn drive_notification_stream<N: DeserializeOwned>(
1300 ws: &mut AccountDiffWs,
1301 stream: NotificationStream,
1302 notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
1303 stop_rx: &mut watch::Receiver<bool>,
1304) -> Result<(), SubscriptionRuntimeError> {
1305 loop {
1306 if *stop_rx.borrow() {
1307 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1308 loop {
1309 match tokio::time::timeout_at(
1310 drain_deadline,
1311 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1312 )
1313 .await
1314 {
1315 Ok(Ok(Some(Ok(Message::Text(text))))) => {
1316 if is_subscription_complete_message(&text) {
1317 return Ok(());
1318 }
1319 if let Some(result) =
1320 parse_notification_message::<N>(&text, stream.notification_method)
1321 {
1322 let _ = notification_tx.send(result);
1323 }
1324 }
1325 _ => return Ok(()),
1326 }
1327 }
1328 }
1329
1330 let msg = tokio::select! {
1331 m = ws.next() => m,
1332 _ = stop_rx.changed() => continue,
1333 };
1334
1335 match msg {
1336 Some(Ok(Message::Text(text))) => {
1337 if is_subscription_complete_message(&text) {
1338 return Ok(());
1339 }
1340 if let Some(result) =
1341 parse_notification_message::<N>(&text, stream.notification_method)
1342 {
1343 let _ = notification_tx.send(result);
1344 }
1345 }
1346 Some(Ok(_)) => {}
1347 _ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
1348 }
1349 }
1350}
1351
1352pub struct ActionSubscriptionHandle {
1359 pub join_handle: SubscriptionTaskHandle,
1361 pub stop: watch::Sender<bool>,
1363}
1364
1365pub async fn subscribe_actions<F, Fut>(
1396 rpc_endpoint: &str,
1397 on_notification: F,
1398) -> Result<ActionSubscriptionHandle, SubscriptionError>
1399where
1400 F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
1401 Fut: Future<Output = ()> + Send + 'static,
1402{
1403 let SubscriptionHandle { join_handle, stop } =
1404 subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
1405 Ok(ActionSubscriptionHandle { join_handle, stop })
1406}
1407
1408#[derive(Debug, Clone, Serialize, Deserialize)]
1412pub struct DiagnosticContext {
1413 pub slot: u64,
1415}
1416
1417#[derive(Debug, Clone, Serialize, Deserialize)]
1422#[serde(rename_all = "camelCase")]
1423pub struct DiagnosticNotification {
1424 #[allow(missing_docs)]
1425 pub context: DiagnosticContext,
1426 pub slot: u64,
1428 pub probe_index: u32,
1430 #[serde(default)]
1432 pub label: Option<String>,
1433 pub market: String,
1435 pub usd_value: u32,
1437 #[serde(default)]
1439 pub pairs: Vec<[String; 2]>,
1440 #[serde(default)]
1443 pub router_slot: Option<u64>,
1444 #[serde(default)]
1446 pub results: Option<serde_json::Value>,
1447 #[serde(default)]
1449 pub account_hashes: Vec<String>,
1450 #[serde(default)]
1452 pub err: Option<String>,
1453}
1454
1455pub struct DiagnosticSubscriptionHandle {
1460 pub join_handle: SubscriptionTaskHandle,
1462 pub stop: watch::Sender<bool>,
1464}
1465
1466pub async fn subscribe_diagnostics<F, Fut>(
1476 rpc_endpoint: &str,
1477 on_notification: F,
1478) -> Result<DiagnosticSubscriptionHandle, SubscriptionError>
1479where
1480 F: Fn(DiagnosticNotification) -> Fut + Send + Sync + 'static,
1481 Fut: Future<Output = ()> + Send + 'static,
1482{
1483 let SubscriptionHandle { join_handle, stop } =
1484 subscribe_notifications(rpc_endpoint, DIAGNOSTIC_STREAM, on_notification).await?;
1485 Ok(DiagnosticSubscriptionHandle { join_handle, stop })
1486}
1487
1488pub use simulator_api::replacement::{
1494 L1Score, OriginalNotification, ProbedHop, ReplacementContext, ReplacementCore,
1495 ReplacementNotification, RequoteNotification, RerouteLegNotification, VenueNotification,
1496};
1497
1498pub async fn subscribe_replacements<F, Fut>(
1540 rpc_endpoint: &str,
1541 on_notification: F,
1542) -> Result<SubscriptionHandle, SubscriptionError>
1543where
1544 F: Fn(ReplacementNotification) -> Fut + Send + Sync + 'static,
1545 Fut: Future<Output = ()> + Send + 'static,
1546{
1547 subscribe_notifications(rpc_endpoint, REPLACEMENT_STREAM, on_notification).await
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552 use rstest::rstest;
1553
1554 use super::*;
1555
1556 #[test]
1557 fn parse_account_diff_notification_ignores_other_messages() {
1558 let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
1559 assert!(parse_account_diff_message(confirmation).is_none());
1560 }
1561
1562 #[test]
1563 fn parse_account_diff_notification_extracts_payload() {
1564 let text = r#"{
1565 "jsonrpc":"2.0",
1566 "method":"accountDiffNotification",
1567 "params":{
1568 "subscription":7,
1569 "result":{
1570 "context":{"slot":123},
1571 "signature":"sig",
1572 "pre":{"a":1},
1573 "post":{"a":2}
1574 }
1575 }
1576 }"#;
1577
1578 let notification = parse_account_diff_message(text)
1579 .expect("notification")
1580 .params
1581 .result;
1582 assert_eq!(notification.context.slot, 123);
1583 assert_eq!(notification.signature.as_deref(), Some("sig"));
1584 assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
1585 assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
1586 }
1587
1588 #[test]
1589 fn parse_routed_account_diff_notification_extracts_subscription_account() {
1590 let text = r#"{
1591 "jsonrpc":"2.0",
1592 "method":"accountDiffNotification",
1593 "params":{
1594 "subscription":42,
1595 "result":{
1596 "context":{"slot":456},
1597 "signature":"sig",
1598 "pre":null,
1599 "post":{"a":2}
1600 }
1601 }
1602 }"#;
1603 let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
1604
1605 let notification =
1606 parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
1607 assert_eq!(notification.account, "acct");
1608 assert_eq!(notification.notification.context.slot, 456);
1609 }
1610
1611 #[test]
1612 fn converts_ui_account_json() {
1613 let value = serde_json::json!({
1614 "lamports": 5,
1615 "data": ["AQID", "base64"],
1616 "owner": "11111111111111111111111111111111",
1617 "executable": false,
1618 "rentEpoch": 0,
1619 });
1620 let account = account_data_from_ui(&value).unwrap();
1621 assert_eq!(account.lamports, 5);
1622 assert_eq!(account.space, 3);
1623 assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
1624 }
1625
1626 #[test]
1627 fn rejects_non_base64_encodings() {
1628 let value = serde_json::json!({
1629 "lamports": 5,
1630 "data": ["{}", "jsonParsed"],
1631 "owner": "11111111111111111111111111111111",
1632 "executable": false,
1633 "rentEpoch": 0,
1634 });
1635 assert!(matches!(
1636 account_data_from_ui(&value),
1637 Err(UiAccountConversionError::UnsupportedEncoding)
1638 ));
1639 }
1640
1641 fn action_result(
1642 errors: &[Option<&str>],
1643 accounts: Vec<Option<serde_json::Value>>,
1644 ) -> ActionResultNotification {
1645 ActionResultNotification {
1646 context: ActionResultContext { slot: 0 },
1647 slot: 0,
1648 batch_index: None,
1649 tx_index: None,
1650 batch_last_tx_index: None,
1651 block_time: None,
1652 action_index: 0,
1653 label: None,
1654 committed: false,
1655 transaction_outcomes: errors
1656 .iter()
1657 .map(|err| ActionTransactionOutcome {
1658 err: err.map(str::to_owned),
1659 logs: Vec::new(),
1660 units_consumed: 0,
1661 fee: None,
1662 return_data: None,
1663 unresolved: false,
1664 })
1665 .collect(),
1666 accounts,
1667 matched: None,
1668 }
1669 }
1670
1671 #[rstest]
1672 #[case::no_outcomes(&[], None)]
1673 #[case::one_ok(&[None], None)]
1674 #[case::all_ok(&[None, None], None)]
1675 #[case::one_err(&[Some("boom")], Some("boom"))]
1676 #[case::second_hop_err(&[None, Some("hop2")], Some("hop2"))]
1677 fn action_failure_is_the_last_failing_outcome(
1678 #[case] errors: &[Option<&str>],
1679 #[case] expected: Option<&str>,
1680 ) {
1681 let result = action_result(errors, Vec::new());
1682 assert_eq!(result.failure().and_then(|o| o.err.as_deref()), expected);
1683 }
1684
1685 #[rstest]
1686 #[case::base64(0, Some(Ok(5)))]
1687 #[case::missing_account(1, None)]
1688 #[case::json_parsed(2, Some(Err(UiAccountConversionError::UnsupportedEncoding.to_string())))]
1689 #[case::past_return_accounts(3, None)]
1690 fn returned_account_reads_positional_entries(
1691 #[case] index: usize,
1692 #[case] expected: Option<Result<u64, String>>,
1693 ) {
1694 let ui_account = |data| {
1695 serde_json::json!({
1696 "lamports": 5,
1697 "data": data,
1698 "owner": "11111111111111111111111111111111",
1699 "executable": false,
1700 "rentEpoch": 0,
1701 })
1702 };
1703 let result = action_result(
1704 &[],
1705 vec![
1706 Some(ui_account(serde_json::json!(["AQID", "base64"]))),
1707 None,
1708 Some(ui_account(serde_json::json!(["{}", "jsonParsed"]))),
1709 ],
1710 );
1711 let lamports = result
1712 .returned_account(index)
1713 .map(|account| account.map(|a| a.lamports).map_err(|e| e.to_string()));
1714 assert_eq!(lamports, expected);
1715 }
1716
1717 #[test]
1718 fn dedup_accounts_preserves_first_seen_order() {
1719 let accounts = dedup_accounts([
1720 "b".to_string(),
1721 "a".to_string(),
1722 "b".to_string(),
1723 "c".to_string(),
1724 ]);
1725 assert_eq!(accounts, vec!["b", "a", "c"]);
1726 }
1727
1728 fn fixture_signature() -> String {
1730 simulator_api::replacement::Signature::default().to_string()
1731 }
1732
1733 fn route_hop(set: serde_json::Value, program: serde_json::Value) -> serde_json::Value {
1735 use serde_json::json;
1736
1737 let mut swap_info = json!({
1738 "label": null, "ammKey": null, "inputMint": null,
1739 "inAmount": null, "outputMint": null, "outAmount": null,
1740 });
1741 for (key, value) in set.as_object().expect("an object") {
1742 swap_info[key] = value.clone();
1743 }
1744 json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
1745 }
1746
1747 #[test]
1750 fn a_requote_notification_round_trips_through_its_own_encoding() {
1751 use serde_json::{Value, json};
1752
1753 let wire = serde_json::json!({
1754 "kind": "requote",
1755 "context": {"slot": 42},
1756 "slot": 42,
1757 "batchIndex": 3,
1758 "originalSignature": fixture_signature(),
1759 "originalFailed": false,
1760 "outcome": "filled",
1761 "legs": [{
1762 "inputMint": simulator_api::mints::SOL.to_string(),
1763 "outputMint": simulator_api::mints::USDC.to_string(),
1764 "amount": 1_000,
1765 "swapMode": "ExactIn",
1766 "originalQuotedOut": 990,
1767 "metisQuotedOut": 1_010,
1768 "routeSummary": "SolFi",
1769 "routePlan": [route_hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
1771 "originalRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
1772 "realizedRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
1773 }],
1774 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1775 "logs": ["Program log: swap"],
1776 "computeUnitsConsumed": 123_456,
1777 "fee": 5_000,
1778 "realizedOutputAmount": 1_009,
1779 "originalRealizedOutputAmount": 991,
1780 });
1781
1782 let notification: ReplacementNotification =
1783 serde_json::from_value(wire.clone()).expect("wire decodes");
1784 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1785 assert_eq!(recorded, wire);
1786
1787 let ReplacementNotification::Requote(read_back) =
1788 serde_json::from_value::<ReplacementNotification>(recorded).expect("recording decodes")
1789 else {
1790 panic!("kind=requote must decode to the Requote variant");
1791 };
1792 assert_eq!(read_back.core.batch_index, 3);
1793 assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
1794 assert_eq!(read_back.original_realized_output_amount, Some(991));
1795 assert!(
1798 read_back
1799 .legs
1800 .iter()
1801 .all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
1802 );
1803 }
1804
1805 #[test]
1807 fn a_venue_notification_round_trips_through_its_own_encoding() {
1808 let wire = serde_json::json!({
1809 "kind": "directFill",
1810 "context": {"slot": 7},
1811 "slot": 7,
1812 "batchIndex": 1,
1813 "originalSignature": fixture_signature(),
1814 "originalFailed": false,
1815 "template": "venue-a",
1816 "program": simulator_api::mints::USDC.to_string(),
1817 "hop": {
1818 "slot": 9,
1819 "blockTime": 1_767_225_600i64,
1820 "txIndex": 4,
1821 "ixIndex": 0,
1822 "legIndex": 0,
1823 "program": simulator_api::mints::SOL.to_string(),
1824 "inputAmount": 1_000,
1825 "outputAmount": 1_000,
1826 "replayInputAmount": 1_000,
1827 "replayOutputAmount": 1_005,
1828 },
1829 "quoteTxIndex": 1,
1830 "quoteLagBlocks": 2,
1831 "inputMint": simulator_api::mints::SOL.to_string(),
1832 "outputMint": simulator_api::mints::USDC.to_string(),
1833 "amount": 1_000,
1834 "swapMode": "ExactIn",
1835 "templateFill": 1_010,
1836 "l1Fill": 1_000,
1837 "changeVsL1Bps": 100,
1838 "outcome": "filled",
1839 });
1840
1841 let notification: ReplacementNotification =
1842 serde_json::from_value(wire.clone()).expect("wire decodes");
1843 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1844 assert_eq!(recorded, wire);
1845
1846 let ReplacementNotification::Venue(read_back) = notification else {
1847 panic!("kind=directFill must decode to the Venue variant");
1848 };
1849 assert_eq!(read_back.template, "venue-a");
1850 assert_eq!(read_back.template_fill, Some(1_010));
1851 assert_eq!(read_back.comparison.l1_fill, Some(1_000));
1852 assert_eq!(read_back.comparison.change_vs_l1_bps, Some(100));
1853 assert!(
1854 read_back.core.category.is_none(),
1855 "a filled probe carries no category"
1856 );
1857 }
1858
1859 #[test]
1865 fn an_original_notification_round_trips_through_its_own_encoding() {
1866 let wire = serde_json::json!({
1867 "kind": "original",
1868 "context": {"slot": 9},
1869 "slot": 9,
1870 "batchIndex": 2,
1871 "originalSignature": fixture_signature(),
1872 "originalFailed": false,
1873 "l1Fill": 2_000,
1874 "changeVsL1Bps": -25,
1875 "computeUnitsConsumed": 31_400,
1876 "fee": 5_000,
1877 "simulatedOutputAmount": 1_995,
1878 "outcome": "filled",
1879 });
1880
1881 let notification: ReplacementNotification =
1882 serde_json::from_value(wire.clone()).expect("wire decodes");
1883
1884 let ReplacementNotification::Original(read_back) = notification else {
1885 panic!("kind=original must decode to the Original variant");
1886 };
1887 assert_eq!(read_back.core.slot, 9);
1888 assert_eq!(
1889 read_back.core.original_signature.to_string(),
1890 fixture_signature()
1891 );
1892 assert_eq!(read_back.comparison.l1_fill, Some(2_000));
1893 assert_eq!(read_back.comparison.change_vs_l1_bps, Some(-25));
1894 assert_eq!(read_back.cost.compute_units_consumed, 31_400);
1895 assert_eq!(read_back.simulated_output_amount, Some(1_995));
1896 assert_eq!(read_back.core.outcome, "filled");
1897 }
1898
1899 #[test]
1902 fn an_untagged_old_format_payload_fails_to_deserialize() {
1903 let old_wire = serde_json::json!({
1904 "context": {"slot": 42},
1905 "slot": 42,
1906 "batchIndex": 3,
1907 "originalSignature": fixture_signature(),
1908 "legs": [],
1909 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1910 "err": serde_json::Value::Null,
1911 "logs": [],
1912 "computeUnitsConsumed": 0,
1913 "fee": serde_json::Value::Null,
1914 "realizedOutputAmount": serde_json::Value::Null,
1915 "originalRealizedOutputAmount": serde_json::Value::Null,
1916 "originalFailed": false,
1917 });
1918
1919 let err = serde_json::from_value::<ReplacementNotification>(old_wire).expect_err(
1920 "an untagged old-format payload must not deserialize as a ReplacementNotification",
1921 );
1922 assert!(
1923 err.to_string().contains("kind"),
1924 "must fail on the missing tag, not misparse into either variant: {err}"
1925 );
1926 }
1927}