Skip to main content

simulator_client/
subscriptions.rs

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