1use std::{future::Future, time::Duration};
2
3use futures::{SinkExt, StreamExt};
4use serde::{Deserialize, Serialize, de::DeserializeOwned};
5use simulator_api::{AccountData, BinaryEncoding, EncodedBinary, route_plan::RoutePlan};
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
102pub struct LogSubscriptionHandle {
104 pub join_handle: SubscriptionTaskHandle,
109
110 pub stop: watch::Sender<bool>,
113}
114
115pub async fn subscribe_program_logs<F, Fut>(
153 rpc_endpoint: &str,
154 program_id: &str,
155 commitment: CommitmentConfig,
156 on_notification: F,
157) -> Result<LogSubscriptionHandle, SubscriptionError>
158where
159 F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
160 Fut: Future<Output = ()> + Send + 'static,
161{
162 let ws_url = http_to_ws_url(rpc_endpoint)?;
163 let program_id = program_id.to_string();
164
165 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
166 let (stop_tx, mut stop_rx) = watch::channel(false);
167
168 let join_handle = tokio::spawn(async move {
172 let client = match PubsubClient::new(&ws_url).await {
173 Ok(c) => c,
174 Err(e) => {
175 let _ = ready_tx.send(Err(SubscriptionError::Connect {
176 url: ws_url,
177 source: Box::new(e),
178 }));
179 return Ok(());
180 }
181 };
182
183 let (mut stream, _unsubscribe) = match client
184 .logs_subscribe(
185 RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
186 RpcTransactionLogsConfig {
187 commitment: Some(commitment),
188 },
189 )
190 .await
191 {
192 Ok(s) => s,
193 Err(e) => {
194 let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
195 source: Box::new(e),
196 }));
197 return Ok(());
198 }
199 };
200
201 let _ = ready_tx.send(Ok(()));
202
203 let mut tasks: Vec<JoinHandle<()>> = Vec::new();
204 let kind = "program logs";
205
206 loop {
207 if *stop_rx.borrow() {
208 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
209 while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
210 drain_deadline,
211 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
212 )
213 .await
214 {
215 tasks.push(tokio::spawn(on_notification(notification)));
216 }
217 break;
218 }
219
220 let notification = tokio::select! {
221 n = stream.next() => n,
222 _ = stop_rx.changed() => continue,
223 };
224
225 match notification {
226 Some(n) => tasks.push(tokio::spawn(on_notification(n))),
227 None => return Err(subscription_runtime_closed(kind, &program_id)),
228 }
229 }
230
231 for task in tasks {
233 if let Err(source) = task.await {
234 return Err(callback_worker_failed(kind, &program_id, source));
235 }
236 }
237
238 Ok(())
239 });
240
241 match ready_rx.await {
242 Ok(Ok(())) => Ok(LogSubscriptionHandle {
243 join_handle,
244 stop: stop_tx,
245 }),
246 Ok(Err(e)) => {
247 join_handle.abort();
248 Err(e)
249 }
250 Err(_) => {
251 join_handle.abort();
252 Err(SubscriptionError::TaskDropped)
253 }
254 }
255}
256
257#[derive(Debug, Clone, Deserialize)]
261pub struct AccountDiffContext {
262 pub slot: u64,
263}
264
265#[derive(Debug, Clone, Deserialize)]
267pub struct AccountDiffNotification {
268 pub context: AccountDiffContext,
269 pub account: Option<String>,
271 pub signature: Option<String>,
273 #[serde(default)]
275 pub tx_index: Option<u32>,
276 #[serde(default)]
278 pub block_time: Option<i64>,
279 pub pre: Option<serde_json::Value>,
281 pub post: Option<serde_json::Value>,
283}
284
285impl AccountDiffNotification {
286 pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
288 self.post.as_ref().map(account_data_from_ui)
289 }
290}
291
292#[derive(Debug, Error)]
294pub enum UiAccountConversionError {
295 #[error("payload is not a UiAccount: {0}")]
296 NotAUiAccount(#[from] serde_json::Error),
297
298 #[error("unsupported ui-account data encoding, expected base64")]
299 UnsupportedEncoding,
300
301 #[error("decoding base64 account data: {0}")]
302 Data(#[from] base64::DecodeError),
303
304 #[error("parsing owner address: {0}")]
305 Owner(#[from] solana_address::error::ParseAddressError),
306}
307
308pub fn account_data_from_ui(
312 value: &serde_json::Value,
313) -> Result<AccountData, UiAccountConversionError> {
314 let ui = UiAccount::deserialize(value)?;
315 let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
316 return Err(UiAccountConversionError::UnsupportedEncoding);
317 };
318 let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
319 let space = match ui.space {
320 Some(space) => space,
321 None => encoded.decode()?.len() as u64,
322 };
323 Ok(AccountData {
324 data: encoded,
325 executable: ui.executable,
326 lamports: ui.lamports,
327 owner: ui.owner.parse()?,
328 space,
329 })
330}
331
332#[derive(Debug, Clone, Deserialize)]
333pub struct ActionResultContext {
334 pub slot: u64,
335}
336
337#[derive(Debug, Clone, Deserialize)]
339#[serde(rename_all = "camelCase")]
340pub struct ActionResultNotification {
341 pub context: ActionResultContext,
342 pub slot: u64,
343 #[serde(default)]
345 pub batch_index: Option<u32>,
346 pub action_index: u32,
348 #[serde(default)]
349 pub label: Option<String>,
350 pub committed: bool,
351 #[serde(default)]
354 pub transaction_outcomes: Vec<ActionTransactionOutcome>,
355 #[serde(default)]
358 pub accounts: Vec<Option<serde_json::Value>>,
359 #[serde(default)]
363 pub matched: Option<EncodedBinary>,
364}
365
366#[derive(Debug, Clone, Deserialize)]
368#[serde(rename_all = "camelCase")]
369pub struct ActionTransactionOutcome {
370 #[serde(default)]
372 pub err: Option<String>,
373 #[serde(default)]
374 pub logs: Vec<String>,
375 pub units_consumed: u64,
376 #[serde(default)]
377 pub fee: Option<u64>,
378 #[serde(default)]
380 pub return_data: Option<serde_json::Value>,
381}
382
383#[derive(Debug, Clone)]
385pub struct RoutedAccountDiffNotification {
386 pub account: String,
387 pub notification: AccountDiffNotification,
388}
389
390pub struct AccountDiffSubscriptionHandle {
394 pub join_handle: SubscriptionTaskHandle,
395 pub stop: watch::Sender<bool>,
396}
397
398fn subscription_runtime_closed(
399 kind: &'static str,
400 target: impl Into<String>,
401) -> SubscriptionRuntimeError {
402 SubscriptionRuntimeError::Closed {
403 kind,
404 target: target.into(),
405 }
406}
407
408fn callback_worker_failed(
409 kind: &'static str,
410 target: impl Into<String>,
411 source: tokio::task::JoinError,
412) -> SubscriptionRuntimeError {
413 SubscriptionRuntimeError::CallbackWorker {
414 kind,
415 target: target.into(),
416 source,
417 }
418}
419
420pub async fn subscribe_account_diffs<F, Fut>(
450 rpc_endpoint: &str,
451 account: &str,
452 on_notification: F,
453) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
454where
455 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
456 Fut: Future<Output = ()> + Send + 'static,
457{
458 subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
459 on_notification(notification.notification)
460 })
461 .await
462}
463
464pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
470 rpc_endpoint: &str,
471 accounts: I,
472 on_notification: F,
473) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
474where
475 F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
476 Fut: Future<Output = ()> + Send + 'static,
477 I: IntoIterator<Item = S>,
478 S: Into<String>,
479{
480 let ws_url = http_to_ws_url(rpc_endpoint)?;
481 let accounts = dedup_accounts(accounts);
482 if accounts.is_empty() {
483 let (stop_tx, stop_rx) = watch::channel(false);
484 return Ok(AccountDiffSubscriptionHandle {
485 join_handle: tokio::spawn(async move {
486 let _ = stop_rx;
487 Ok(())
488 }),
489 stop: stop_tx,
490 });
491 }
492
493 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
494 let (stop_tx, mut stop_rx) = watch::channel(false);
495 let target = format!("{} accounts", accounts.len());
496
497 let join_handle = tokio::spawn(async move {
498 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
499 let callback_handle = tokio::spawn(async move {
500 while let Some(notification) = notification_rx.recv().await {
501 on_notification(notification).await;
502 }
503 });
504
505 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
506 Ok(connection) => connection,
507 Err(e) => {
508 let _ = ready_tx.send(Err(SubscriptionError::Connect {
509 url: ws_url,
510 source: Box::new(e),
511 }));
512 return Ok(());
513 }
514 };
515
516 let subscriptions =
517 match send_account_diff_subscribe_many(&mut ws, &accounts, ¬ification_tx).await {
518 Ok(subscriptions) => subscriptions,
519 Err(error) => {
520 let _ = ready_tx.send(Err(error));
521 return Ok(());
522 }
523 };
524
525 let _ = ready_tx.send(Ok(()));
526
527 if let Err(error) =
528 drive_account_diff_stream_many(&mut ws, &subscriptions, ¬ification_tx, &mut stop_rx)
529 .await
530 {
531 drop(notification_tx);
532 if let Err(source) = callback_handle.await {
533 return Err(callback_worker_failed("account diff", target, source));
534 }
535 return Err(error);
536 }
537
538 drop(notification_tx);
539 if let Err(source) = callback_handle.await {
540 return Err(callback_worker_failed("account diff", target, source));
541 }
542
543 Ok(())
544 });
545
546 match ready_rx.await {
547 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
548 join_handle,
549 stop: stop_tx,
550 }),
551 Ok(Err(e)) => {
552 join_handle.abort();
553 Err(e)
554 }
555 Err(_) => {
556 join_handle.abort();
557 Err(SubscriptionError::TaskDropped)
558 }
559 }
560}
561
562#[derive(Deserialize)]
563struct AccountDiffMessage {
564 method: String,
565 params: AccountDiffParams,
566}
567
568#[derive(Deserialize)]
569struct AccountDiffParams {
570 subscription: u64,
571 result: AccountDiffNotification,
572}
573
574async fn send_account_diff_subscribe_many(
575 ws: &mut AccountDiffWs,
576 accounts: &[String],
577 notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
578) -> Result<std::collections::HashMap<u64, String>, SubscriptionError> {
579 #[derive(Deserialize)]
580 struct SubscriptionConfirmation {
581 id: u64,
582 result: Option<u64>,
583 }
584
585 let mut pending: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
586 let mut subscriptions = std::collections::HashMap::with_capacity(accounts.len());
587
588 for (index, account) in accounts.iter().enumerate() {
589 let request_id = (index + 1) as u64;
590 let req = serde_json::json!({
591 "jsonrpc": "2.0",
592 "id": request_id,
593 "method": "accountDiffSubscribe",
594 "params": [account]
595 });
596 ws.send(Message::Text(req.to_string()))
597 .await
598 .map_err(|source| SubscriptionError::Subscribe {
599 source: Box::new(source),
600 })?;
601 pending.insert(request_id, account.clone());
602 }
603
604 while !pending.is_empty() {
605 match ws.next().await {
606 Some(Ok(Message::Text(text))) => {
607 if let Ok(confirmation) = serde_json::from_str::<SubscriptionConfirmation>(&text) {
608 let Some(account) = pending.remove(&confirmation.id) else {
609 continue;
610 };
611 let Some(subscription_id) = confirmation.result else {
612 return Err(SubscriptionError::TaskDropped);
613 };
614 subscriptions.insert(subscription_id, account);
615 continue;
616 }
617
618 if let Some(notification) =
619 parse_routed_account_diff_notification(&text, &subscriptions)
620 {
621 let _ = notification_tx.send(notification);
622 }
623 }
624 Some(Ok(_)) => {}
625 _ => return Err(SubscriptionError::TaskDropped),
626 }
627 }
628
629 Ok(subscriptions)
630}
631
632async fn drive_account_diff_stream_many(
633 ws: &mut AccountDiffWs,
634 subscriptions: &std::collections::HashMap<u64, String>,
635 notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
636 stop_rx: &mut watch::Receiver<bool>,
637) -> Result<(), SubscriptionRuntimeError> {
638 loop {
639 if *stop_rx.borrow() {
640 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
641 loop {
642 match tokio::time::timeout_at(
643 drain_deadline,
644 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
645 )
646 .await
647 {
648 Ok(Ok(Some(Ok(Message::Text(text))))) => {
649 if let Some(notification) =
650 parse_routed_account_diff_notification(&text, subscriptions)
651 {
652 let _ = notification_tx.send(notification);
653 }
654 }
655 _ => return Ok(()),
656 }
657 }
658 }
659
660 let msg = tokio::select! {
661 m = ws.next() => m,
662 _ = stop_rx.changed() => continue,
663 };
664
665 match msg {
666 Some(Ok(Message::Text(text))) => {
667 if let Some(notification) =
668 parse_routed_account_diff_notification(&text, subscriptions)
669 {
670 let _ = notification_tx.send(notification);
671 }
672 }
673 Some(Ok(_)) => {}
674 _ => {
675 return Err(subscription_runtime_closed(
676 "account diff",
677 format!("{} accounts", subscriptions.len()),
678 ));
679 }
680 }
681 }
682}
683
684fn parse_account_diff_message(text: &str) -> Option<AccountDiffMessage> {
685 let msg: AccountDiffMessage = serde_json::from_str(text).ok()?;
686 (msg.method == "accountDiffNotification").then_some(msg)
687}
688
689fn parse_routed_account_diff_notification(
690 text: &str,
691 subscriptions: &std::collections::HashMap<u64, String>,
692) -> Option<RoutedAccountDiffNotification> {
693 let msg = parse_account_diff_message(text)?;
694 let account = subscriptions.get(&msg.params.subscription)?.clone();
695 Some(RoutedAccountDiffNotification {
696 account,
697 notification: msg.params.result,
698 })
699}
700
701fn dedup_accounts<I, S>(accounts: I) -> Vec<String>
702where
703 I: IntoIterator<Item = S>,
704 S: Into<String>,
705{
706 let mut unique = std::collections::BTreeSet::new();
707 accounts
708 .into_iter()
709 .map(Into::into)
710 .filter(|account| unique.insert(account.clone()))
711 .collect()
712}
713
714pub async fn subscribe_program_diffs<F, Fut>(
747 rpc_endpoint: &str,
748 program_id: &str,
749 on_notification: F,
750) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
751where
752 F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
753 Fut: Future<Output = ()> + Send + 'static,
754{
755 let ws_url = http_to_ws_url(rpc_endpoint)?;
756 let program_id = program_id.to_string();
757
758 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
759 let (stop_tx, mut stop_rx) = watch::channel(false);
760
761 let join_handle = tokio::spawn(async move {
762 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
763 let callback_handle = tokio::spawn(async move {
764 while let Some(notification) = notification_rx.recv().await {
765 on_notification(notification).await;
766 }
767 });
768
769 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
770 Ok(connection) => connection,
771 Err(e) => {
772 let _ = ready_tx.send(Err(SubscriptionError::Connect {
773 url: ws_url,
774 source: Box::new(e),
775 }));
776 return Ok(());
777 }
778 };
779
780 if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
781 let _ = ready_tx.send(Err(error));
782 return Ok(());
783 }
784
785 let _ = ready_tx.send(Ok(()));
786
787 if let Err(error) =
788 drive_program_diff_stream(&mut ws, ¬ification_tx, &mut stop_rx, &program_id).await
789 {
790 drop(notification_tx);
791 if let Err(source) = callback_handle.await {
792 return Err(callback_worker_failed(
793 "program account diff",
794 &program_id,
795 source,
796 ));
797 }
798 return Err(error);
799 }
800
801 drop(notification_tx);
802 if let Err(source) = callback_handle.await {
803 return Err(callback_worker_failed(
804 "program account diff",
805 &program_id,
806 source,
807 ));
808 }
809
810 Ok(())
811 });
812
813 match ready_rx.await {
814 Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
815 join_handle,
816 stop: stop_tx,
817 }),
818 Ok(Err(e)) => {
819 join_handle.abort();
820 Err(e)
821 }
822 Err(_) => {
823 join_handle.abort();
824 Err(SubscriptionError::TaskDropped)
825 }
826 }
827}
828
829async fn send_program_diff_subscribe(
830 ws: &mut AccountDiffWs,
831 program_id: &str,
832) -> Result<(), SubscriptionError> {
833 #[derive(Deserialize)]
834 struct SubscriptionConfirmation {
835 result: Option<u64>,
836 }
837
838 let req = serde_json::json!({
839 "jsonrpc": "2.0",
840 "id": 1,
841 "method": "accountDiffSubscribe",
842 "params": [program_id, {"address_type": "program"}]
843 });
844 ws.send(Message::Text(req.to_string()))
845 .await
846 .map_err(|source| SubscriptionError::Subscribe {
847 source: Box::new(source),
848 })?;
849
850 loop {
851 match ws.next().await {
852 Some(Ok(Message::Text(text))) => {
853 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
854 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
855 Ok(_) => continue,
856 Err(source) => {
857 return Err(SubscriptionError::Subscribe {
858 source: Box::new(source),
859 });
860 }
861 }
862 }
863 Some(Ok(_)) => continue,
864 _ => return Err(SubscriptionError::TaskDropped),
865 }
866 }
867}
868
869async fn drive_program_diff_stream(
870 ws: &mut AccountDiffWs,
871 notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
872 stop_rx: &mut watch::Receiver<bool>,
873 program_id: &str,
874) -> Result<(), SubscriptionRuntimeError> {
875 loop {
876 if *stop_rx.borrow() {
877 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
878 loop {
879 match tokio::time::timeout_at(
880 drain_deadline,
881 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
882 )
883 .await
884 {
885 Ok(Ok(Some(Ok(Message::Text(text))))) => {
886 if let Some(msg) = parse_account_diff_message(&text) {
887 let _ = notification_tx.send(msg.params.result);
888 }
889 }
890 _ => return Ok(()),
891 }
892 }
893 }
894
895 let msg = tokio::select! {
896 m = ws.next() => m,
897 _ = stop_rx.changed() => continue,
898 };
899
900 match msg {
901 Some(Ok(Message::Text(text))) => {
902 if let Some(msg) = parse_account_diff_message(&text) {
903 let _ = notification_tx.send(msg.params.result);
904 }
905 }
906 Some(Ok(_)) => {}
907 _ => {
908 return Err(subscription_runtime_closed(
909 "program account diff",
910 program_id,
911 ));
912 }
913 }
914 }
915}
916
917#[derive(Clone, Copy)]
921struct NotificationStream {
922 subscribe_method: &'static str,
923 notification_method: &'static str,
924 kind: &'static str,
926 target: &'static str,
928}
929
930const ACTION_STREAM: NotificationStream = NotificationStream {
931 subscribe_method: "actionSubscribe",
932 notification_method: "actionNotification",
933 kind: "action",
934 target: "actions",
935};
936
937const REROUTE_STREAM: NotificationStream = NotificationStream {
938 subscribe_method: "rerouteSubscribe",
939 notification_method: "rerouteNotification",
940 kind: "reroute",
941 target: "reroutes",
942};
943
944#[derive(Deserialize)]
945struct NotificationMessage<N> {
946 method: String,
947 params: NotificationParams<N>,
948}
949
950#[derive(Deserialize)]
951struct NotificationParams<N> {
952 #[allow(dead_code)]
953 subscription: u64,
954 result: N,
955}
956
957fn parse_notification_message<N: DeserializeOwned>(
958 text: &str,
959 notification_method: &str,
960) -> Option<N> {
961 let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
962 (msg.method == notification_method).then_some(msg.params.result)
963}
964
965fn is_subscription_complete_message(text: &str) -> bool {
966 #[derive(Deserialize)]
967 struct SubscriptionCompleteMessage {
968 method: String,
969 }
970
971 serde_json::from_str::<SubscriptionCompleteMessage>(text)
972 .is_ok_and(|msg| msg.method == "subscriptionComplete")
973}
974
975async fn subscribe_notifications<N, F, Fut>(
980 rpc_endpoint: &str,
981 stream: NotificationStream,
982 on_notification: F,
983) -> Result<SubscriptionHandle, SubscriptionError>
984where
985 N: DeserializeOwned + Send + 'static,
986 F: Fn(N) -> Fut + Send + Sync + 'static,
987 Fut: Future<Output = ()> + Send + 'static,
988{
989 let ws_url = http_to_ws_url(rpc_endpoint)?;
990
991 let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
992 let (stop_tx, mut stop_rx) = watch::channel(false);
993
994 let join_handle = tokio::spawn(async move {
995 let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
996 let callback_handle = tokio::spawn(async move {
997 while let Some(notification) = notification_rx.recv().await {
998 on_notification(notification).await;
999 }
1000 });
1001
1002 let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
1003 Ok(connection) => connection,
1004 Err(e) => {
1005 let _ = ready_tx.send(Err(SubscriptionError::Connect {
1006 url: ws_url,
1007 source: Box::new(e),
1008 }));
1009 return Ok(());
1010 }
1011 };
1012
1013 if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
1014 let _ = ready_tx.send(Err(error));
1015 return Ok(());
1016 }
1017
1018 let _ = ready_tx.send(Ok(()));
1019
1020 if let Err(error) =
1021 drive_notification_stream::<N>(&mut ws, stream, ¬ification_tx, &mut stop_rx).await
1022 {
1023 drop(notification_tx);
1024 if let Err(source) = callback_handle.await {
1025 return Err(callback_worker_failed(stream.kind, stream.target, source));
1026 }
1027 return Err(error);
1028 }
1029
1030 drop(notification_tx);
1031 if let Err(source) = callback_handle.await {
1032 return Err(callback_worker_failed(stream.kind, stream.target, source));
1033 }
1034
1035 Ok(())
1036 });
1037
1038 match ready_rx.await {
1039 Ok(Ok(())) => Ok(SubscriptionHandle {
1040 join_handle,
1041 stop: stop_tx,
1042 }),
1043 Ok(Err(e)) => {
1044 join_handle.abort();
1045 Err(e)
1046 }
1047 Err(_) => {
1048 join_handle.abort();
1049 Err(SubscriptionError::TaskDropped)
1050 }
1051 }
1052}
1053
1054async fn send_stream_subscribe(
1055 ws: &mut AccountDiffWs,
1056 subscribe_method: &str,
1057) -> Result<(), SubscriptionError> {
1058 #[derive(Deserialize)]
1059 struct SubscriptionConfirmation {
1060 result: Option<u64>,
1061 }
1062
1063 let req = serde_json::json!({
1065 "jsonrpc": "2.0",
1066 "id": 1,
1067 "method": subscribe_method,
1068 "params": [serde_json::Value::Null, {}]
1069 });
1070
1071 ws.send(Message::Text(req.to_string()))
1072 .await
1073 .map_err(|source| SubscriptionError::Subscribe {
1074 source: Box::new(source),
1075 })?;
1076
1077 loop {
1078 match ws.next().await {
1079 Some(Ok(Message::Text(text))) => {
1080 match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1081 Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1082 Ok(_) => continue,
1083 Err(source) => {
1084 return Err(SubscriptionError::Subscribe {
1085 source: Box::new(source),
1086 });
1087 }
1088 }
1089 }
1090 Some(Ok(_)) => continue,
1091 _ => return Err(SubscriptionError::TaskDropped),
1092 }
1093 }
1094}
1095
1096async fn drive_notification_stream<N: DeserializeOwned>(
1097 ws: &mut AccountDiffWs,
1098 stream: NotificationStream,
1099 notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
1100 stop_rx: &mut watch::Receiver<bool>,
1101) -> Result<(), SubscriptionRuntimeError> {
1102 loop {
1103 if *stop_rx.borrow() {
1104 let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1105 loop {
1106 match tokio::time::timeout_at(
1107 drain_deadline,
1108 tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1109 )
1110 .await
1111 {
1112 Ok(Ok(Some(Ok(Message::Text(text))))) => {
1113 if is_subscription_complete_message(&text) {
1114 return Ok(());
1115 }
1116 if let Some(result) =
1117 parse_notification_message::<N>(&text, stream.notification_method)
1118 {
1119 let _ = notification_tx.send(result);
1120 }
1121 }
1122 _ => return Ok(()),
1123 }
1124 }
1125 }
1126
1127 let msg = tokio::select! {
1128 m = ws.next() => m,
1129 _ = stop_rx.changed() => continue,
1130 };
1131
1132 match msg {
1133 Some(Ok(Message::Text(text))) => {
1134 if is_subscription_complete_message(&text) {
1135 return Ok(());
1136 }
1137 if let Some(result) =
1138 parse_notification_message::<N>(&text, stream.notification_method)
1139 {
1140 let _ = notification_tx.send(result);
1141 }
1142 }
1143 Some(Ok(_)) => {}
1144 _ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
1145 }
1146 }
1147}
1148
1149pub struct ActionSubscriptionHandle {
1155 pub join_handle: SubscriptionTaskHandle,
1156 pub stop: watch::Sender<bool>,
1157}
1158
1159pub async fn subscribe_actions<F, Fut>(
1189 rpc_endpoint: &str,
1190 on_notification: F,
1191) -> Result<ActionSubscriptionHandle, SubscriptionError>
1192where
1193 F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
1194 Fut: Future<Output = ()> + Send + 'static,
1195{
1196 let SubscriptionHandle { join_handle, stop } =
1197 subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
1198 Ok(ActionSubscriptionHandle { join_handle, stop })
1199}
1200
1201#[derive(Debug, Clone, Serialize, Deserialize)]
1204pub struct RerouteContext {
1205 pub slot: u64,
1206}
1207
1208#[derive(Debug, Clone, Serialize, Deserialize)]
1210#[serde(rename_all = "camelCase")]
1211pub struct RerouteLegNotification {
1212 pub input_mint: String,
1213 pub output_mint: String,
1214 pub amount: u64,
1215 pub swap_mode: String,
1216 pub original_quoted_out: u64,
1217 pub metis_quoted_out: u64,
1218 pub route_summary: String,
1219 #[serde(default)]
1221 pub route_plan: Option<RoutePlan>,
1222 #[serde(default)]
1224 pub original_route_plan: Option<RoutePlan>,
1225 #[serde(default)]
1228 pub realized_route_plan: Option<RoutePlan>,
1229}
1230
1231#[derive(Debug, Clone, Serialize, Deserialize)]
1236#[serde(rename_all = "camelCase")]
1237pub struct RerouteNotification {
1238 pub context: RerouteContext,
1239 pub slot: u64,
1240 pub batch_index: u32,
1242 pub original_signature: String,
1244 #[serde(default)]
1246 pub legs: Vec<RerouteLegNotification>,
1247 pub routed_transaction: EncodedBinary,
1250 #[serde(default)]
1252 pub err: Option<String>,
1253 #[serde(default)]
1254 pub logs: Vec<String>,
1255 pub compute_units_consumed: u64,
1256 #[serde(default)]
1257 pub fee: Option<u64>,
1258 #[serde(default)]
1261 pub realized_output_amount: Option<u64>,
1262 #[serde(default)]
1266 pub original_realized_output_amount: Option<u64>,
1267 #[serde(default)]
1269 pub original_failed: bool,
1270}
1271
1272pub async fn subscribe_reroutes<F, Fut>(
1301 rpc_endpoint: &str,
1302 on_notification: F,
1303) -> Result<SubscriptionHandle, SubscriptionError>
1304where
1305 F: Fn(RerouteNotification) -> Fut + Send + Sync + 'static,
1306 Fut: Future<Output = ()> + Send + 'static,
1307{
1308 subscribe_notifications(rpc_endpoint, REROUTE_STREAM, on_notification).await
1309}
1310
1311#[cfg(test)]
1312mod tests {
1313 use super::*;
1314
1315 #[test]
1316 fn parse_account_diff_notification_ignores_other_messages() {
1317 let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
1318 assert!(parse_account_diff_message(confirmation).is_none());
1319 }
1320
1321 #[test]
1322 fn parse_account_diff_notification_extracts_payload() {
1323 let text = r#"{
1324 "jsonrpc":"2.0",
1325 "method":"accountDiffNotification",
1326 "params":{
1327 "subscription":7,
1328 "result":{
1329 "context":{"slot":123},
1330 "signature":"sig",
1331 "pre":{"a":1},
1332 "post":{"a":2}
1333 }
1334 }
1335 }"#;
1336
1337 let notification = parse_account_diff_message(text)
1338 .expect("notification")
1339 .params
1340 .result;
1341 assert_eq!(notification.context.slot, 123);
1342 assert_eq!(notification.signature.as_deref(), Some("sig"));
1343 assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
1344 assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
1345 }
1346
1347 #[test]
1348 fn parse_routed_account_diff_notification_extracts_subscription_account() {
1349 let text = r#"{
1350 "jsonrpc":"2.0",
1351 "method":"accountDiffNotification",
1352 "params":{
1353 "subscription":42,
1354 "result":{
1355 "context":{"slot":456},
1356 "signature":"sig",
1357 "pre":null,
1358 "post":{"a":2}
1359 }
1360 }
1361 }"#;
1362 let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
1363
1364 let notification =
1365 parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
1366 assert_eq!(notification.account, "acct");
1367 assert_eq!(notification.notification.context.slot, 456);
1368 }
1369
1370 #[test]
1371 fn converts_ui_account_json() {
1372 let value = serde_json::json!({
1373 "lamports": 5,
1374 "data": ["AQID", "base64"],
1375 "owner": "11111111111111111111111111111111",
1376 "executable": false,
1377 "rentEpoch": 0,
1378 });
1379 let account = account_data_from_ui(&value).unwrap();
1380 assert_eq!(account.lamports, 5);
1381 assert_eq!(account.space, 3);
1382 assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
1383 }
1384
1385 #[test]
1386 fn rejects_non_base64_encodings() {
1387 let value = serde_json::json!({
1388 "lamports": 5,
1389 "data": ["{}", "jsonParsed"],
1390 "owner": "11111111111111111111111111111111",
1391 "executable": false,
1392 "rentEpoch": 0,
1393 });
1394 assert!(matches!(
1395 account_data_from_ui(&value),
1396 Err(UiAccountConversionError::UnsupportedEncoding)
1397 ));
1398 }
1399
1400 #[test]
1401 fn dedup_accounts_preserves_first_seen_order() {
1402 let accounts = dedup_accounts([
1403 "b".to_string(),
1404 "a".to_string(),
1405 "b".to_string(),
1406 "c".to_string(),
1407 ]);
1408 assert_eq!(accounts, vec!["b", "a", "c"]);
1409 }
1410
1411 #[test]
1414 fn a_reroute_notification_round_trips_through_its_own_encoding() {
1415 use serde_json::{Value, json};
1416
1417 fn hop(set: Value, program: Value) -> Value {
1419 let mut swap_info = json!({
1420 "label": null, "ammKey": null, "inputMint": null,
1421 "inAmount": null, "outputMint": null, "outAmount": null,
1422 });
1423 for (key, value) in set.as_object().expect("an object") {
1424 swap_info[key] = value.clone();
1425 }
1426 json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
1427 }
1428
1429 let wire = serde_json::json!({
1430 "context": {"slot": 42},
1431 "slot": 42,
1432 "batchIndex": 3,
1433 "originalSignature": "sig",
1434 "legs": [{
1435 "inputMint": "in",
1436 "outputMint": "out",
1437 "amount": 1_000,
1438 "swapMode": "ExactIn",
1439 "originalQuotedOut": 990,
1440 "metisQuotedOut": 1_010,
1441 "routeSummary": "SolFi",
1442 "routePlan": [hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
1444 "originalRoutePlan": [hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
1445 "realizedRoutePlan": [hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
1446 }],
1447 "routedTransaction": {"data": "AA==", "encoding": "base64"},
1448 "err": serde_json::Value::Null,
1449 "logs": ["Program log: swap"],
1450 "computeUnitsConsumed": 123_456,
1451 "fee": 5_000,
1452 "realizedOutputAmount": 1_009,
1453 "originalRealizedOutputAmount": 991,
1454 "originalFailed": false,
1455 });
1456
1457 let notification: RerouteNotification =
1458 serde_json::from_value(wire.clone()).expect("wire decodes");
1459 let recorded = serde_json::to_value(¬ification).expect("notification encodes");
1460 assert_eq!(recorded, wire);
1461
1462 let read_back: RerouteNotification =
1463 serde_json::from_value(recorded).expect("recording decodes");
1464 assert_eq!(read_back.batch_index, 3);
1465 assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
1466 assert_eq!(read_back.original_realized_output_amount, Some(991));
1467 assert!(
1470 read_back
1471 .legs
1472 .iter()
1473 .all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
1474 );
1475 }
1476}