1use std::{future::Future, time::Duration};
2
3use futures::{SinkExt, StreamExt};
4use serde::{Deserialize, Serialize, de::DeserializeOwned};
5use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
6use solana_account_decoder::{UiAccount, UiAccountData, UiAccountEncoding};
7use solana_client::{
8 nonblocking::pubsub_client::PubsubClient,
9 rpc_response::{Response, RpcLogsResponse},
10};
11use solana_commitment_config::CommitmentConfig;
12use solana_rpc_client_api::config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
13use thiserror::Error;
14use tokio::{
15 sync::{oneshot, watch},
16 task::JoinHandle,
17};
18use tokio_tungstenite::tungstenite::Message;
19
20use crate::urls::{UrlError, http_to_ws_url};
21
22#[derive(Debug, Error)]
24pub enum SubscriptionError {
25 #[error(transparent)]
26 InvalidUrl(#[from] UrlError),
27
28 #[error("pubsub connect to {url} failed: {source}")]
29 Connect {
30 url: String,
31 #[source]
32 source: Box<dyn std::error::Error + Send + Sync>,
33 },
34
35 #[error("logs_subscribe failed: {source}")]
36 Subscribe {
37 #[source]
38 source: Box<dyn std::error::Error + Send + Sync>,
39 },
40
41 #[error("subscription task exited unexpectedly before signaling ready")]
42 TaskDropped,
43
44 #[error("session has no rpc_endpoint (was the session created?)")]
45 NoRpcEndpoint,
46}
47
48#[derive(Debug, Error)]
49pub enum SubscriptionRuntimeError {
50 #[error("{kind} subscription for {target} closed unexpectedly")]
51 Closed { kind: &'static str, target: String },
52
53 #[error("{kind} subscription callback worker for {target} failed: {source}")]
54 CallbackWorker {
55 kind: &'static str,
56 target: String,
57 #[source]
58 source: tokio::task::JoinError,
59 },
60}
61
62const SUBSCRIPTION_DRAIN_IDLE_TIMEOUT: Duration = Duration::from_millis(250);
63const SUBSCRIPTION_DRAIN_MAX_DURATION: Duration = Duration::from_secs(5);
64
65type SubscriptionTaskHandle = JoinHandle<Result<(), SubscriptionRuntimeError>>;
66type AccountDiffWs =
67 tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
68
69pub struct SubscriptionHandle {
71 pub join_handle: SubscriptionTaskHandle,
72 pub stop: watch::Sender<bool>,
73}
74
75impl From<LogSubscriptionHandle> for SubscriptionHandle {
76 fn from(h: LogSubscriptionHandle) -> Self {
77 Self {
78 join_handle: h.join_handle,
79 stop: h.stop,
80 }
81 }
82}
83
84impl From<AccountDiffSubscriptionHandle> for SubscriptionHandle {
85 fn from(h: AccountDiffSubscriptionHandle) -> Self {
86 Self {
87 join_handle: h.join_handle,
88 stop: h.stop,
89 }
90 }
91}
92
93impl From<ActionSubscriptionHandle> for SubscriptionHandle {
94 fn from(h: ActionSubscriptionHandle) -> Self {
95 Self {
96 join_handle: h.join_handle,
97 stop: h.stop,
98 }
99 }
100}
101
102impl From<DiagnosticSubscriptionHandle> for SubscriptionHandle {
103 fn from(h: DiagnosticSubscriptionHandle) -> Self {
104 Self {
105 join_handle: h.join_handle,
106 stop: h.stop,
107 }
108 }
109}
110
111pub struct LogSubscriptionHandle {
113 pub join_handle: SubscriptionTaskHandle,
118
119 pub stop: watch::Sender<bool>,
122}
123
124pub async fn subscribe_program_logs<F, Fut>(
162 rpc_endpoint: &str,
163 program_id: &str,
164 commitment: CommitmentConfig,
165 on_notification: F,
166) -> Result<LogSubscriptionHandle, SubscriptionError>
167where
168 F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
169 Fut: Future<Output = ()> + Send + 'static,
170{
171 let ws_url = http_to_ws_url(rpc_endpoint)?;
172 let program_id = program_id.to_string();
173
174 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
175 let (stop_tx, mut stop_rx) = watch::channel(false);
176
177 let join_handle = tokio::spawn(async move {
181 let client = match PubsubClient::new(&ws_url).await {
182 Ok(c) => c,
183 Err(e) => {
184 let _ = ready_tx.send(Err(SubscriptionError::Connect {
185 url: ws_url,
186 source: Box::new(e),
187 }));
188 return Ok(());
189 }
190 };
191
192 let (mut stream, _unsubscribe) = match client
193 .logs_subscribe(
194 RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
195 RpcTransactionLogsConfig {
196 commitment: Some(commitment),
197 },
198 )
199 .await
200 {
201 Ok(s) => s,
202 Err(e) => {
203 let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
204 source: Box::new(e),
205 }));
206 return Ok(());
207 }
208 };
209
210 let _ = ready_tx.send(Ok(()));
211
212 let mut tasks: Vec<JoinHandle<()>> = Vec::new();
213 let kind = "program logs";
214
215 loop {
216 if *stop_rx.borrow() {
217 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
218 while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
219 drain_deadline,
220 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
221 )
222 .await
223 {
224 tasks.push(tokio::spawn(on_notification(notification)));
225 }
226 break;
227 }
228
229 let notification = tokio::select! {
230 n = stream.next() => n,
231 _ = stop_rx.changed() => continue,
232 };
233
234 match notification {
235 Some(n) => tasks.push(tokio::spawn(on_notification(n))),
236 None => return Err(subscription_runtime_closed(kind, &program_id)),
237 }
238 }
239
240 for task in tasks {
242 if let Err(source) = task.await {
243 return Err(callback_worker_failed(kind, &program_id, source));
244 }
245 }
246
247 Ok(())
248 });
249
250 match ready_rx.await {
251 Ok(Ok(())) => Ok(LogSubscriptionHandle {
252 join_handle,
253 stop: stop_tx,
254 }),
255 Ok(Err(e)) => {
256 join_handle.abort();
257 Err(e)
258 }
259 Err(_) => {
260 join_handle.abort();
261 Err(SubscriptionError::TaskDropped)
262 }
263 }
264}
265
266#[derive(Debug, Clone, Deserialize)]
270pub struct AccountDiffContext {
271 pub slot: u64,
272}
273
274#[derive(Debug, Clone, Deserialize)]
276pub struct AccountDiffNotification {
277 pub context: AccountDiffContext,
278 pub account: Option<String>,
280 pub signature: Option<String>,
282 #[serde(default)]
284 pub tx_index: Option<u32>,
285 #[serde(default)]
287 pub block_time: Option<i64>,
288 pub pre: Option<serde_json::Value>,
290 pub post: Option<serde_json::Value>,
292}
293
294impl AccountDiffNotification {
295 pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
297 self.post.as_ref().map(account_data_from_ui)
298 }
299}
300
301#[derive(Debug, Error)]
303pub enum UiAccountConversionError {
304 #[error("payload is not a UiAccount: {0}")]
305 NotAUiAccount(#[from] serde_json::Error),
306
307 #[error("unsupported ui-account data encoding, expected base64")]
308 UnsupportedEncoding,
309
310 #[error("decoding base64 account data: {0}")]
311 Data(#[from] base64::DecodeError),
312
313 #[error("parsing owner address: {0}")]
314 Owner(#[from] solana_address::error::ParseAddressError),
315}
316
317pub fn account_data_from_ui(
321 value: &serde_json::Value,
322) -> Result<AccountData, UiAccountConversionError> {
323 let ui = UiAccount::deserialize(value)?;
324 let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
325 return Err(UiAccountConversionError::UnsupportedEncoding);
326 };
327 let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
328 let space = match ui.space {
329 Some(space) => space,
330 None => encoded.decode()?.len() as u64,
331 };
332 Ok(AccountData {
333 data: encoded,
334 executable: ui.executable,
335 lamports: ui.lamports,
336 owner: ui.owner.parse()?,
337 space,
338 })
339}
340
341#[derive(Debug, Clone, Deserialize)]
342pub struct ActionResultContext {
343 pub slot: u64,
344}
345
346#[derive(Debug, Clone, Deserialize)]
348#[serde(rename_all = "camelCase")]
349pub struct ActionResultNotification {
350 pub context: ActionResultContext,
351 pub slot: u64,
352 #[serde(default)]
354 pub batch_index: Option<u32>,
355 #[serde(default)]
358 pub tx_index: Option<u32>,
359 pub action_index: u32,
361 #[serde(default)]
362 pub label: Option<String>,
363 pub committed: bool,
364 #[serde(default)]
367 pub transaction_outcomes: Vec<ActionTransactionOutcome>,
368 #[serde(default)]
371 pub accounts: Vec<Option<serde_json::Value>>,
372 #[serde(default)]
376 pub matched: Option<EncodedBinary>,
377}
378
379#[derive(Debug, Clone, Deserialize)]
381#[serde(rename_all = "camelCase")]
382pub struct ActionTransactionOutcome {
383 #[serde(default)]
385 pub err: Option<String>,
386 #[serde(default)]
387 pub logs: Vec<String>,
388 pub units_consumed: u64,
389 #[serde(default)]
390 pub fee: Option<u64>,
391 #[serde(default)]
393 pub return_data: Option<serde_json::Value>,
394}
395
396#[derive(Debug, Clone)]
398pub struct RoutedAccountDiffNotification {
399 pub account: String,
400 pub notification: AccountDiffNotification,
401}
402
403pub struct AccountDiffSubscriptionHandle {
407 pub join_handle: SubscriptionTaskHandle,
408 pub stop: watch::Sender<bool>,
409}
410
411fn subscription_runtime_closed(
412 kind: &'static str,
413 target: impl Into<String>,
414) -> SubscriptionRuntimeError {
415 SubscriptionRuntimeError::Closed {
416 kind,
417 target: target.into(),
418 }
419}
420
421fn callback_worker_failed(
422 kind: &'static str,
423 target: impl Into<String>,
424 source: tokio::task::JoinError,
425) -> SubscriptionRuntimeError {
426 SubscriptionRuntimeError::CallbackWorker {
427 kind,
428 target: target.into(),
429 source,
430 }
431}
432
433pub async fn subscribe_account_diffs<F, Fut>(
463 rpc_endpoint: &str,
464 account: &str,
465 on_notification: F,
466) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
467where
468 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
469 Fut: Future<Output = ()> + Send + 'static,
470{
471 subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
472 on_notification(notification.notification)
473 })
474 .await
475}
476
477pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
483 rpc_endpoint: &str,
484 accounts: I,
485 on_notification: F,
486) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
487where
488 F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
489 Fut: Future<Output = ()> + Send + 'static,
490 I: IntoIterator<Item = S>,
491 S: Into<String>,
492{
493 let ws_url = http_to_ws_url(rpc_endpoint)?;
494 let accounts = dedup_accounts(accounts);
495 if accounts.is_empty() {
496 let (stop_tx, stop_rx) = watch::channel(false);
497 return Ok(AccountDiffSubscriptionHandle {
498 join_handle: tokio::spawn(async move {
499 let _ = stop_rx;
500 Ok(())
501 }),
502 stop: stop_tx,
503 });
504 }
505
506 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
507 let (stop_tx, mut stop_rx) = watch::channel(false);
508 let target = format!("{} accounts", accounts.len());
509
510 let join_handle = tokio::spawn(async move {
511 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
512 let callback_handle = tokio::spawn(async move {
513 while let Some(notification) = notification_rx.recv().await {
514 on_notification(notification).await;
515 }
516 });
517
518 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
519 Ok(connection) => connection,
520 Err(e) => {
521 let _ = ready_tx.send(Err(SubscriptionError::Connect {
522 url: ws_url,
523 source: Box::new(e),
524 }));
525 return Ok(());
526 }
527 };
528
529 let subscriptions =
530 match send_account_diff_subscribe_many(&mut ws, &accounts, ¬ification_tx).await {
531 Ok(subscriptions) => subscriptions,
532 Err(error) => {
533 let _ = ready_tx.send(Err(error));
534 return Ok(());
535 }
536 };
537
538 let _ = ready_tx.send(Ok(()));
539
540 if let Err(error) =
541 drive_account_diff_stream_many(&mut ws, &subscriptions, ¬ification_tx, &mut stop_rx)
542 .await
543 {
544 drop(notification_tx);
545 if let Err(source) = callback_handle.await {
546 return Err(callback_worker_failed("account diff", target, source));
547 }
548 return Err(error);
549 }
550
551 drop(notification_tx);
552 if let Err(source) = callback_handle.await {
553 return Err(callback_worker_failed("account diff", target, source));
554 }
555
556 Ok(())
557 });
558
559 match ready_rx.await {
560 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
561 join_handle,
562 stop: stop_tx,
563 }),
564 Ok(Err(e)) => {
565 join_handle.abort();
566 Err(e)
567 }
568 Err(_) => {
569 join_handle.abort();
570 Err(SubscriptionError::TaskDropped)
571 }
572 }
573}
574
575#[derive(Deserialize)]
576struct AccountDiffMessage {
577 method: String,
578 params: AccountDiffParams,
579}
580
581#[derive(Deserialize)]
582struct AccountDiffParams {
583 subscription: u64,
584 result: AccountDiffNotification,
585}
586
587async fn send_account_diff_subscribe_many(
588 ws: &mut AccountDiffWs,
589 accounts: &[String],
590 notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
591) -> Result<std::collections::HashMap<u64, String>, SubscriptionError> {
592 #[derive(Deserialize)]
593 struct SubscriptionConfirmation {
594 id: u64,
595 result: Option<u64>,
596 }
597
598 let mut pending: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
599 let mut subscriptions = std::collections::HashMap::with_capacity(accounts.len());
600
601 for (index, account) in accounts.iter().enumerate() {
602 let request_id = (index + 1) as u64;
603 let req = serde_json::json!({
604 "jsonrpc": "2.0",
605 "id": request_id,
606 "method": "accountDiffSubscribe",
607 "params": [account]
608 });
609 ws.send(Message::Text(req.to_string()))
610 .await
611 .map_err(|source| SubscriptionError::Subscribe {
612 source: Box::new(source),
613 })?;
614 pending.insert(request_id, account.clone());
615 }
616
617 while !pending.is_empty() {
618 match ws.next().await {
619 Some(Ok(Message::Text(text))) => {
620 if let Ok(confirmation) = serde_json::from_str::<SubscriptionConfirmation>(&text) {
621 let Some(account) = pending.remove(&confirmation.id) else {
622 continue;
623 };
624 let Some(subscription_id) = confirmation.result else {
625 return Err(SubscriptionError::TaskDropped);
626 };
627 subscriptions.insert(subscription_id, account);
628 continue;
629 }
630
631 if let Some(notification) =
632 parse_routed_account_diff_notification(&text, &subscriptions)
633 {
634 let _ = notification_tx.send(notification);
635 }
636 }
637 Some(Ok(_)) => {}
638 _ => return Err(SubscriptionError::TaskDropped),
639 }
640 }
641
642 Ok(subscriptions)
643}
644
645async fn drive_account_diff_stream_many(
646 ws: &mut AccountDiffWs,
647 subscriptions: &std::collections::HashMap<u64, String>,
648 notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
649 stop_rx: &mut watch::Receiver<bool>,
650) -> Result<(), SubscriptionRuntimeError> {
651 loop {
652 if *stop_rx.borrow() {
653 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
654 loop {
655 match tokio::time::timeout_at(
656 drain_deadline,
657 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
658 )
659 .await
660 {
661 Ok(Ok(Some(Ok(Message::Text(text))))) => {
662 if let Some(notification) =
663 parse_routed_account_diff_notification(&text, subscriptions)
664 {
665 let _ = notification_tx.send(notification);
666 }
667 }
668 _ => return Ok(()),
669 }
670 }
671 }
672
673 let msg = tokio::select! {
674 m = ws.next() => m,
675 _ = stop_rx.changed() => continue,
676 };
677
678 match msg {
679 Some(Ok(Message::Text(text))) => {
680 if let Some(notification) =
681 parse_routed_account_diff_notification(&text, subscriptions)
682 {
683 let _ = notification_tx.send(notification);
684 }
685 }
686 Some(Ok(_)) => {}
687 _ => {
688 return Err(subscription_runtime_closed(
689 "account diff",
690 format!("{} accounts", subscriptions.len()),
691 ));
692 }
693 }
694 }
695}
696
697fn parse_account_diff_message(text: &str) -> Option<AccountDiffMessage> {
698 let msg: AccountDiffMessage = serde_json::from_str(text).ok()?;
699 (msg.method == "accountDiffNotification").then_some(msg)
700}
701
702fn parse_routed_account_diff_notification(
703 text: &str,
704 subscriptions: &std::collections::HashMap<u64, String>,
705) -> Option<RoutedAccountDiffNotification> {
706 let msg = parse_account_diff_message(text)?;
707 let account = subscriptions.get(&msg.params.subscription)?.clone();
708 Some(RoutedAccountDiffNotification {
709 account,
710 notification: msg.params.result,
711 })
712}
713
714fn dedup_accounts<I, S>(accounts: I) -> Vec<String>
715where
716 I: IntoIterator<Item = S>,
717 S: Into<String>,
718{
719 let mut unique = std::collections::BTreeSet::new();
720 accounts
721 .into_iter()
722 .map(Into::into)
723 .filter(|account| unique.insert(account.clone()))
724 .collect()
725}
726
727pub async fn subscribe_program_diffs<F, Fut>(
760 rpc_endpoint: &str,
761 program_id: &str,
762 on_notification: F,
763) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
764where
765 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
766 Fut: Future<Output = ()> + Send + 'static,
767{
768 let ws_url = http_to_ws_url(rpc_endpoint)?;
769 let program_id = program_id.to_string();
770
771 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
772 let (stop_tx, mut stop_rx) = watch::channel(false);
773
774 let join_handle = tokio::spawn(async move {
775 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
776 let callback_handle = tokio::spawn(async move {
777 while let Some(notification) = notification_rx.recv().await {
778 on_notification(notification).await;
779 }
780 });
781
782 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
783 Ok(connection) => connection,
784 Err(e) => {
785 let _ = ready_tx.send(Err(SubscriptionError::Connect {
786 url: ws_url,
787 source: Box::new(e),
788 }));
789 return Ok(());
790 }
791 };
792
793 if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
794 let _ = ready_tx.send(Err(error));
795 return Ok(());
796 }
797
798 let _ = ready_tx.send(Ok(()));
799
800 if let Err(error) =
801 drive_program_diff_stream(&mut ws, ¬ification_tx, &mut stop_rx, &program_id).await
802 {
803 drop(notification_tx);
804 if let Err(source) = callback_handle.await {
805 return Err(callback_worker_failed(
806 "program account diff",
807 &program_id,
808 source,
809 ));
810 }
811 return Err(error);
812 }
813
814 drop(notification_tx);
815 if let Err(source) = callback_handle.await {
816 return Err(callback_worker_failed(
817 "program account diff",
818 &program_id,
819 source,
820 ));
821 }
822
823 Ok(())
824 });
825
826 match ready_rx.await {
827 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
828 join_handle,
829 stop: stop_tx,
830 }),
831 Ok(Err(e)) => {
832 join_handle.abort();
833 Err(e)
834 }
835 Err(_) => {
836 join_handle.abort();
837 Err(SubscriptionError::TaskDropped)
838 }
839 }
840}
841
842async fn send_program_diff_subscribe(
843 ws: &mut AccountDiffWs,
844 program_id: &str,
845) -> Result<(), SubscriptionError> {
846 #[derive(Deserialize)]
847 struct SubscriptionConfirmation {
848 result: Option<u64>,
849 }
850
851 let req = serde_json::json!({
852 "jsonrpc": "2.0",
853 "id": 1,
854 "method": "accountDiffSubscribe",
855 "params": [program_id, {"address_type": "program"}]
856 });
857 ws.send(Message::Text(req.to_string()))
858 .await
859 .map_err(|source| SubscriptionError::Subscribe {
860 source: Box::new(source),
861 })?;
862
863 loop {
864 match ws.next().await {
865 Some(Ok(Message::Text(text))) => {
866 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
867 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
868 Ok(_) => continue,
869 Err(source) => {
870 return Err(SubscriptionError::Subscribe {
871 source: Box::new(source),
872 });
873 }
874 }
875 }
876 Some(Ok(_)) => continue,
877 _ => return Err(SubscriptionError::TaskDropped),
878 }
879 }
880}
881
882async fn drive_program_diff_stream(
883 ws: &mut AccountDiffWs,
884 notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
885 stop_rx: &mut watch::Receiver<bool>,
886 program_id: &str,
887) -> Result<(), SubscriptionRuntimeError> {
888 loop {
889 if *stop_rx.borrow() {
890 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
891 loop {
892 match tokio::time::timeout_at(
893 drain_deadline,
894 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
895 )
896 .await
897 {
898 Ok(Ok(Some(Ok(Message::Text(text))))) => {
899 if let Some(msg) = parse_account_diff_message(&text) {
900 let _ = notification_tx.send(msg.params.result);
901 }
902 }
903 _ => return Ok(()),
904 }
905 }
906 }
907
908 let msg = tokio::select! {
909 m = ws.next() => m,
910 _ = stop_rx.changed() => continue,
911 };
912
913 match msg {
914 Some(Ok(Message::Text(text))) => {
915 if let Some(msg) = parse_account_diff_message(&text) {
916 let _ = notification_tx.send(msg.params.result);
917 }
918 }
919 Some(Ok(_)) => {}
920 _ => {
921 return Err(subscription_runtime_closed(
922 "program account diff",
923 program_id,
924 ));
925 }
926 }
927 }
928}
929
930#[derive(Clone, Copy)]
934struct NotificationStream {
935 subscribe_method: &'static str,
936 notification_method: &'static str,
937 kind: &'static str,
939 target: &'static str,
941}
942
943const ACTION_STREAM: NotificationStream = NotificationStream {
944 subscribe_method: "actionSubscribe",
945 notification_method: "actionNotification",
946 kind: "action",
947 target: "actions",
948};
949
950const REPLACEMENT_STREAM: NotificationStream = NotificationStream {
951 subscribe_method: "replacementSubscribe",
952 notification_method: "replacementNotification",
953 kind: "replacement",
954 target: "replacements",
955};
956
957const DIAGNOSTIC_STREAM: NotificationStream = NotificationStream {
958 subscribe_method: "diagnosticSubscribe",
959 notification_method: "diagnosticNotification",
960 kind: "diagnostic",
961 target: "diagnostics",
962};
963
964#[derive(Deserialize)]
965struct NotificationMessage<N> {
966 method: String,
967 params: NotificationParams<N>,
968}
969
970#[derive(Deserialize)]
971struct NotificationParams<N> {
972 #[allow(dead_code)]
973 subscription: u64,
974 result: N,
975}
976
977fn parse_notification_message<N: DeserializeOwned>(
978 text: &str,
979 notification_method: &str,
980) -> Option<N> {
981 let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
982 (msg.method == notification_method).then_some(msg.params.result)
983}
984
985fn is_subscription_complete_message(text: &str) -> bool {
986 #[derive(Deserialize)]
987 struct SubscriptionCompleteMessage {
988 method: String,
989 }
990
991 serde_json::from_str::<SubscriptionCompleteMessage>(text)
992 .is_ok_and(|msg| msg.method == "subscriptionComplete")
993}
994
995async fn subscribe_notifications<N, F, Fut>(
1000 rpc_endpoint: &str,
1001 stream: NotificationStream,
1002 on_notification: F,
1003) -> Result<SubscriptionHandle, SubscriptionError>
1004where
1005 N: DeserializeOwned + Send + 'static,
1006 F: Fn(N) -> Fut + Send + Sync + 'static,
1007 Fut: Future<Output = ()> + Send + 'static,
1008{
1009 let ws_url = http_to_ws_url(rpc_endpoint)?;
1010
1011 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
1012 let (stop_tx, mut stop_rx) = watch::channel(false);
1013
1014 let join_handle = tokio::spawn(async move {
1015 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
1016 let callback_handle = tokio::spawn(async move {
1017 while let Some(notification) = notification_rx.recv().await {
1018 on_notification(notification).await;
1019 }
1020 });
1021
1022 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
1023 Ok(connection) => connection,
1024 Err(e) => {
1025 let _ = ready_tx.send(Err(SubscriptionError::Connect {
1026 url: ws_url,
1027 source: Box::new(e),
1028 }));
1029 return Ok(());
1030 }
1031 };
1032
1033 if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
1034 let _ = ready_tx.send(Err(error));
1035 return Ok(());
1036 }
1037
1038 let _ = ready_tx.send(Ok(()));
1039
1040 if let Err(error) =
1041 drive_notification_stream::<N>(&mut ws, stream, ¬ification_tx, &mut stop_rx).await
1042 {
1043 drop(notification_tx);
1044 if let Err(source) = callback_handle.await {
1045 return Err(callback_worker_failed(stream.kind, stream.target, source));
1046 }
1047 return Err(error);
1048 }
1049
1050 drop(notification_tx);
1051 if let Err(source) = callback_handle.await {
1052 return Err(callback_worker_failed(stream.kind, stream.target, source));
1053 }
1054
1055 Ok(())
1056 });
1057
1058 match ready_rx.await {
1059 Ok(Ok(())) => Ok(SubscriptionHandle {
1060 join_handle,
1061 stop: stop_tx,
1062 }),
1063 Ok(Err(e)) => {
1064 join_handle.abort();
1065 Err(e)
1066 }
1067 Err(_) => {
1068 join_handle.abort();
1069 Err(SubscriptionError::TaskDropped)
1070 }
1071 }
1072}
1073
1074async fn send_stream_subscribe(
1075 ws: &mut AccountDiffWs,
1076 subscribe_method: &str,
1077) -> Result<(), SubscriptionError> {
1078 #[derive(Deserialize)]
1079 struct SubscriptionConfirmation {
1080 result: Option<u64>,
1081 }
1082
1083 let req = serde_json::json!({
1085 "jsonrpc": "2.0",
1086 "id": 1,
1087 "method": subscribe_method,
1088 "params": [serde_json::Value::Null, {}]
1089 });
1090
1091 ws.send(Message::Text(req.to_string()))
1092 .await
1093 .map_err(|source| SubscriptionError::Subscribe {
1094 source: Box::new(source),
1095 })?;
1096
1097 loop {
1098 match ws.next().await {
1099 Some(Ok(Message::Text(text))) => {
1100 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1101 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1102 Ok(_) => continue,
1103 Err(source) => {
1104 return Err(SubscriptionError::Subscribe {
1105 source: Box::new(source),
1106 });
1107 }
1108 }
1109 }
1110 Some(Ok(_)) => continue,
1111 _ => return Err(SubscriptionError::TaskDropped),
1112 }
1113 }
1114}
1115
1116async fn drive_notification_stream<N: DeserializeOwned>(
1117 ws: &mut AccountDiffWs,
1118 stream: NotificationStream,
1119 notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
1120 stop_rx: &mut watch::Receiver<bool>,
1121) -> Result<(), SubscriptionRuntimeError> {
1122 loop {
1123 if *stop_rx.borrow() {
1124 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1125 loop {
1126 match tokio::time::timeout_at(
1127 drain_deadline,
1128 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1129 )
1130 .await
1131 {
1132 Ok(Ok(Some(Ok(Message::Text(text))))) => {
1133 if is_subscription_complete_message(&text) {
1134 return Ok(());
1135 }
1136 if let Some(result) =
1137 parse_notification_message::<N>(&text, stream.notification_method)
1138 {
1139 let _ = notification_tx.send(result);
1140 }
1141 }
1142 _ => return Ok(()),
1143 }
1144 }
1145 }
1146
1147 let msg = tokio::select! {
1148 m = ws.next() => m,
1149 _ = stop_rx.changed() => continue,
1150 };
1151
1152 match msg {
1153 Some(Ok(Message::Text(text))) => {
1154 if is_subscription_complete_message(&text) {
1155 return Ok(());
1156 }
1157 if let Some(result) =
1158 parse_notification_message::<N>(&text, stream.notification_method)
1159 {
1160 let _ = notification_tx.send(result);
1161 }
1162 }
1163 Some(Ok(_)) => {}
1164 _ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
1165 }
1166 }
1167}
1168
1169pub struct ActionSubscriptionHandle {
1175 pub join_handle: SubscriptionTaskHandle,
1176 pub stop: watch::Sender<bool>,
1177}
1178
1179pub async fn subscribe_actions<F, Fut>(
1209 rpc_endpoint: &str,
1210 on_notification: F,
1211) -> Result<ActionSubscriptionHandle, SubscriptionError>
1212where
1213 F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
1214 Fut: Future<Output = ()> + Send + 'static,
1215{
1216 let SubscriptionHandle { join_handle, stop } =
1217 subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
1218 Ok(ActionSubscriptionHandle { join_handle, stop })
1219}
1220
1221#[derive(Debug, Clone, Serialize, Deserialize)]
1224pub struct DiagnosticContext {
1225 pub slot: u64,
1226}
1227
1228#[derive(Debug, Clone, Serialize, Deserialize)]
1233#[serde(rename_all = "camelCase")]
1234pub struct DiagnosticNotification {
1235 pub context: DiagnosticContext,
1236 pub slot: u64,
1238 pub probe_index: u32,
1240 #[serde(default)]
1241 pub label: Option<String>,
1242 pub market: String,
1243 pub usd_value: u32,
1244 #[serde(default)]
1247 pub router_slot: Option<u64>,
1248 #[serde(default)]
1250 pub results: Option<serde_json::Value>,
1251 #[serde(default)]
1253 pub account_hashes: Vec<String>,
1254 #[serde(default)]
1256 pub err: Option<String>,
1257}
1258
1259pub struct DiagnosticSubscriptionHandle {
1260 pub join_handle: SubscriptionTaskHandle,
1261 pub stop: watch::Sender<bool>,
1262}
1263
1264pub async fn subscribe_diagnostics<F, Fut>(
1267 rpc_endpoint: &str,
1268 on_notification: F,
1269) -> Result<DiagnosticSubscriptionHandle, SubscriptionError>
1270where
1271 F: Fn(DiagnosticNotification) -> Fut + Send + Sync + 'static,
1272 Fut: Future<Output = ()> + Send + 'static,
1273{
1274 let SubscriptionHandle { join_handle, stop } =
1275 subscribe_notifications(rpc_endpoint, DIAGNOSTIC_STREAM, on_notification).await?;
1276 Ok(DiagnosticSubscriptionHandle { join_handle, stop })
1277}
1278
1279pub use simulator_api::replacement::{
1285 DirectFillNotification, OriginalNotification, ReplacementContext, ReplacementCore,
1286 ReplacementNotification, RequoteNotification, RerouteLegNotification,
1287};
1288
1289pub async fn subscribe_replacements<F, Fut>(
1327 rpc_endpoint: &str,
1328 on_notification: F,
1329) -> Result<SubscriptionHandle, SubscriptionError>
1330where
1331 F: Fn(ReplacementNotification) -> Fut + Send + Sync + 'static,
1332 Fut: Future<Output = ()> + Send + 'static,
1333{
1334 subscribe_notifications(rpc_endpoint, REPLACEMENT_STREAM, on_notification).await
1335}
1336
1337#[cfg(test)]
1338mod tests {
1339 use super::*;
1340
1341 #[test]
1342 fn parse_account_diff_notification_ignores_other_messages() {
1343 let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
1344 assert!(parse_account_diff_message(confirmation).is_none());
1345 }
1346
1347 #[test]
1348 fn parse_account_diff_notification_extracts_payload() {
1349 let text = r#"{
1350 "jsonrpc":"2.0",
1351 "method":"accountDiffNotification",
1352 "params":{
1353 "subscription":7,
1354 "result":{
1355 "context":{"slot":123},
1356 "signature":"sig",
1357 "pre":{"a":1},
1358 "post":{"a":2}
1359 }
1360 }
1361 }"#;
1362
1363 let notification = parse_account_diff_message(text)
1364 .expect("notification")
1365 .params
1366 .result;
1367 assert_eq!(notification.context.slot, 123);
1368 assert_eq!(notification.signature.as_deref(), Some("sig"));
1369 assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
1370 assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
1371 }
1372
1373 #[test]
1374 fn parse_routed_account_diff_notification_extracts_subscription_account() {
1375 let text = r#"{
1376 "jsonrpc":"2.0",
1377 "method":"accountDiffNotification",
1378 "params":{
1379 "subscription":42,
1380 "result":{
1381 "context":{"slot":456},
1382 "signature":"sig",
1383 "pre":null,
1384 "post":{"a":2}
1385 }
1386 }
1387 }"#;
1388 let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
1389
1390 let notification =
1391 parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
1392 assert_eq!(notification.account, "acct");
1393 assert_eq!(notification.notification.context.slot, 456);
1394 }
1395
1396 #[test]
1397 fn converts_ui_account_json() {
1398 let value = serde_json::json!({
1399 "lamports": 5,
1400 "data": ["AQID", "base64"],
1401 "owner": "11111111111111111111111111111111",
1402 "executable": false,
1403 "rentEpoch": 0,
1404 });
1405 let account = account_data_from_ui(&value).unwrap();
1406 assert_eq!(account.lamports, 5);
1407 assert_eq!(account.space, 3);
1408 assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
1409 }
1410
1411 #[test]
1412 fn rejects_non_base64_encodings() {
1413 let value = serde_json::json!({
1414 "lamports": 5,
1415 "data": ["{}", "jsonParsed"],
1416 "owner": "11111111111111111111111111111111",
1417 "executable": false,
1418 "rentEpoch": 0,
1419 });
1420 assert!(matches!(
1421 account_data_from_ui(&value),
1422 Err(UiAccountConversionError::UnsupportedEncoding)
1423 ));
1424 }
1425
1426 #[test]
1427 fn dedup_accounts_preserves_first_seen_order() {
1428 let accounts = dedup_accounts([
1429 "b".to_string(),
1430 "a".to_string(),
1431 "b".to_string(),
1432 "c".to_string(),
1433 ]);
1434 assert_eq!(accounts, vec!["b", "a", "c"]);
1435 }
1436
1437 fn fixture_signature() -> String {
1439 simulator_api::replacement::Signature::default().to_string()
1440 }
1441
1442 fn route_hop(set: serde_json::Value, program: serde_json::Value) -> serde_json::Value {
1444 use serde_json::json;
1445
1446 let mut swap_info = json!({
1447 "label": null, "ammKey": null, "inputMint": null,
1448 "inAmount": null, "outputMint": null, "outAmount": null,
1449 });
1450 for (key, value) in set.as_object().expect("an object") {
1451 swap_info[key] = value.clone();
1452 }
1453 json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
1454 }
1455
1456 #[test]
1459 fn a_requote_notification_round_trips_through_its_own_encoding() {
1460 use serde_json::{Value, json};
1461
1462 let wire = serde_json::json!({
1463 "kind": "requote",
1464 "context": {"slot": 42},
1465 "slot": 42,
1466 "batchIndex": 3,
1467 "originalSignature": fixture_signature(),
1468 "originalFailed": false,
1469 "outcome": "filled",
1470 "legs": [{
1471 "inputMint": simulator_api::mints::SOL.to_string(),
1472 "outputMint": simulator_api::mints::USDC.to_string(),
1473 "amount": 1_000,
1474 "swapMode": "ExactIn",
1475 "originalQuotedOut": 990,
1476 "metisQuotedOut": 1_010,
1477 "routeSummary": "SolFi",
1478 "routePlan": [route_hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
1480 "originalRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
1481 "realizedRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
1482 }],
1483 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1484 "logs": ["Program log: swap"],
1485 "computeUnitsConsumed": 123_456,
1486 "fee": 5_000,
1487 "realizedOutputAmount": 1_009,
1488 "originalRealizedOutputAmount": 991,
1489 });
1490
1491 let notification: ReplacementNotification =
1492 serde_json::from_value(wire.clone()).expect("wire decodes");
1493 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1494 assert_eq!(recorded, wire);
1495
1496 let ReplacementNotification::Requote(read_back) =
1497 serde_json::from_value::<ReplacementNotification>(recorded).expect("recording decodes")
1498 else {
1499 panic!("kind=requote must decode to the Requote variant");
1500 };
1501 assert_eq!(read_back.core.batch_index, 3);
1502 assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
1503 assert_eq!(read_back.original_realized_output_amount, Some(991));
1504 assert!(
1507 read_back
1508 .legs
1509 .iter()
1510 .all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
1511 );
1512 }
1513
1514 #[test]
1516 fn a_direct_fill_notification_round_trips_through_its_own_encoding() {
1517 let wire = serde_json::json!({
1518 "kind": "directFill",
1519 "context": {"slot": 7},
1520 "slot": 7,
1521 "batchIndex": 1,
1522 "originalSignature": fixture_signature(),
1523 "originalFailed": false,
1524 "template": "Tempest",
1525 "inputMint": simulator_api::mints::SOL.to_string(),
1526 "outputMint": simulator_api::mints::USDC.to_string(),
1527 "amount": 1_000,
1528 "swapMode": "ExactIn",
1529 "templateFill": 1_010,
1530 "l1Fill": 1_000,
1531 "changeVsL1Bps": 100,
1532 "outcome": "filled",
1533 });
1534
1535 let notification: ReplacementNotification =
1536 serde_json::from_value(wire.clone()).expect("wire decodes");
1537 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1538 assert_eq!(recorded, wire);
1539
1540 let ReplacementNotification::DirectFill(read_back) = notification else {
1541 panic!("kind=directFill must decode to the DirectFill variant");
1542 };
1543 assert_eq!(read_back.template, "Tempest");
1544 assert_eq!(read_back.template_fill, Some(1_010));
1545 assert_eq!(read_back.comparison.l1_fill, Some(1_000));
1546 assert_eq!(read_back.comparison.change_vs_l1_bps, Some(100));
1547 assert!(
1548 read_back.core.category.is_none(),
1549 "a filled probe carries no category"
1550 );
1551 }
1552
1553 #[test]
1559 fn an_original_notification_round_trips_through_its_own_encoding() {
1560 let wire = serde_json::json!({
1561 "kind": "original",
1562 "context": {"slot": 9},
1563 "slot": 9,
1564 "batchIndex": 2,
1565 "originalSignature": fixture_signature(),
1566 "originalFailed": false,
1567 "l1Fill": 2_000,
1568 "changeVsL1Bps": -25,
1569 "computeUnitsConsumed": 31_400,
1570 "fee": 5_000,
1571 "simulatedOutputAmount": 1_995,
1572 "outcome": "filled",
1573 });
1574
1575 let notification: ReplacementNotification =
1576 serde_json::from_value(wire.clone()).expect("wire decodes");
1577
1578 let ReplacementNotification::Original(read_back) = notification else {
1579 panic!("kind=original must decode to the Original variant");
1580 };
1581 assert_eq!(read_back.core.slot, 9);
1582 assert_eq!(
1583 read_back.core.original_signature.to_string(),
1584 fixture_signature()
1585 );
1586 assert_eq!(read_back.comparison.l1_fill, Some(2_000));
1587 assert_eq!(read_back.comparison.change_vs_l1_bps, Some(-25));
1588 assert_eq!(read_back.cost.compute_units_consumed, 31_400);
1589 assert_eq!(read_back.simulated_output_amount, Some(1_995));
1590 assert_eq!(read_back.core.outcome, "filled");
1591 }
1592
1593 #[test]
1596 fn an_untagged_old_format_payload_fails_to_deserialize() {
1597 let old_wire = serde_json::json!({
1598 "context": {"slot": 42},
1599 "slot": 42,
1600 "batchIndex": 3,
1601 "originalSignature": fixture_signature(),
1602 "legs": [],
1603 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1604 "err": serde_json::Value::Null,
1605 "logs": [],
1606 "computeUnitsConsumed": 0,
1607 "fee": serde_json::Value::Null,
1608 "realizedOutputAmount": serde_json::Value::Null,
1609 "originalRealizedOutputAmount": serde_json::Value::Null,
1610 "originalFailed": false,
1611 });
1612
1613 let err = serde_json::from_value::<ReplacementNotification>(old_wire).expect_err(
1614 "an untagged old-format payload must not deserialize as a ReplacementNotification",
1615 );
1616 assert!(
1617 err.to_string().contains("kind"),
1618 "must fail on the missing tag, not misparse into either variant: {err}"
1619 );
1620 }
1621}