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