Skip to main content

simulator_client/
subscriptions.rs

1use std::{future::Future, time::Duration};
2
3use futures::{SinkExt, StreamExt};
4use serde::{Deserialize, 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/// Error establishing a PubSub log subscription.
23#[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
69/// A unified subscription handle that can represent any subscription type.
70pub 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
102/// Handle for a running log subscription background task.
103pub struct LogSubscriptionHandle {
104    /// Background task that drives the subscription and spawns per-notification callbacks.
105    ///
106    /// Resolves after `stop.send(true)` is called, remaining buffered
107    /// notifications are drained, and all spawned callback tasks complete.
108    pub join_handle: SubscriptionTaskHandle,
109
110    /// Send `true` to signal the background task to stop accepting new
111    /// notifications, drain remaining buffered ones, and exit cleanly.
112    pub stop: watch::Sender<bool>,
113}
114
115/// Subscribe to program log notifications and invoke a callback for each one.
116///
117/// Spawns a background task that:
118/// 1. Connects to the PubSub endpoint derived from `rpc_endpoint`.
119/// 2. Subscribes to logs mentioning `program_id`.
120/// 3. For each notification, spawns `on_notification(notification)` as a Tokio task.
121/// 4. When `handle.stop.send(true)` is called, drains remaining buffered
122///    notifications (up to 1s), waits for all spawned tasks, then returns.
123///
124/// Returns after the subscription is established. If setup fails, an error is
125/// returned before any background task is left running.
126///
127/// ## Example
128///
129/// ```no_run
130/// use std::sync::{Arc, Mutex};
131/// use simulator_client::subscribe_program_logs;
132/// use solana_commitment_config::CommitmentConfig;
133///
134/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
135/// let handle = subscribe_program_logs(
136///     "https://api.mainnet-beta.solana.com",
137///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
138///     CommitmentConfig::confirmed(),
139///     |notification| async move {
140///         println!("sig: {}", notification.value.signature);
141///     },
142/// )
143/// .await?;
144///
145/// // ... do other work ...
146///
147/// handle.stop.send(true).ok();
148/// handle.join_handle.await.ok();
149/// # Ok(())
150/// # }
151/// ```
152pub 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    // PubsubClient::logs_subscribe borrows &self, so both the client and the
169    // stream must live inside the spawned task. We report setup success/failure
170    // back through a oneshot channel before entering the notification loop.
171    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        // Wait for all in-flight callback tasks to complete.
232        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// ── Account diff subscription ────────────────────────────────────────────────
258
259/// Slot context included in every account diff notification.
260#[derive(Debug, Clone, Deserialize)]
261pub struct AccountDiffContext {
262    pub slot: u64,
263}
264
265/// A single account diff notification delivered by `accountDiffSubscribe`.
266#[derive(Debug, Clone, Deserialize)]
267pub struct AccountDiffNotification {
268    pub context: AccountDiffContext,
269    /// The address of the account that changed.
270    pub account: Option<String>,
271    /// Signature of the transaction that triggered this change, if known.
272    pub signature: Option<String>,
273    /// Position of the transaction within its slot, if known.
274    #[serde(default)]
275    pub tx_index: Option<u32>,
276    /// Unix-seconds block time of the slot, if known.
277    #[serde(default)]
278    pub block_time: Option<i64>,
279    /// Account state before the change (absent for newly created accounts).
280    pub pre: Option<serde_json::Value>,
281    /// Account state after the change (absent for deleted accounts).
282    pub post: Option<serde_json::Value>,
283}
284
285impl AccountDiffNotification {
286    /// Decode the post-state into the wire [`AccountData`] shape, when present.
287    pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
288        self.post.as_ref().map(account_data_from_ui)
289    }
290}
291
292/// Error decoding a serialized [`UiAccount`] into the wire [`AccountData`] shape.
293#[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
308/// Decode a serde-serialized [`UiAccount`] (the `pre`/`post` payload shape) into
309/// the wire [`AccountData`] shape. Only base64 data is supported; `space` falls
310/// back to the decoded data length when absent.
311pub 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/// One scheduled-action result delivered by `actionSubscribe`.
338#[derive(Debug, Clone, Deserialize)]
339#[serde(rename_all = "camelCase")]
340pub struct ActionResultNotification {
341    pub context: ActionResultContext,
342    pub slot: u64,
343    /// Batch the action fired at; `None` for slot-boundary actions.
344    #[serde(default)]
345    pub batch_index: Option<u32>,
346    /// Index of the action in the session's `actions` list.
347    pub action_index: u32,
348    #[serde(default)]
349    pub label: Option<String>,
350    pub committed: bool,
351    /// One per transaction in the action's sequence, in order. A failing
352    /// transaction is the last entry; later transactions don't run.
353    #[serde(default)]
354    pub transaction_outcomes: Vec<ActionTransactionOutcome>,
355    /// Post-execution `UiAccount` JSON per `return_accounts` address, positional;
356    /// cumulative state after the final transaction.
357    #[serde(default)]
358    pub accounts: Vec<Option<serde_json::Value>>,
359    /// Encoded transaction whose discovery-filter match triggered this action;
360    /// absent for slot-boundary actions. Decode with [`EncodedBinary::decode`]
361    /// (base64 bincode of `TxWithMeta`) to inspect the matching transaction.
362    #[serde(default)]
363    pub matched: Option<EncodedBinary>,
364}
365
366/// One transaction's result within a scheduled action's sequence.
367#[derive(Debug, Clone, Deserialize)]
368#[serde(rename_all = "camelCase")]
369pub struct ActionTransactionOutcome {
370    /// Transaction failure message; `None` on success.
371    #[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    /// Program return data (`{programId, data}`), if any.
379    #[serde(default)]
380    pub return_data: Option<serde_json::Value>,
381}
382
383/// A routed account diff notification tied to the subscribed account that produced it.
384#[derive(Debug, Clone)]
385pub struct RoutedAccountDiffNotification {
386    pub account: String,
387    pub notification: AccountDiffNotification,
388}
389
390/// Handle for a running account diff subscription background task.
391///
392/// Send `true` on `stop` to request a clean shutdown, then await `join_handle`.
393pub 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
420/// Subscribe to account diff notifications and invoke a callback for each one.
421///
422/// Spawns a background task that:
423/// 1. Connects to the WebSocket endpoint derived from `rpc_endpoint`.
424/// 2. Subscribes to account diffs for the given filter (account or program).
425/// 3. For each notification, spawns `on_notification(notification)` as a Tokio task.
426/// 4. When `handle.stop.send(true)` is called, drains remaining buffered
427///    notifications (up to 1s), waits for all spawned tasks, then returns.
428///
429/// ## Example
430///
431/// ```no_run
432/// use simulator_client::subscribe_account_diffs;
433///
434/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
435/// let handle = subscribe_account_diffs(
436///     "http://localhost:8900/session/abc",
437///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
438///     |notification| async move {
439///         println!("slot={} sig={:?}", notification.context.slot, notification.signature);
440///     },
441/// )
442/// .await?;
443///
444/// handle.stop.send(true).ok();
445/// handle.join_handle.await.ok();
446/// # Ok(())
447/// # }
448/// ```
449pub 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
464/// Subscribe to account diff notifications for many accounts over a single websocket.
465///
466/// All requested subscriptions must be acknowledged before this returns. Once the
467/// stream is live, any websocket disconnect is treated as a fatal completeness
468/// error instead of silently reconnecting and risking dropped notifications.
469pub 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, &notification_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, &notification_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
714// ── Program account diff subscription ────────────────────────────────────────
715
716/// Subscribe to account diff notifications for all accounts owned by a program.
717///
718/// Uses the server-side program filter (`{"address_type": "program"}`), so no
719/// RPC prefetch of program accounts is required.  The callback receives one
720/// [`AccountDiffNotification`] per changed account.
721///
722/// A websocket disconnect is treated as a fatal error — the handle's
723/// `join_handle` resolves with a [`SubscriptionRuntimeError`].
724///
725/// ## Example
726///
727/// ```no_run
728/// use simulator_client::subscribe_program_diffs;
729///
730/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
731/// let handle = subscribe_program_diffs(
732///     "http://localhost:8900/session/abc",
733///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
734///     |notification| async move {
735///         let account = notification.account.unwrap_or_default();
736///         println!("account={account} slot={}", notification.context.slot);
737///     },
738/// )
739/// .await?;
740///
741/// handle.stop.send(true).ok();
742/// handle.join_handle.await.ok();
743/// # Ok(())
744/// # }
745/// ```
746pub 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, &notification_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// ── Keyless notification streams ─────────────────────────────────────────────
918
919/// The strings that distinguish one keyless notification stream from another.
920#[derive(Clone, Copy)]
921struct NotificationStream {
922    subscribe_method: &'static str,
923    notification_method: &'static str,
924    /// Singular label used in runtime errors.
925    kind: &'static str,
926    /// Plural label used in runtime errors.
927    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
975/// Drive a keyless notification stream, invoking `on_notification` for each payload.
976///
977/// Implements the protocol every single-stream subscription shares; once `stop` is set, drains
978/// whatever the server has already queued before resolving.
979async 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, &notification_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    // Keyless: index 0 is an unused placeholder, index 1 the (empty) config object.
1064    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
1149// ── Action subscription ──────────────────────────────────────────────────────
1150
1151/// Handle for a running scheduled-action subscription background task.
1152///
1153/// Send `true` on `stop` to request a clean shutdown, then await `join_handle`.
1154pub struct ActionSubscriptionHandle {
1155    pub join_handle: SubscriptionTaskHandle,
1156    pub stop: watch::Sender<bool>,
1157}
1158
1159/// Subscribe to scheduled-action results streamed over `actionSubscribe`.
1160///
1161/// The session automatically runs the `ScheduledAction`s registered at creation;
1162/// each result is delivered to `on_notification` as an [`ActionResultNotification`].
1163/// This is a single, keyless subscription — every action shares one stream, so the
1164/// callback distinguishes them via `action_index` / `label`.
1165///
1166/// A websocket disconnect is treated as a fatal error — the handle's `join_handle`
1167/// resolves with a [`SubscriptionRuntimeError`].
1168///
1169/// ## Example
1170///
1171/// ```no_run
1172/// use simulator_client::subscribe_actions;
1173///
1174/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1175/// let handle = subscribe_actions(
1176///     "http://localhost:8900/session/abc",
1177///     |result| async move {
1178///         println!("slot={} label={:?}", result.slot, result.label);
1179///     },
1180/// )
1181/// .await?;
1182///
1183/// handle.stop.send(true).ok();
1184/// handle.join_handle.await.ok();
1185/// # Ok(())
1186/// # }
1187/// ```
1188pub 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// ── Reroute subscription ─────────────────────────────────────────────────────
1202
1203#[derive(Debug, Clone, Deserialize)]
1204pub struct RerouteContext {
1205    pub slot: u64,
1206}
1207
1208/// One re-quoted swap within a rerouted transaction's simulation.
1209#[derive(Debug, Clone, 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    /// The raw metis `routePlan` JSON array (per-hop mints, pool `ammKey`, amounts, split
1220    /// percent), when metis returned one.
1221    #[serde(default)]
1222    pub route_plan: Option<String>,
1223}
1224
1225/// One rerouted transaction's simulation result, delivered by `rerouteSubscribe`. The historical
1226/// original still executed; this is the counterfactual, committed nowhere.
1227#[derive(Debug, Clone, Deserialize)]
1228#[serde(rename_all = "camelCase")]
1229pub struct RerouteNotification {
1230    pub context: RerouteContext,
1231    pub slot: u64,
1232    /// Batch within the slot the original sits in; the simulation ran just before it executed.
1233    pub batch_index: u32,
1234    /// Base58 signature of the historical transaction whose swap(s) were re-routed.
1235    pub original_signature: String,
1236    /// One per detected swap in the original, in order.
1237    #[serde(default)]
1238    pub legs: Vec<RerouteLegNotification>,
1239    /// The metis-routed transaction that was simulated. Decode with [`EncodedBinary::decode`]
1240    /// (base64 bincode of `TxWithMeta`) to inspect its instructions.
1241    pub routed_transaction: EncodedBinary,
1242    /// Simulation error message; `None` on success.
1243    #[serde(default)]
1244    pub err: Option<String>,
1245    #[serde(default)]
1246    pub logs: Vec<String>,
1247    pub compute_units_consumed: u64,
1248    #[serde(default)]
1249    pub fee: Option<u64>,
1250    /// What the routed swap actually produced; `None` for a multi-swap tx, a missing output
1251    /// balance record, or a reverted simulation.
1252    #[serde(default)]
1253    pub realized_output_amount: Option<u64>,
1254    /// What the historical original actually produced; `None` for a multi-swap tx, a missing
1255    /// output balance record, or a reverted original. Set independently of the simulation's
1256    /// outcome, so it is present even when `err` is.
1257    #[serde(default)]
1258    pub original_realized_output_amount: Option<u64>,
1259}
1260
1261/// Subscribe to simulated-reroute results streamed over `rerouteSubscribe`.
1262///
1263/// Each simulation is delivered to `on_notification` as a [`RerouteNotification`]. This is a
1264/// single, keyless subscription — every result shares one stream, distinguished by
1265/// `slot` / `batch_index` / `original_signature`.
1266///
1267/// A websocket disconnect is treated as a fatal error — the handle's `join_handle` resolves with
1268/// a [`SubscriptionRuntimeError`].
1269///
1270/// ## Example
1271///
1272/// ```no_run
1273/// use simulator_client::subscribe_reroutes;
1274///
1275/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1276/// let handle = subscribe_reroutes(
1277///     "http://localhost:8900/session/abc",
1278///     |result| async move {
1279///         println!("slot={} sig={}", result.slot, result.original_signature);
1280///     },
1281/// )
1282/// .await?;
1283///
1284/// handle.stop.send(true).ok();
1285/// handle.join_handle.await.ok();
1286/// # Ok(())
1287/// # }
1288/// ```
1289pub async fn subscribe_reroutes<F, Fut>(
1290    rpc_endpoint: &str,
1291    on_notification: F,
1292) -> Result<SubscriptionHandle, SubscriptionError>
1293where
1294    F: Fn(RerouteNotification) -> Fut + Send + Sync + 'static,
1295    Fut: Future<Output = ()> + Send + 'static,
1296{
1297    subscribe_notifications(rpc_endpoint, REROUTE_STREAM, on_notification).await
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302    use super::*;
1303
1304    #[test]
1305    fn parse_account_diff_notification_ignores_other_messages() {
1306        let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
1307        assert!(parse_account_diff_message(confirmation).is_none());
1308    }
1309
1310    #[test]
1311    fn parse_account_diff_notification_extracts_payload() {
1312        let text = r#"{
1313            "jsonrpc":"2.0",
1314            "method":"accountDiffNotification",
1315            "params":{
1316                "subscription":7,
1317                "result":{
1318                    "context":{"slot":123},
1319                    "signature":"sig",
1320                    "pre":{"a":1},
1321                    "post":{"a":2}
1322                }
1323            }
1324        }"#;
1325
1326        let notification = parse_account_diff_message(text)
1327            .expect("notification")
1328            .params
1329            .result;
1330        assert_eq!(notification.context.slot, 123);
1331        assert_eq!(notification.signature.as_deref(), Some("sig"));
1332        assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
1333        assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
1334    }
1335
1336    #[test]
1337    fn parse_routed_account_diff_notification_extracts_subscription_account() {
1338        let text = r#"{
1339            "jsonrpc":"2.0",
1340            "method":"accountDiffNotification",
1341            "params":{
1342                "subscription":42,
1343                "result":{
1344                    "context":{"slot":456},
1345                    "signature":"sig",
1346                    "pre":null,
1347                    "post":{"a":2}
1348                }
1349            }
1350        }"#;
1351        let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
1352
1353        let notification =
1354            parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
1355        assert_eq!(notification.account, "acct");
1356        assert_eq!(notification.notification.context.slot, 456);
1357    }
1358
1359    #[test]
1360    fn converts_ui_account_json() {
1361        let value = serde_json::json!({
1362            "lamports": 5,
1363            "data": ["AQID", "base64"],
1364            "owner": "11111111111111111111111111111111",
1365            "executable": false,
1366            "rentEpoch": 0,
1367        });
1368        let account = account_data_from_ui(&value).unwrap();
1369        assert_eq!(account.lamports, 5);
1370        assert_eq!(account.space, 3);
1371        assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
1372    }
1373
1374    #[test]
1375    fn rejects_non_base64_encodings() {
1376        let value = serde_json::json!({
1377            "lamports": 5,
1378            "data": ["{}", "jsonParsed"],
1379            "owner": "11111111111111111111111111111111",
1380            "executable": false,
1381            "rentEpoch": 0,
1382        });
1383        assert!(matches!(
1384            account_data_from_ui(&value),
1385            Err(UiAccountConversionError::UnsupportedEncoding)
1386        ));
1387    }
1388
1389    #[test]
1390    fn dedup_accounts_preserves_first_seen_order() {
1391        let accounts = dedup_accounts([
1392            "b".to_string(),
1393            "a".to_string(),
1394            "b".to_string(),
1395            "c".to_string(),
1396        ]);
1397        assert_eq!(accounts, vec!["b", "a", "c"]);
1398    }
1399}