Skip to main content

simulator_client/
subscriptions.rs

1//! Standalone subscriptions to a session's RPC endpoint.
2//!
3//! Each `subscribe_*` function opens its own WebSocket to the session's RPC endpoint
4//! ([`SessionInfo::rpc_endpoint`](crate::managed::SessionInfo::rpc_endpoint)), runs your callback
5//! once per notification on a background task, and returns a handle.
6//!
7//! - These functions never reconnect. If the server closes the socket, the handle's
8//!   [`shutdown`](SubscriptionHandle::shutdown) returns [`SubscriptionRuntimeError::Closed`] and
9//!   the notifications after the close are lost. On a [`ManagedBacktestSession`], prefer its
10//!   `subscribe_*` methods, which reconnect and deliver results as [`ManagedEvent`]s.
11//! - Subscribe before you continue the session, or you miss the notifications sent before the
12//!   subscription was confirmed.
13//! - Always finish with `handle.shutdown().await?`, before you close the session. Dropping a
14//!   handle does not stop its task.
15//!
16//! Per-account diffs ([`subscribe_account_diffs`], [`subscribe_account_diffs_many`]) and program
17//! logs ([`subscribe_program_logs`]) are only available here.
18//!
19//! [`ManagedBacktestSession`]: crate::ManagedBacktestSession
20//! [`ManagedEvent`]: crate::ManagedEvent
21
22use std::{future::Future, time::Duration};
23
24use futures::{SinkExt, StreamExt};
25use serde::{Deserialize, Serialize, de::DeserializeOwned};
26use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
27use solana_account_decoder::{UiAccount, UiAccountData, UiAccountEncoding};
28use solana_client::{
29    nonblocking::pubsub_client::PubsubClient,
30    rpc_response::{Response, RpcLogsResponse},
31};
32use solana_commitment_config::CommitmentConfig;
33use solana_rpc_client_api::config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
34use solana_transaction::versioned::VersionedTransaction;
35use thiserror::Error;
36use tokio::{
37    sync::{oneshot, watch},
38    task::JoinHandle,
39};
40use tokio_tungstenite::tungstenite::Message;
41
42use crate::{
43    tx::{TxDecodeError, decode_transaction},
44    urls::{UrlError, http_to_ws_url},
45};
46
47/// Error starting a subscription. Returned by the `subscribe_*` functions before any
48/// notification is delivered; no background task is left running.
49#[derive(Debug, Error)]
50#[allow(missing_docs)]
51pub enum SubscriptionError {
52    /// The RPC endpoint is not an `http://` or `https://` URL. Stop: pass the session's RPC
53    /// endpoint as reported by the server.
54    #[error(transparent)]
55    InvalidUrl(#[from] UrlError),
56
57    /// The WebSocket to the session's RPC endpoint could not be opened. Retry with backoff.
58    /// If it keeps failing, the session is not serving yet (wait for the first
59    /// `ReadyForContinue`) or has ended.
60    #[error("pubsub connect to {url} failed: {source}")]
61    Connect {
62        /// The WebSocket URL derived from the RPC endpoint.
63        url: String,
64        #[source]
65        source: Box<dyn std::error::Error + Send + Sync>,
66    },
67
68    /// The subscribe request could not be sent, or the server's reply was not valid JSON-RPC.
69    /// Retry once; if it fails again, stop.
70    #[error("logs_subscribe failed: {source}")]
71    Subscribe {
72        /// The send or decode error.
73        #[source]
74        source: Box<dyn std::error::Error + Send + Sync>,
75    },
76
77    /// The server closed the socket, or refused the subscription, before confirming it. Retry
78    /// while the session is live; stop once it has ended.
79    #[error("subscription task exited unexpectedly before signaling ready")]
80    TaskDropped,
81
82    /// The session has no RPC endpoint yet. Stop: create the session first, then subscribe.
83    #[error("session has no rpc_endpoint (was the session created?)")]
84    NoRpcEndpoint,
85}
86
87/// Error from a running subscription, returned by the handle's
88/// [`shutdown`](SubscriptionHandle::shutdown).
89///
90/// Any of these means the capture is incomplete: notifications were lost.
91#[derive(Debug, Error)]
92pub enum SubscriptionRuntimeError {
93    /// The server closed the socket before you called `shutdown`. The functions in this module
94    /// never reconnect, so every notification after the close is lost. Typical cause: the
95    /// session ended, or the connection dropped. Re-subscribing does not recover the gap; use a
96    /// [`ManagedBacktestSession`](crate::ManagedBacktestSession) subscription to survive drops.
97    #[error("{kind} subscription for {target} closed unexpectedly")]
98    Closed {
99        /// The subscription type, such as `"account diff"`.
100        kind: &'static str,
101        /// What was subscribed: a program ID, an account count, or the stream name.
102        target: String,
103    },
104
105    /// Your callback panicked. Fix the callback. The notification it was handling was lost,
106    /// and on every stream except program logs, so was every later one.
107    #[error("{kind} subscription callback worker for {target} failed: {source}")]
108    CallbackWorker {
109        /// The subscription type, such as `"account diff"`.
110        kind: &'static str,
111        /// What was subscribed: a program ID, an account count, or the stream name.
112        target: String,
113        /// The panic or cancellation.
114        #[source]
115        source: tokio::task::JoinError,
116    },
117
118    /// The subscription's own task panicked or was aborted (a callback panic is
119    /// [`Self::CallbackWorker`]). Stop.
120    #[error("subscription task failed: {0}")]
121    Task(#[from] tokio::task::JoinError),
122}
123
124const SUBSCRIPTION_DRAIN_IDLE_TIMEOUT: Duration = Duration::from_millis(250);
125const SUBSCRIPTION_DRAIN_MAX_DURATION: Duration = Duration::from_secs(5);
126
127type SubscriptionTaskHandle = JoinHandle<Result<(), SubscriptionRuntimeError>>;
128type AccountDiffWs =
129    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
130
131/// Handle for a running subscription; every typed handle converts into it with `From`.
132///
133/// Finish with [`Self::shutdown`]. Dropping a handle does not stop its task: it keeps running,
134/// and calling your callback, until the server closes the socket, and its errors are lost.
135pub struct SubscriptionHandle {
136    /// The background task. Resolves after a stop, once buffered notifications are drained and
137    /// every callback has returned. Prefer [`Self::shutdown`], which also signals the stop.
138    pub join_handle: SubscriptionTaskHandle,
139    /// Stop signal: sending `true` stops accepting new notifications and starts the drain.
140    /// Prefer [`Self::shutdown`].
141    pub stop: watch::Sender<bool>,
142}
143
144impl SubscriptionHandle {
145    /// Stop, drain what is buffered (250ms idle / 5s cap), and wait for every callback.
146    ///
147    /// Call it before you close the session, so the last notifications are still delivered.
148    ///
149    /// # Errors
150    ///
151    /// Any [`SubscriptionRuntimeError`]. [`SubscriptionRuntimeError::Closed`] means the server
152    /// closed the socket before this call, so the capture is incomplete.
153    pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
154        // Cannot fail, unlike `send`, which errors once the task has dropped its receiver.
155        self.stop.send_replace(true);
156        self.join_handle.await?
157    }
158}
159
160impl LogSubscriptionHandle {
161    /// See [`SubscriptionHandle::shutdown`].
162    pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
163        SubscriptionHandle::from(self).shutdown().await
164    }
165}
166
167impl From<LogSubscriptionHandle> for SubscriptionHandle {
168    fn from(h: LogSubscriptionHandle) -> Self {
169        Self {
170            join_handle: h.join_handle,
171            stop: h.stop,
172        }
173    }
174}
175
176impl AccountDiffSubscriptionHandle {
177    /// See [`SubscriptionHandle::shutdown`].
178    pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
179        SubscriptionHandle::from(self).shutdown().await
180    }
181}
182
183impl From<AccountDiffSubscriptionHandle> for SubscriptionHandle {
184    fn from(h: AccountDiffSubscriptionHandle) -> Self {
185        Self {
186            join_handle: h.join_handle,
187            stop: h.stop,
188        }
189    }
190}
191
192impl ActionSubscriptionHandle {
193    /// See [`SubscriptionHandle::shutdown`].
194    pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
195        SubscriptionHandle::from(self).shutdown().await
196    }
197}
198
199impl From<ActionSubscriptionHandle> for SubscriptionHandle {
200    fn from(h: ActionSubscriptionHandle) -> Self {
201        Self {
202            join_handle: h.join_handle,
203            stop: h.stop,
204        }
205    }
206}
207
208impl DiagnosticSubscriptionHandle {
209    /// See [`SubscriptionHandle::shutdown`].
210    pub async fn shutdown(self) -> Result<(), SubscriptionRuntimeError> {
211        SubscriptionHandle::from(self).shutdown().await
212    }
213}
214
215impl From<DiagnosticSubscriptionHandle> for SubscriptionHandle {
216    fn from(h: DiagnosticSubscriptionHandle) -> Self {
217        Self {
218            join_handle: h.join_handle,
219            stop: h.stop,
220        }
221    }
222}
223
224/// Handle for a running [`subscribe_program_logs`] subscription.
225///
226/// Finish with [`Self::shutdown`]; see [`SubscriptionHandle`] for the fields and what dropping
227/// it does.
228pub struct LogSubscriptionHandle {
229    /// The background task. Resolves after a stop, once buffered notifications are drained and
230    /// every callback has returned. Prefer [`Self::shutdown`], which also signals the stop.
231    pub join_handle: SubscriptionTaskHandle,
232
233    /// Stop signal: sending `true` stops accepting new notifications and starts the drain.
234    /// Prefer [`Self::shutdown`].
235    pub stop: watch::Sender<bool>,
236}
237
238/// Subscribe to the logs of every transaction that mentions `program_id`.
239///
240/// `rpc_endpoint` is the session's RPC endpoint. Each notification runs
241/// `on_notification` as its own Tokio task, so callbacks can run concurrently and out of order.
242/// Returns once the server confirms the subscription. Never reconnects; see the
243/// [module docs](crate::subscriptions).
244///
245/// On a [`ManagedBacktestSession`](crate::ManagedBacktestSession), you can instead read logs
246/// from `meta.log_messages` of the transactions its `subscribe_transactions` delivers, which
247/// survives reconnects.
248///
249/// # Errors
250///
251/// [`SubscriptionError`] if the subscription cannot be started.
252///
253/// ## Example
254///
255/// ```no_run
256/// use simulator_client::{ManagedBacktestSession, subscribe_program_logs};
257/// use solana_commitment_config::CommitmentConfig;
258///
259/// # async fn example(session: &ManagedBacktestSession) -> Result<(), Box<dyn std::error::Error>> {
260/// let handle = subscribe_program_logs(
261///     &session.session_info().rpc_endpoint,
262///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
263///     CommitmentConfig::confirmed(),
264///     |notification| async move {
265///         println!("sig: {}", notification.value.signature);
266///     },
267/// )
268/// .await?;
269///
270/// // ... do other work ...
271///
272/// handle.shutdown().await?;
273/// # Ok(())
274/// # }
275/// ```
276pub async fn subscribe_program_logs<F, Fut>(
277    rpc_endpoint: &str,
278    program_id: &str,
279    commitment: CommitmentConfig,
280    on_notification: F,
281) -> Result<LogSubscriptionHandle, SubscriptionError>
282where
283    F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
284    Fut: Future<Output = ()> + Send + 'static,
285{
286    let ws_url = http_to_ws_url(rpc_endpoint)?;
287    let program_id = program_id.to_string();
288
289    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
290    let (stop_tx, mut stop_rx) = watch::channel(false);
291
292    // PubsubClient::logs_subscribe borrows &self, so both the client and the
293    // stream must live inside the spawned task. We report setup success/failure
294    // back through a oneshot channel before entering the notification loop.
295    let join_handle = tokio::spawn(async move {
296        let client = match PubsubClient::new(&ws_url).await {
297            Ok(c) => c,
298            Err(e) => {
299                let _ = ready_tx.send(Err(SubscriptionError::Connect {
300                    url: ws_url,
301                    source: Box::new(e),
302                }));
303                return Ok(());
304            }
305        };
306
307        let (mut stream, _unsubscribe) = match client
308            .logs_subscribe(
309                RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
310                RpcTransactionLogsConfig {
311                    commitment: Some(commitment),
312                },
313            )
314            .await
315        {
316            Ok(s) => s,
317            Err(e) => {
318                let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
319                    source: Box::new(e),
320                }));
321                return Ok(());
322            }
323        };
324
325        let _ = ready_tx.send(Ok(()));
326
327        let mut tasks: Vec<JoinHandle<()>> = Vec::new();
328        let kind = "program logs";
329
330        loop {
331            if *stop_rx.borrow() {
332                let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
333                while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
334                    drain_deadline,
335                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
336                )
337                .await
338                {
339                    tasks.push(tokio::spawn(on_notification(notification)));
340                }
341                break;
342            }
343
344            let notification = tokio::select! {
345                n = stream.next() => n,
346                _ = stop_rx.changed() => continue,
347            };
348
349            match notification {
350                Some(n) => tasks.push(tokio::spawn(on_notification(n))),
351                None => return Err(subscription_runtime_closed(kind, &program_id)),
352            }
353        }
354
355        // Wait for all in-flight callback tasks to complete.
356        for task in tasks {
357            if let Err(source) = task.await {
358                return Err(callback_worker_failed(kind, &program_id, source));
359            }
360        }
361
362        Ok(())
363    });
364
365    match ready_rx.await {
366        Ok(Ok(())) => Ok(LogSubscriptionHandle {
367            join_handle,
368            stop: stop_tx,
369        }),
370        Ok(Err(e)) => {
371            join_handle.abort();
372            Err(e)
373        }
374        Err(_) => {
375            join_handle.abort();
376            Err(SubscriptionError::TaskDropped)
377        }
378    }
379}
380
381// ── Account diff subscription ────────────────────────────────────────────────
382
383/// Slot context included in every account diff notification.
384#[derive(Debug, Clone, Deserialize)]
385pub struct AccountDiffContext {
386    #[allow(missing_docs)]
387    pub slot: u64,
388}
389
390/// A single account diff notification delivered by `accountDiffSubscribe`.
391///
392/// `pre` and `post` are `UiAccount` JSON; decode them with [`account_data_from_ui`] or
393/// [`Self::post_account_data`].
394#[derive(Debug, Clone, Deserialize)]
395pub struct AccountDiffNotification {
396    #[allow(missing_docs)]
397    pub context: AccountDiffContext,
398    /// The address of the account that changed.
399    pub account: Option<String>,
400    /// Signature of the transaction that triggered this change, if known.
401    pub signature: Option<String>,
402    /// Position of the transaction within its slot, if known.
403    #[serde(default)]
404    pub tx_index: Option<u32>,
405    /// Unix-seconds block time of the slot, if known.
406    #[serde(default)]
407    pub block_time: Option<i64>,
408    /// Account state before the change (absent for newly created accounts).
409    pub pre: Option<serde_json::Value>,
410    /// Account state after the change (absent for deleted accounts).
411    pub post: Option<serde_json::Value>,
412}
413
414impl AccountDiffNotification {
415    /// Decode the post-state into the wire [`AccountData`] shape; `None` for a deleted account.
416    pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
417        self.post.as_ref().map(account_data_from_ui)
418    }
419}
420
421/// Error decoding a serialized [`UiAccount`] into the wire [`AccountData`] shape.
422#[derive(Debug, Error)]
423pub enum UiAccountConversionError {
424    /// The JSON is not a `UiAccount`.
425    #[error("payload is not a UiAccount: {0}")]
426    NotAUiAccount(#[from] serde_json::Error),
427
428    /// The account data is not base64-encoded; only base64 is supported.
429    #[error("unsupported ui-account data encoding, expected base64")]
430    UnsupportedEncoding,
431
432    /// The account data is not valid base64.
433    #[error("decoding base64 account data: {0}")]
434    Data(#[from] base64::DecodeError),
435
436    /// The `owner` is not a valid address.
437    #[error("parsing owner address: {0}")]
438    Owner(#[from] solana_address::error::ParseAddressError),
439}
440
441/// Decode a serde-serialized [`UiAccount`] (the `pre`/`post` payload shape) into
442/// the wire [`AccountData`] shape. Only base64 data is supported; `space` falls
443/// back to the decoded data length when absent.
444///
445/// # Errors
446///
447/// [`UiAccountConversionError`] if `value` is not a base64 `UiAccount`.
448pub fn account_data_from_ui(
449    value: &serde_json::Value,
450) -> Result<AccountData, UiAccountConversionError> {
451    let ui = UiAccount::deserialize(value)?;
452    let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
453        return Err(UiAccountConversionError::UnsupportedEncoding);
454    };
455    let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
456    let space = match ui.space {
457        Some(space) => space,
458        None => encoded.decode()?.len() as u64,
459    };
460    Ok(AccountData {
461        data: encoded,
462        executable: ui.executable,
463        lamports: ui.lamports,
464        owner: ui.owner.parse()?,
465        space,
466    })
467}
468
469/// Slot context included in every action result.
470#[derive(Debug, Clone, Deserialize)]
471pub struct ActionResultContext {
472    /// Same as the notification's `slot`.
473    pub slot: u64,
474}
475
476/// One scheduled-action result delivered by `actionSubscribe`.
477#[derive(Debug, Clone, Deserialize)]
478#[serde(rename_all = "camelCase")]
479pub struct ActionResultNotification {
480    #[allow(missing_docs)]
481    pub context: ActionResultContext,
482    /// The slot the action fired in.
483    pub slot: u64,
484    /// Batch the action fired at; `None` for slot-boundary actions.
485    #[serde(default)]
486    pub batch_index: Option<u32>,
487    /// The matched transaction's index in its slot's block, the index Solana reports for it;
488    /// `None` for slot-boundary actions and from a session that predates it.
489    #[serde(default)]
490    pub tx_index: Option<u32>,
491    /// Block index of the batch's last transaction; `None` for slot-boundary actions.
492    #[serde(default)]
493    pub batch_last_tx_index: Option<u32>,
494    /// Block time in Unix seconds; `None` for slot-boundary actions.
495    #[serde(default)]
496    pub block_time: Option<i64>,
497    /// Index of the action in the session's `actions` list.
498    pub action_index: u32,
499    /// The action's `label`, if it set one.
500    #[serde(default)]
501    pub label: Option<String>,
502    /// `true` when the action's writes were committed to the session (`kind: send`); `false`
503    /// for a simulation, which leaves the replay unchanged.
504    pub committed: bool,
505    /// One per transaction in the action's sequence, in order. A failing
506    /// transaction is the last entry; later transactions don't run.
507    #[serde(default)]
508    pub transaction_outcomes: Vec<ActionTransactionOutcome>,
509    /// Post-execution `UiAccount` JSON per `return_accounts` address, positional;
510    /// cumulative state after the final transaction.
511    #[serde(default)]
512    pub accounts: Vec<Option<serde_json::Value>>,
513    /// Encoded transaction whose discovery-filter match triggered this action;
514    /// absent for slot-boundary actions. Decode with [`decode_transaction`] or
515    /// [`Self::matched_transaction`].
516    #[serde(default)]
517    pub matched: Option<EncodedBinary>,
518}
519
520impl ActionResultNotification {
521    /// The failing transaction's outcome, or `None` when every transaction succeeded.
522    pub fn failure(&self) -> Option<&ActionTransactionOutcome> {
523        // A failure ends the sequence, so it can only be the last entry.
524        self.transaction_outcomes.last().filter(|o| o.err.is_some())
525    }
526
527    /// Decode the `index`th `return_accounts` entry; `None` when the account does not exist or
528    /// `index` is past the action's `return_accounts`.
529    pub fn returned_account(
530        &self,
531        index: usize,
532    ) -> Option<Result<AccountData, UiAccountConversionError>> {
533        self.accounts.get(index)?.as_ref().map(account_data_from_ui)
534    }
535
536    /// Decode [`Self::matched`]; `None` for slot-boundary actions.
537    pub fn matched_transaction(&self) -> Option<Result<VersionedTransaction, TxDecodeError>> {
538        self.matched.as_ref().map(decode_transaction)
539    }
540}
541
542/// One transaction's result within a scheduled action's sequence.
543#[derive(Debug, Clone, Deserialize)]
544#[serde(rename_all = "camelCase")]
545pub struct ActionTransactionOutcome {
546    /// Transaction failure message; `None` on success.
547    #[serde(default)]
548    pub err: Option<String>,
549    #[serde(default)]
550    #[allow(missing_docs)]
551    pub logs: Vec<String>,
552    #[allow(missing_docs)]
553    pub units_consumed: u64,
554    /// Fee in lamports, if known.
555    #[serde(default)]
556    pub fee: Option<u64>,
557    /// Program return data (`{programId, data}`), if any.
558    #[serde(default)]
559    pub return_data: Option<serde_json::Value>,
560    /// The action's resolver failed, so nothing was simulated and `err` says why: what the action
561    /// measures is unknown rather than reverted.
562    #[serde(default)]
563    pub unresolved: bool,
564}
565
566/// An account diff from [`subscribe_account_diffs_many`], tagged with the subscribed account
567/// that produced it.
568#[derive(Debug, Clone)]
569pub struct RoutedAccountDiffNotification {
570    /// The subscribed account address, as you passed it.
571    pub account: String,
572    #[allow(missing_docs)]
573    pub notification: AccountDiffNotification,
574}
575
576/// Handle for a running account diff or program diff subscription.
577///
578/// Finish with [`Self::shutdown`]; see [`SubscriptionHandle`] for the fields and what dropping
579/// it does.
580pub struct AccountDiffSubscriptionHandle {
581    /// The background task. Prefer [`Self::shutdown`].
582    pub join_handle: SubscriptionTaskHandle,
583    /// Stop signal. Prefer [`Self::shutdown`].
584    pub stop: watch::Sender<bool>,
585}
586
587fn subscription_runtime_closed(
588    kind: &'static str,
589    target: impl Into<String>,
590) -> SubscriptionRuntimeError {
591    SubscriptionRuntimeError::Closed {
592        kind,
593        target: target.into(),
594    }
595}
596
597fn callback_worker_failed(
598    kind: &'static str,
599    target: impl Into<String>,
600    source: tokio::task::JoinError,
601) -> SubscriptionRuntimeError {
602    SubscriptionRuntimeError::CallbackWorker {
603        kind,
604        target: target.into(),
605        source,
606    }
607}
608
609/// Subscribe to the changes of one account.
610///
611/// `rpc_endpoint` is the session's RPC endpoint. Callbacks run one at a time, in the order the
612/// server sent the diffs. Returns once the server confirms the subscription. Never reconnects;
613/// see the [module docs](crate::subscriptions). For every account a program owns, use
614/// [`subscribe_program_diffs`].
615///
616/// # Errors
617///
618/// [`SubscriptionError`] if the subscription cannot be started.
619///
620/// ## Example
621///
622/// ```no_run
623/// use simulator_client::{ManagedBacktestSession, subscribe_account_diffs};
624///
625/// # async fn example(session: &ManagedBacktestSession) -> Result<(), Box<dyn std::error::Error>> {
626/// let handle = subscribe_account_diffs(
627///     &session.session_info().rpc_endpoint,
628///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
629///     |notification| async move {
630///         println!("slot={} sig={:?}", notification.context.slot, notification.signature);
631///     },
632/// )
633/// .await?;
634///
635/// handle.shutdown().await?;
636/// # Ok(())
637/// # }
638/// ```
639pub async fn subscribe_account_diffs<F, Fut>(
640    rpc_endpoint: &str,
641    account: &str,
642    on_notification: F,
643) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
644where
645    F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
646    Fut: Future<Output = ()> + Send + 'static,
647{
648    subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
649        on_notification(notification.notification)
650    })
651    .await
652}
653
654/// Subscribe to the changes of many accounts over one WebSocket.
655///
656/// Duplicate accounts are subscribed once; each diff is tagged with the account it belongs to.
657/// Callbacks run one at a time, in the order the server sent the diffs. Returns once the server
658/// confirms every subscription; with no accounts, returns a handle that delivers nothing. Never
659/// reconnects: a dropped WebSocket ends the stream with [`SubscriptionRuntimeError::Closed`].
660///
661/// # Errors
662///
663/// [`SubscriptionError`] if any subscription cannot be started.
664pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
665    rpc_endpoint: &str,
666    accounts: I,
667    on_notification: F,
668) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
669where
670    F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
671    Fut: Future<Output = ()> + Send + 'static,
672    I: IntoIterator<Item = S>,
673    S: Into<String>,
674{
675    let ws_url = http_to_ws_url(rpc_endpoint)?;
676    let accounts = dedup_accounts(accounts);
677    if accounts.is_empty() {
678        let (stop_tx, stop_rx) = watch::channel(false);
679        return Ok(AccountDiffSubscriptionHandle {
680            join_handle: tokio::spawn(async move {
681                let _ = stop_rx;
682                Ok(())
683            }),
684            stop: stop_tx,
685        });
686    }
687
688    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
689    let (stop_tx, mut stop_rx) = watch::channel(false);
690    let target = format!("{} accounts", accounts.len());
691
692    let join_handle = tokio::spawn(async move {
693        let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
694        let callback_handle = tokio::spawn(async move {
695            while let Some(notification) = notification_rx.recv().await {
696                on_notification(notification).await;
697            }
698        });
699
700        let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
701            Ok(connection) => connection,
702            Err(e) => {
703                let _ = ready_tx.send(Err(SubscriptionError::Connect {
704                    url: ws_url,
705                    source: Box::new(e),
706                }));
707                return Ok(());
708            }
709        };
710
711        let subscriptions =
712            match send_account_diff_subscribe_many(&mut ws, &accounts, &notification_tx).await {
713                Ok(subscriptions) => subscriptions,
714                Err(error) => {
715                    let _ = ready_tx.send(Err(error));
716                    return Ok(());
717                }
718            };
719
720        let _ = ready_tx.send(Ok(()));
721
722        if let Err(error) =
723            drive_account_diff_stream_many(&mut ws, &subscriptions, &notification_tx, &mut stop_rx)
724                .await
725        {
726            drop(notification_tx);
727            if let Err(source) = callback_handle.await {
728                return Err(callback_worker_failed("account diff", target, source));
729            }
730            return Err(error);
731        }
732
733        drop(notification_tx);
734        if let Err(source) = callback_handle.await {
735            return Err(callback_worker_failed("account diff", target, source));
736        }
737
738        Ok(())
739    });
740
741    match ready_rx.await {
742        Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
743            join_handle,
744            stop: stop_tx,
745        }),
746        Ok(Err(e)) => {
747            join_handle.abort();
748            Err(e)
749        }
750        Err(_) => {
751            join_handle.abort();
752            Err(SubscriptionError::TaskDropped)
753        }
754    }
755}
756
757#[derive(Deserialize)]
758struct AccountDiffMessage {
759    method: String,
760    params: AccountDiffParams,
761}
762
763#[derive(Deserialize)]
764struct AccountDiffParams {
765    subscription: u64,
766    result: AccountDiffNotification,
767}
768
769async fn send_account_diff_subscribe_many(
770    ws: &mut AccountDiffWs,
771    accounts: &[String],
772    notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
773) -> Result<std::collections::HashMap<u64, String>, SubscriptionError> {
774    #[derive(Deserialize)]
775    struct SubscriptionConfirmation {
776        id: u64,
777        result: Option<u64>,
778    }
779
780    let mut pending: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
781    let mut subscriptions = std::collections::HashMap::with_capacity(accounts.len());
782
783    for (index, account) in accounts.iter().enumerate() {
784        let request_id = (index + 1) as u64;
785        let req = serde_json::json!({
786            "jsonrpc": "2.0",
787            "id": request_id,
788            "method": "accountDiffSubscribe",
789            "params": [account]
790        });
791        ws.send(Message::Text(req.to_string()))
792            .await
793            .map_err(|source| SubscriptionError::Subscribe {
794                source: Box::new(source),
795            })?;
796        pending.insert(request_id, account.clone());
797    }
798
799    while !pending.is_empty() {
800        match ws.next().await {
801            Some(Ok(Message::Text(text))) => {
802                if let Ok(confirmation) = serde_json::from_str::<SubscriptionConfirmation>(&text) {
803                    let Some(account) = pending.remove(&confirmation.id) else {
804                        continue;
805                    };
806                    let Some(subscription_id) = confirmation.result else {
807                        return Err(SubscriptionError::TaskDropped);
808                    };
809                    subscriptions.insert(subscription_id, account);
810                    continue;
811                }
812
813                if let Some(notification) =
814                    parse_routed_account_diff_notification(&text, &subscriptions)
815                {
816                    let _ = notification_tx.send(notification);
817                }
818            }
819            Some(Ok(_)) => {}
820            _ => return Err(SubscriptionError::TaskDropped),
821        }
822    }
823
824    Ok(subscriptions)
825}
826
827async fn drive_account_diff_stream_many(
828    ws: &mut AccountDiffWs,
829    subscriptions: &std::collections::HashMap<u64, String>,
830    notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
831    stop_rx: &mut watch::Receiver<bool>,
832) -> Result<(), SubscriptionRuntimeError> {
833    loop {
834        if *stop_rx.borrow() {
835            let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
836            loop {
837                match tokio::time::timeout_at(
838                    drain_deadline,
839                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
840                )
841                .await
842                {
843                    Ok(Ok(Some(Ok(Message::Text(text))))) => {
844                        if let Some(notification) =
845                            parse_routed_account_diff_notification(&text, subscriptions)
846                        {
847                            let _ = notification_tx.send(notification);
848                        }
849                    }
850                    _ => return Ok(()),
851                }
852            }
853        }
854
855        let msg = tokio::select! {
856            m = ws.next() => m,
857            _ = stop_rx.changed() => continue,
858        };
859
860        match msg {
861            Some(Ok(Message::Text(text))) => {
862                if let Some(notification) =
863                    parse_routed_account_diff_notification(&text, subscriptions)
864                {
865                    let _ = notification_tx.send(notification);
866                }
867            }
868            Some(Ok(_)) => {}
869            _ => {
870                return Err(subscription_runtime_closed(
871                    "account diff",
872                    format!("{} accounts", subscriptions.len()),
873                ));
874            }
875        }
876    }
877}
878
879fn parse_account_diff_message(text: &str) -> Option<AccountDiffMessage> {
880    let msg: AccountDiffMessage = serde_json::from_str(text).ok()?;
881    (msg.method == "accountDiffNotification").then_some(msg)
882}
883
884fn parse_routed_account_diff_notification(
885    text: &str,
886    subscriptions: &std::collections::HashMap<u64, String>,
887) -> Option<RoutedAccountDiffNotification> {
888    let msg = parse_account_diff_message(text)?;
889    let account = subscriptions.get(&msg.params.subscription)?.clone();
890    Some(RoutedAccountDiffNotification {
891        account,
892        notification: msg.params.result,
893    })
894}
895
896fn dedup_accounts<I, S>(accounts: I) -> Vec<String>
897where
898    I: IntoIterator<Item = S>,
899    S: Into<String>,
900{
901    let mut unique = std::collections::BTreeSet::new();
902    accounts
903        .into_iter()
904        .map(Into::into)
905        .filter(|account| unique.insert(account.clone()))
906        .collect()
907}
908
909// ── Program account diff subscription ────────────────────────────────────────
910
911/// Subscribe to the changes of every account a program owns.
912///
913/// `rpc_endpoint` is the session's RPC endpoint. The callback receives one
914/// [`AccountDiffNotification`] per changed account, with `account` set; callbacks run one at a
915/// time, in order. Never reconnects: a dropped WebSocket ends the stream with
916/// [`SubscriptionRuntimeError::Closed`].
917///
918/// # Errors
919///
920/// [`SubscriptionError`] if the subscription cannot be started.
921///
922/// ## Example
923///
924/// ```no_run
925/// use simulator_client::{ManagedBacktestSession, subscribe_program_diffs};
926///
927/// # async fn example(session: &ManagedBacktestSession) -> Result<(), Box<dyn std::error::Error>> {
928/// let handle = subscribe_program_diffs(
929///     &session.session_info().rpc_endpoint,
930///     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
931///     |notification| async move {
932///         let account = notification.account.unwrap_or_default();
933///         println!("account={account} slot={}", notification.context.slot);
934///     },
935/// )
936/// .await?;
937///
938/// handle.shutdown().await?;
939/// # Ok(())
940/// # }
941/// ```
942pub async fn subscribe_program_diffs<F, Fut>(
943    rpc_endpoint: &str,
944    program_id: &str,
945    on_notification: F,
946) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
947where
948    F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
949    Fut: Future<Output = ()> + Send + 'static,
950{
951    let ws_url = http_to_ws_url(rpc_endpoint)?;
952    let program_id = program_id.to_string();
953
954    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
955    let (stop_tx, mut stop_rx) = watch::channel(false);
956
957    let join_handle = tokio::spawn(async move {
958        let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
959        let callback_handle = tokio::spawn(async move {
960            while let Some(notification) = notification_rx.recv().await {
961                on_notification(notification).await;
962            }
963        });
964
965        let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
966            Ok(connection) => connection,
967            Err(e) => {
968                let _ = ready_tx.send(Err(SubscriptionError::Connect {
969                    url: ws_url,
970                    source: Box::new(e),
971                }));
972                return Ok(());
973            }
974        };
975
976        if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
977            let _ = ready_tx.send(Err(error));
978            return Ok(());
979        }
980
981        let _ = ready_tx.send(Ok(()));
982
983        if let Err(error) =
984            drive_program_diff_stream(&mut ws, &notification_tx, &mut stop_rx, &program_id).await
985        {
986            drop(notification_tx);
987            if let Err(source) = callback_handle.await {
988                return Err(callback_worker_failed(
989                    "program account diff",
990                    &program_id,
991                    source,
992                ));
993            }
994            return Err(error);
995        }
996
997        drop(notification_tx);
998        if let Err(source) = callback_handle.await {
999            return Err(callback_worker_failed(
1000                "program account diff",
1001                &program_id,
1002                source,
1003            ));
1004        }
1005
1006        Ok(())
1007    });
1008
1009    match ready_rx.await {
1010        Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
1011            join_handle,
1012            stop: stop_tx,
1013        }),
1014        Ok(Err(e)) => {
1015            join_handle.abort();
1016            Err(e)
1017        }
1018        Err(_) => {
1019            join_handle.abort();
1020            Err(SubscriptionError::TaskDropped)
1021        }
1022    }
1023}
1024
1025async fn send_program_diff_subscribe(
1026    ws: &mut AccountDiffWs,
1027    program_id: &str,
1028) -> Result<(), SubscriptionError> {
1029    #[derive(Deserialize)]
1030    struct SubscriptionConfirmation {
1031        result: Option<u64>,
1032    }
1033
1034    let req = serde_json::json!({
1035        "jsonrpc": "2.0",
1036        "id": 1,
1037        "method": "accountDiffSubscribe",
1038        "params": [program_id, {"address_type": "program"}]
1039    });
1040    ws.send(Message::Text(req.to_string()))
1041        .await
1042        .map_err(|source| SubscriptionError::Subscribe {
1043            source: Box::new(source),
1044        })?;
1045
1046    loop {
1047        match ws.next().await {
1048            Some(Ok(Message::Text(text))) => {
1049                match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1050                    Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1051                    Ok(_) => continue,
1052                    Err(source) => {
1053                        return Err(SubscriptionError::Subscribe {
1054                            source: Box::new(source),
1055                        });
1056                    }
1057                }
1058            }
1059            Some(Ok(_)) => continue,
1060            _ => return Err(SubscriptionError::TaskDropped),
1061        }
1062    }
1063}
1064
1065async fn drive_program_diff_stream(
1066    ws: &mut AccountDiffWs,
1067    notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
1068    stop_rx: &mut watch::Receiver<bool>,
1069    program_id: &str,
1070) -> Result<(), SubscriptionRuntimeError> {
1071    loop {
1072        if *stop_rx.borrow() {
1073            let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1074            loop {
1075                match tokio::time::timeout_at(
1076                    drain_deadline,
1077                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1078                )
1079                .await
1080                {
1081                    Ok(Ok(Some(Ok(Message::Text(text))))) => {
1082                        if let Some(msg) = parse_account_diff_message(&text) {
1083                            let _ = notification_tx.send(msg.params.result);
1084                        }
1085                    }
1086                    _ => return Ok(()),
1087                }
1088            }
1089        }
1090
1091        let msg = tokio::select! {
1092            m = ws.next() => m,
1093            _ = stop_rx.changed() => continue,
1094        };
1095
1096        match msg {
1097            Some(Ok(Message::Text(text))) => {
1098                if let Some(msg) = parse_account_diff_message(&text) {
1099                    let _ = notification_tx.send(msg.params.result);
1100                }
1101            }
1102            Some(Ok(_)) => {}
1103            _ => {
1104                return Err(subscription_runtime_closed(
1105                    "program account diff",
1106                    program_id,
1107                ));
1108            }
1109        }
1110    }
1111}
1112
1113// ── Keyless notification streams ─────────────────────────────────────────────
1114
1115/// The strings that distinguish one keyless notification stream from another.
1116#[derive(Clone, Copy)]
1117struct NotificationStream {
1118    subscribe_method: &'static str,
1119    notification_method: &'static str,
1120    /// Singular label used in runtime errors.
1121    kind: &'static str,
1122    /// Plural label used in runtime errors.
1123    target: &'static str,
1124}
1125
1126const ACTION_STREAM: NotificationStream = NotificationStream {
1127    subscribe_method: "actionSubscribe",
1128    notification_method: "actionNotification",
1129    kind: "action",
1130    target: "actions",
1131};
1132
1133const REPLACEMENT_STREAM: NotificationStream = NotificationStream {
1134    subscribe_method: "replacementSubscribe",
1135    notification_method: "replacementNotification",
1136    kind: "replacement",
1137    target: "replacements",
1138};
1139
1140const DIAGNOSTIC_STREAM: NotificationStream = NotificationStream {
1141    subscribe_method: "diagnosticSubscribe",
1142    notification_method: "diagnosticNotification",
1143    kind: "diagnostic",
1144    target: "diagnostics",
1145};
1146
1147#[derive(Deserialize)]
1148struct NotificationMessage<N> {
1149    method: String,
1150    params: NotificationParams<N>,
1151}
1152
1153#[derive(Deserialize)]
1154struct NotificationParams<N> {
1155    #[allow(dead_code)]
1156    subscription: u64,
1157    result: N,
1158}
1159
1160fn parse_notification_message<N: DeserializeOwned>(
1161    text: &str,
1162    notification_method: &str,
1163) -> Option<N> {
1164    let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
1165    (msg.method == notification_method).then_some(msg.params.result)
1166}
1167
1168fn is_subscription_complete_message(text: &str) -> bool {
1169    #[derive(Deserialize)]
1170    struct SubscriptionCompleteMessage {
1171        method: String,
1172    }
1173
1174    serde_json::from_str::<SubscriptionCompleteMessage>(text)
1175        .is_ok_and(|msg| msg.method == "subscriptionComplete")
1176}
1177
1178/// Drive a keyless notification stream, invoking `on_notification` for each payload.
1179///
1180/// Implements the protocol every single-stream subscription shares; once `stop` is set, drains
1181/// whatever the server has already queued before resolving.
1182async fn subscribe_notifications<N, F, Fut>(
1183    rpc_endpoint: &str,
1184    stream: NotificationStream,
1185    on_notification: F,
1186) -> Result<SubscriptionHandle, SubscriptionError>
1187where
1188    N: DeserializeOwned + Send + 'static,
1189    F: Fn(N) -> Fut + Send + Sync + 'static,
1190    Fut: Future<Output = ()> + Send + 'static,
1191{
1192    let ws_url = http_to_ws_url(rpc_endpoint)?;
1193
1194    let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
1195    let (stop_tx, mut stop_rx) = watch::channel(false);
1196
1197    let join_handle = tokio::spawn(async move {
1198        let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
1199        let callback_handle = tokio::spawn(async move {
1200            while let Some(notification) = notification_rx.recv().await {
1201                on_notification(notification).await;
1202            }
1203        });
1204
1205        let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
1206            Ok(connection) => connection,
1207            Err(e) => {
1208                let _ = ready_tx.send(Err(SubscriptionError::Connect {
1209                    url: ws_url,
1210                    source: Box::new(e),
1211                }));
1212                return Ok(());
1213            }
1214        };
1215
1216        if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
1217            let _ = ready_tx.send(Err(error));
1218            return Ok(());
1219        }
1220
1221        let _ = ready_tx.send(Ok(()));
1222
1223        if let Err(error) =
1224            drive_notification_stream::<N>(&mut ws, stream, &notification_tx, &mut stop_rx).await
1225        {
1226            drop(notification_tx);
1227            if let Err(source) = callback_handle.await {
1228                return Err(callback_worker_failed(stream.kind, stream.target, source));
1229            }
1230            return Err(error);
1231        }
1232
1233        drop(notification_tx);
1234        if let Err(source) = callback_handle.await {
1235            return Err(callback_worker_failed(stream.kind, stream.target, source));
1236        }
1237
1238        Ok(())
1239    });
1240
1241    match ready_rx.await {
1242        Ok(Ok(())) => Ok(SubscriptionHandle {
1243            join_handle,
1244            stop: stop_tx,
1245        }),
1246        Ok(Err(e)) => {
1247            join_handle.abort();
1248            Err(e)
1249        }
1250        Err(_) => {
1251            join_handle.abort();
1252            Err(SubscriptionError::TaskDropped)
1253        }
1254    }
1255}
1256
1257async fn send_stream_subscribe(
1258    ws: &mut AccountDiffWs,
1259    subscribe_method: &str,
1260) -> Result<(), SubscriptionError> {
1261    #[derive(Deserialize)]
1262    struct SubscriptionConfirmation {
1263        result: Option<u64>,
1264    }
1265
1266    // Keyless: index 0 is an unused placeholder, index 1 the (empty) config object.
1267    let req = serde_json::json!({
1268        "jsonrpc": "2.0",
1269        "id": 1,
1270        "method": subscribe_method,
1271        "params": [serde_json::Value::Null, {}]
1272    });
1273
1274    ws.send(Message::Text(req.to_string()))
1275        .await
1276        .map_err(|source| SubscriptionError::Subscribe {
1277            source: Box::new(source),
1278        })?;
1279
1280    loop {
1281        match ws.next().await {
1282            Some(Ok(Message::Text(text))) => {
1283                match serde_json::from_str::<SubscriptionConfirmation>(&text) {
1284                    Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
1285                    Ok(_) => continue,
1286                    Err(source) => {
1287                        return Err(SubscriptionError::Subscribe {
1288                            source: Box::new(source),
1289                        });
1290                    }
1291                }
1292            }
1293            Some(Ok(_)) => continue,
1294            _ => return Err(SubscriptionError::TaskDropped),
1295        }
1296    }
1297}
1298
1299async fn drive_notification_stream<N: DeserializeOwned>(
1300    ws: &mut AccountDiffWs,
1301    stream: NotificationStream,
1302    notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
1303    stop_rx: &mut watch::Receiver<bool>,
1304) -> Result<(), SubscriptionRuntimeError> {
1305    loop {
1306        if *stop_rx.borrow() {
1307            let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
1308            loop {
1309                match tokio::time::timeout_at(
1310                    drain_deadline,
1311                    tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
1312                )
1313                .await
1314                {
1315                    Ok(Ok(Some(Ok(Message::Text(text))))) => {
1316                        if is_subscription_complete_message(&text) {
1317                            return Ok(());
1318                        }
1319                        if let Some(result) =
1320                            parse_notification_message::<N>(&text, stream.notification_method)
1321                        {
1322                            let _ = notification_tx.send(result);
1323                        }
1324                    }
1325                    _ => return Ok(()),
1326                }
1327            }
1328        }
1329
1330        let msg = tokio::select! {
1331            m = ws.next() => m,
1332            _ = stop_rx.changed() => continue,
1333        };
1334
1335        match msg {
1336            Some(Ok(Message::Text(text))) => {
1337                if is_subscription_complete_message(&text) {
1338                    return Ok(());
1339                }
1340                if let Some(result) =
1341                    parse_notification_message::<N>(&text, stream.notification_method)
1342                {
1343                    let _ = notification_tx.send(result);
1344                }
1345            }
1346            Some(Ok(_)) => {}
1347            _ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
1348        }
1349    }
1350}
1351
1352// ── Action subscription ──────────────────────────────────────────────────────
1353
1354/// Handle for a running [`subscribe_actions`] subscription.
1355///
1356/// Finish with [`Self::shutdown`]; see [`SubscriptionHandle`] for the fields and what dropping
1357/// it does.
1358pub struct ActionSubscriptionHandle {
1359    /// The background task. Prefer [`Self::shutdown`].
1360    pub join_handle: SubscriptionTaskHandle,
1361    /// Stop signal. Prefer [`Self::shutdown`].
1362    pub stop: watch::Sender<bool>,
1363}
1364
1365/// Subscribe to the results of the session's scheduled actions.
1366///
1367/// The session runs the `actions` registered at creation; each result arrives as an
1368/// [`ActionResultNotification`]. Every action shares this one stream: tell them apart by
1369/// `action_index` or `label`. Callbacks run one at a time, in order. The stream ends cleanly
1370/// when the server finishes it. Never reconnects: a dropped WebSocket ends the stream with
1371/// [`SubscriptionRuntimeError::Closed`].
1372///
1373/// # Errors
1374///
1375/// [`SubscriptionError`] if the subscription cannot be started.
1376///
1377/// ## Example
1378///
1379/// ```no_run
1380/// use simulator_client::{ManagedBacktestSession, subscribe_actions};
1381///
1382/// # async fn example(session: &ManagedBacktestSession) -> Result<(), Box<dyn std::error::Error>> {
1383/// let handle = subscribe_actions(
1384///     &session.session_info().rpc_endpoint,
1385///     |result| async move {
1386///         println!("slot={} label={:?}", result.slot, result.label);
1387///     },
1388/// )
1389/// .await?;
1390///
1391/// handle.shutdown().await?;
1392/// # Ok(())
1393/// # }
1394/// ```
1395pub async fn subscribe_actions<F, Fut>(
1396    rpc_endpoint: &str,
1397    on_notification: F,
1398) -> Result<ActionSubscriptionHandle, SubscriptionError>
1399where
1400    F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
1401    Fut: Future<Output = ()> + Send + 'static,
1402{
1403    let SubscriptionHandle { join_handle, stop } =
1404        subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
1405    Ok(ActionSubscriptionHandle { join_handle, stop })
1406}
1407
1408// ── Diagnostic subscription ──────────────────────────────────────────────────
1409
1410/// Slot context included in every diagnostic sample.
1411#[derive(Debug, Clone, Serialize, Deserialize)]
1412pub struct DiagnosticContext {
1413    /// Same as the notification's `slot`.
1414    pub slot: u64,
1415}
1416
1417/// One market's `/diagnostic` sample at one size, delivered by `diagnosticSubscribe`: the
1418/// router's own pricing, not a fill the venue produced.
1419///
1420/// [`Serialize`] so a run can be recorded as it streams and read back as this same type.
1421#[derive(Debug, Clone, Serialize, Deserialize)]
1422#[serde(rename_all = "camelCase")]
1423pub struct DiagnosticNotification {
1424    #[allow(missing_docs)]
1425    pub context: DiagnosticContext,
1426    /// The replayed slot the probe fired at the end of.
1427    pub slot: u64,
1428    /// Index of the probe in the session's `diagnosticProbes` list.
1429    pub probe_index: u32,
1430    /// The probe's `label`, if it set one.
1431    #[serde(default)]
1432    pub label: Option<String>,
1433    /// The probed market (pool) address.
1434    pub market: String,
1435    /// The trade size probed, in whole US dollars (one of the probe's `usdValues`).
1436    pub usd_value: u32,
1437    /// Mints of the pairs asked for; empty means every pair the market holds.
1438    #[serde(default)]
1439    pub pairs: Vec<[String; 2]>,
1440    /// The router's ingest slot when it answered. Lags `slot` by whatever the stream has yet to
1441    /// drain, so a consumer needing the two aligned must check rather than assume.
1442    #[serde(default)]
1443    pub router_slot: Option<u64>,
1444    /// `swapInfoResults` verbatim: both directions priced at `usd_value`.
1445    #[serde(default)]
1446    pub results: Option<serde_json::Value>,
1447    /// One per backing account the router priced from, in the order it sent them.
1448    #[serde(default)]
1449    pub account_hashes: Vec<String>,
1450    /// Why this probe produced no sample; `None` on success.
1451    #[serde(default)]
1452    pub err: Option<String>,
1453}
1454
1455/// Handle for a running [`subscribe_diagnostics`] subscription.
1456///
1457/// Finish with [`Self::shutdown`]; see [`SubscriptionHandle`] for the fields and what dropping
1458/// it does.
1459pub struct DiagnosticSubscriptionHandle {
1460    /// The background task. Prefer [`Self::shutdown`].
1461    pub join_handle: SubscriptionTaskHandle,
1462    /// Stop signal. Prefer [`Self::shutdown`].
1463    pub stop: watch::Sender<bool>,
1464}
1465
1466/// Subscribe to the session's `/diagnostic` samples.
1467///
1468/// Probes are registered at creation (`diagnostic_probes` in `CreateSessionParams`); this only
1469/// attaches the consumer. Callbacks run one at a time, in order. Never reconnects: a dropped
1470/// WebSocket ends the stream with [`SubscriptionRuntimeError::Closed`].
1471///
1472/// # Errors
1473///
1474/// [`SubscriptionError`] if the subscription cannot be started.
1475pub async fn subscribe_diagnostics<F, Fut>(
1476    rpc_endpoint: &str,
1477    on_notification: F,
1478) -> Result<DiagnosticSubscriptionHandle, SubscriptionError>
1479where
1480    F: Fn(DiagnosticNotification) -> Fut + Send + Sync + 'static,
1481    Fut: Future<Output = ()> + Send + 'static,
1482{
1483    let SubscriptionHandle { join_handle, stop } =
1484        subscribe_notifications(rpc_endpoint, DIAGNOSTIC_STREAM, on_notification).await?;
1485    Ok(DiagnosticSubscriptionHandle { join_handle, stop })
1486}
1487
1488// ── Replacement subscription ─────────────────────────────────────────────────
1489
1490// The wire contract itself, not a mirror of it: one declaration both sides build against, so a
1491// field the server adds cannot go missing here. Restating it by hand is how `outcome`,
1492// `category` and `err` came to be dropped.
1493pub use simulator_api::replacement::{
1494    L1Score, OriginalNotification, ProbedHop, ReplacementContext, ReplacementCore,
1495    ReplacementNotification, RequoteNotification, RerouteLegNotification, VenueNotification,
1496};
1497
1498/// Subscribe to the session's reroute results.
1499///
1500/// Each result (a requote simulation, a reroute directly to a venue, or the original swap)
1501/// arrives as a [`ReplacementNotification`]; branch on its variant, or hand the stream to
1502/// [`crate::reroute_report::from_stream`] / [`crate::reroute_report::probes_from_stream`]. Every
1503/// result shares this one stream: tell them apart by `slot`, `batch_index` and
1504/// `original_signature`. Callbacks run one at a time, in order. Never reconnects: a dropped
1505/// WebSocket ends the stream with [`SubscriptionRuntimeError::Closed`].
1506///
1507/// # Errors
1508///
1509/// [`SubscriptionError`] if the subscription cannot be started.
1510///
1511/// ## Example
1512///
1513/// ```no_run
1514/// use simulator_client::{ManagedBacktestSession, ReplacementNotification, subscribe_replacements};
1515///
1516/// # async fn example(session: &ManagedBacktestSession) -> Result<(), Box<dyn std::error::Error>> {
1517/// let handle = subscribe_replacements(
1518///     &session.session_info().rpc_endpoint,
1519///     |result| async move {
1520///         match result {
1521///             ReplacementNotification::Requote(requote) => {
1522///                 println!("slot={} sig={}", requote.core.slot, requote.core.original_signature);
1523///             }
1524///             ReplacementNotification::Venue(probe) => {
1525///                 println!("template={} sig={}", probe.template, probe.core.original_signature);
1526///             }
1527///             ReplacementNotification::Original(original) => {
1528///                 println!("baseline sig={}", original.core.original_signature);
1529///             }
1530///         }
1531///     },
1532/// )
1533/// .await?;
1534///
1535/// handle.shutdown().await?;
1536/// # Ok(())
1537/// # }
1538/// ```
1539pub async fn subscribe_replacements<F, Fut>(
1540    rpc_endpoint: &str,
1541    on_notification: F,
1542) -> Result<SubscriptionHandle, SubscriptionError>
1543where
1544    F: Fn(ReplacementNotification) -> Fut + Send + Sync + 'static,
1545    Fut: Future<Output = ()> + Send + 'static,
1546{
1547    subscribe_notifications(rpc_endpoint, REPLACEMENT_STREAM, on_notification).await
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552    use rstest::rstest;
1553
1554    use super::*;
1555
1556    #[test]
1557    fn parse_account_diff_notification_ignores_other_messages() {
1558        let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
1559        assert!(parse_account_diff_message(confirmation).is_none());
1560    }
1561
1562    #[test]
1563    fn parse_account_diff_notification_extracts_payload() {
1564        let text = r#"{
1565            "jsonrpc":"2.0",
1566            "method":"accountDiffNotification",
1567            "params":{
1568                "subscription":7,
1569                "result":{
1570                    "context":{"slot":123},
1571                    "signature":"sig",
1572                    "pre":{"a":1},
1573                    "post":{"a":2}
1574                }
1575            }
1576        }"#;
1577
1578        let notification = parse_account_diff_message(text)
1579            .expect("notification")
1580            .params
1581            .result;
1582        assert_eq!(notification.context.slot, 123);
1583        assert_eq!(notification.signature.as_deref(), Some("sig"));
1584        assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
1585        assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
1586    }
1587
1588    #[test]
1589    fn parse_routed_account_diff_notification_extracts_subscription_account() {
1590        let text = r#"{
1591            "jsonrpc":"2.0",
1592            "method":"accountDiffNotification",
1593            "params":{
1594                "subscription":42,
1595                "result":{
1596                    "context":{"slot":456},
1597                    "signature":"sig",
1598                    "pre":null,
1599                    "post":{"a":2}
1600                }
1601            }
1602        }"#;
1603        let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
1604
1605        let notification =
1606            parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
1607        assert_eq!(notification.account, "acct");
1608        assert_eq!(notification.notification.context.slot, 456);
1609    }
1610
1611    #[test]
1612    fn converts_ui_account_json() {
1613        let value = serde_json::json!({
1614            "lamports": 5,
1615            "data": ["AQID", "base64"],
1616            "owner": "11111111111111111111111111111111",
1617            "executable": false,
1618            "rentEpoch": 0,
1619        });
1620        let account = account_data_from_ui(&value).unwrap();
1621        assert_eq!(account.lamports, 5);
1622        assert_eq!(account.space, 3);
1623        assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
1624    }
1625
1626    #[test]
1627    fn rejects_non_base64_encodings() {
1628        let value = serde_json::json!({
1629            "lamports": 5,
1630            "data": ["{}", "jsonParsed"],
1631            "owner": "11111111111111111111111111111111",
1632            "executable": false,
1633            "rentEpoch": 0,
1634        });
1635        assert!(matches!(
1636            account_data_from_ui(&value),
1637            Err(UiAccountConversionError::UnsupportedEncoding)
1638        ));
1639    }
1640
1641    fn action_result(
1642        errors: &[Option<&str>],
1643        accounts: Vec<Option<serde_json::Value>>,
1644    ) -> ActionResultNotification {
1645        ActionResultNotification {
1646            context: ActionResultContext { slot: 0 },
1647            slot: 0,
1648            batch_index: None,
1649            tx_index: None,
1650            batch_last_tx_index: None,
1651            block_time: None,
1652            action_index: 0,
1653            label: None,
1654            committed: false,
1655            transaction_outcomes: errors
1656                .iter()
1657                .map(|err| ActionTransactionOutcome {
1658                    err: err.map(str::to_owned),
1659                    logs: Vec::new(),
1660                    units_consumed: 0,
1661                    fee: None,
1662                    return_data: None,
1663                    unresolved: false,
1664                })
1665                .collect(),
1666            accounts,
1667            matched: None,
1668        }
1669    }
1670
1671    #[rstest]
1672    #[case::no_outcomes(&[], None)]
1673    #[case::one_ok(&[None], None)]
1674    #[case::all_ok(&[None, None], None)]
1675    #[case::one_err(&[Some("boom")], Some("boom"))]
1676    #[case::second_hop_err(&[None, Some("hop2")], Some("hop2"))]
1677    fn action_failure_is_the_last_failing_outcome(
1678        #[case] errors: &[Option<&str>],
1679        #[case] expected: Option<&str>,
1680    ) {
1681        let result = action_result(errors, Vec::new());
1682        assert_eq!(result.failure().and_then(|o| o.err.as_deref()), expected);
1683    }
1684
1685    #[rstest]
1686    #[case::base64(0, Some(Ok(5)))]
1687    #[case::missing_account(1, None)]
1688    #[case::json_parsed(2, Some(Err(UiAccountConversionError::UnsupportedEncoding.to_string())))]
1689    #[case::past_return_accounts(3, None)]
1690    fn returned_account_reads_positional_entries(
1691        #[case] index: usize,
1692        #[case] expected: Option<Result<u64, String>>,
1693    ) {
1694        let ui_account = |data| {
1695            serde_json::json!({
1696                "lamports": 5,
1697                "data": data,
1698                "owner": "11111111111111111111111111111111",
1699                "executable": false,
1700                "rentEpoch": 0,
1701            })
1702        };
1703        let result = action_result(
1704            &[],
1705            vec![
1706                Some(ui_account(serde_json::json!(["AQID", "base64"]))),
1707                None,
1708                Some(ui_account(serde_json::json!(["{}", "jsonParsed"]))),
1709            ],
1710        );
1711        let lamports = result
1712            .returned_account(index)
1713            .map(|account| account.map(|a| a.lamports).map_err(|e| e.to_string()));
1714        assert_eq!(lamports, expected);
1715    }
1716
1717    #[test]
1718    fn dedup_accounts_preserves_first_seen_order() {
1719        let accounts = dedup_accounts([
1720            "b".to_string(),
1721            "a".to_string(),
1722            "b".to_string(),
1723            "c".to_string(),
1724        ]);
1725        assert_eq!(accounts, vec!["b", "a", "c"]);
1726    }
1727
1728    /// The signature every fixture names. Typed on the core, so it has to be real base58.
1729    fn fixture_signature() -> String {
1730        simulator_api::replacement::Signature::default().to_string()
1731    }
1732
1733    /// `set` overrides its `swapInfo`; every other field is explicitly null.
1734    fn route_hop(set: serde_json::Value, program: serde_json::Value) -> serde_json::Value {
1735        use serde_json::json;
1736
1737        let mut swap_info = json!({
1738            "label": null, "ammKey": null, "inputMint": null,
1739            "inAmount": null, "outputMint": null, "outAmount": null,
1740        });
1741        for (key, value) in set.as_object().expect("an object") {
1742            swap_info[key] = value.clone();
1743        }
1744        json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
1745    }
1746
1747    /// A wire-shaped fixture rather than a constructed value: a field serializing under a
1748    /// different name than it deserializes would still round-trip through a struct.
1749    #[test]
1750    fn a_requote_notification_round_trips_through_its_own_encoding() {
1751        use serde_json::{Value, json};
1752
1753        let wire = serde_json::json!({
1754            "kind": "requote",
1755            "context": {"slot": 42},
1756            "slot": 42,
1757            "batchIndex": 3,
1758            "originalSignature": fixture_signature(),
1759            "originalFailed": false,
1760            "outcome": "filled",
1761            "legs": [{
1762                "inputMint": simulator_api::mints::SOL.to_string(),
1763                "outputMint": simulator_api::mints::USDC.to_string(),
1764                "amount": 1_000,
1765                "swapMode": "ExactIn",
1766                "originalQuotedOut": 990,
1767                "metisQuotedOut": 1_010,
1768                "routeSummary": "SolFi",
1769                // Unset fields are written as null: the recording path decodes positionally.
1770                "routePlan": [route_hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
1771                "originalRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
1772                "realizedRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
1773            }],
1774            "routedTransaction": {"data": "AA==", "encoding": "base64"},
1775            "logs": ["Program log: swap"],
1776            "computeUnitsConsumed": 123_456,
1777            "fee": 5_000,
1778            "realizedOutputAmount": 1_009,
1779            "originalRealizedOutputAmount": 991,
1780        });
1781
1782        let notification: ReplacementNotification =
1783            serde_json::from_value(wire.clone()).expect("wire decodes");
1784        let recorded = serde_json::to_value(&notification).expect("notification encodes");
1785        assert_eq!(recorded, wire);
1786
1787        let ReplacementNotification::Requote(read_back) =
1788            serde_json::from_value::<ReplacementNotification>(recorded).expect("recording decodes")
1789        else {
1790            panic!("kind=requote must decode to the Requote variant");
1791        };
1792        assert_eq!(read_back.core.batch_index, 3);
1793        assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
1794        assert_eq!(read_back.original_realized_output_amount, Some(991));
1795        // The routed plan is the fill and `route_plan` is the quote; a reader that conflated them
1796        // would compare a projection against an outcome.
1797        assert!(
1798            read_back
1799                .legs
1800                .iter()
1801                .all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
1802        );
1803    }
1804
1805    /// The adapter keys filled-ness on `outcome`; `category` carries only the revert reason.
1806    #[test]
1807    fn a_venue_notification_round_trips_through_its_own_encoding() {
1808        let wire = serde_json::json!({
1809            "kind": "directFill",
1810            "context": {"slot": 7},
1811            "slot": 7,
1812            "batchIndex": 1,
1813            "originalSignature": fixture_signature(),
1814            "originalFailed": false,
1815            "template": "venue-a",
1816            "program": simulator_api::mints::USDC.to_string(),
1817            "hop": {
1818                "slot": 9,
1819                "blockTime": 1_767_225_600i64,
1820                "txIndex": 4,
1821                "ixIndex": 0,
1822                "legIndex": 0,
1823                "program": simulator_api::mints::SOL.to_string(),
1824                "inputAmount": 1_000,
1825                "outputAmount": 1_000,
1826                "replayInputAmount": 1_000,
1827                "replayOutputAmount": 1_005,
1828            },
1829            "quoteTxIndex": 1,
1830            "quoteLagBlocks": 2,
1831            "inputMint": simulator_api::mints::SOL.to_string(),
1832            "outputMint": simulator_api::mints::USDC.to_string(),
1833            "amount": 1_000,
1834            "swapMode": "ExactIn",
1835            "templateFill": 1_010,
1836            "l1Fill": 1_000,
1837            "changeVsL1Bps": 100,
1838            "outcome": "filled",
1839        });
1840
1841        let notification: ReplacementNotification =
1842            serde_json::from_value(wire.clone()).expect("wire decodes");
1843        let recorded = serde_json::to_value(&notification).expect("notification encodes");
1844        assert_eq!(recorded, wire);
1845
1846        let ReplacementNotification::Venue(read_back) = notification else {
1847            panic!("kind=directFill must decode to the Venue variant");
1848        };
1849        assert_eq!(read_back.template, "venue-a");
1850        assert_eq!(read_back.template_fill, Some(1_010));
1851        assert_eq!(read_back.comparison.l1_fill, Some(1_000));
1852        assert_eq!(read_back.comparison.change_vs_l1_bps, Some(100));
1853        assert!(
1854            read_back.core.category.is_none(),
1855            "a filled probe carries no category"
1856        );
1857    }
1858
1859    /// The server emits one of these for every admitted transaction. Until this variant existed
1860    /// client-side, `parse_notification_message` turned the unknown tag into `Ok(None)` and the
1861    /// caller dropped it with no `else` — a silent discard, once per original, in every reroute
1862    /// session. Nothing logged it and nothing counted it, so only a decode test catches the next
1863    /// time the hand-written mirror drifts from the server's shape.
1864    #[test]
1865    fn an_original_notification_round_trips_through_its_own_encoding() {
1866        let wire = serde_json::json!({
1867            "kind": "original",
1868            "context": {"slot": 9},
1869            "slot": 9,
1870            "batchIndex": 2,
1871            "originalSignature": fixture_signature(),
1872            "originalFailed": false,
1873            "l1Fill": 2_000,
1874            "changeVsL1Bps": -25,
1875            "computeUnitsConsumed": 31_400,
1876            "fee": 5_000,
1877            "simulatedOutputAmount": 1_995,
1878            "outcome": "filled",
1879        });
1880
1881        let notification: ReplacementNotification =
1882            serde_json::from_value(wire.clone()).expect("wire decodes");
1883
1884        let ReplacementNotification::Original(read_back) = notification else {
1885            panic!("kind=original must decode to the Original variant");
1886        };
1887        assert_eq!(read_back.core.slot, 9);
1888        assert_eq!(
1889            read_back.core.original_signature.to_string(),
1890            fixture_signature()
1891        );
1892        assert_eq!(read_back.comparison.l1_fill, Some(2_000));
1893        assert_eq!(read_back.comparison.change_vs_l1_bps, Some(-25));
1894        assert_eq!(read_back.cost.compute_units_consumed, 31_400);
1895        assert_eq!(read_back.simulated_output_amount, Some(1_995));
1896        assert_eq!(read_back.core.outcome, "filled");
1897    }
1898
1899    /// A payload with no `kind` tag: an internally-tagged enum needs one to pick a variant, so
1900    /// this must fail loudly rather than silently misparse into either shape.
1901    #[test]
1902    fn an_untagged_old_format_payload_fails_to_deserialize() {
1903        let old_wire = serde_json::json!({
1904            "context": {"slot": 42},
1905            "slot": 42,
1906            "batchIndex": 3,
1907            "originalSignature": fixture_signature(),
1908            "legs": [],
1909            "routedTransaction": {"data": "AA==", "encoding": "base64"},
1910            "err": serde_json::Value::Null,
1911            "logs": [],
1912            "computeUnitsConsumed": 0,
1913            "fee": serde_json::Value::Null,
1914            "realizedOutputAmount": serde_json::Value::Null,
1915            "originalRealizedOutputAmount": serde_json::Value::Null,
1916            "originalFailed": false,
1917        });
1918
1919        let err = serde_json::from_value::<ReplacementNotification>(old_wire).expect_err(
1920            "an untagged old-format payload must not deserialize as a ReplacementNotification",
1921        );
1922        assert!(
1923            err.to_string().contains("kind"),
1924            "must fail on the missing tag, not misparse into either variant: {err}"
1925        );
1926    }
1927}