use std::{future::Future, time::Duration};
use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
use solana_account_decoder::{UiAccount, UiAccountData, UiAccountEncoding};
use solana_client::{
nonblocking::pubsub_client::PubsubClient,
rpc_response::{Response, RpcLogsResponse},
};
use solana_commitment_config::CommitmentConfig;
use solana_rpc_client_api::config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
use thiserror::Error;
use tokio::{
sync::{oneshot, watch},
task::JoinHandle,
};
use tokio_tungstenite::tungstenite::Message;
use crate::urls::{UrlError, http_to_ws_url};
#[derive(Debug, Error)]
pub enum SubscriptionError {
#[error(transparent)]
InvalidUrl(#[from] UrlError),
#[error("pubsub connect to {url} failed: {source}")]
Connect {
url: String,
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error("logs_subscribe failed: {source}")]
Subscribe {
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error("subscription task exited unexpectedly before signaling ready")]
TaskDropped,
#[error("session has no rpc_endpoint (was the session created?)")]
NoRpcEndpoint,
}
#[derive(Debug, Error)]
pub enum SubscriptionRuntimeError {
#[error("{kind} subscription for {target} closed unexpectedly")]
Closed { kind: &'static str, target: String },
#[error("{kind} subscription callback worker for {target} failed: {source}")]
CallbackWorker {
kind: &'static str,
target: String,
#[source]
source: tokio::task::JoinError,
},
}
const SUBSCRIPTION_DRAIN_IDLE_TIMEOUT: Duration = Duration::from_millis(250);
const SUBSCRIPTION_DRAIN_MAX_DURATION: Duration = Duration::from_secs(5);
type SubscriptionTaskHandle = JoinHandle<Result<(), SubscriptionRuntimeError>>;
type AccountDiffWs =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
pub struct SubscriptionHandle {
pub join_handle: SubscriptionTaskHandle,
pub stop: watch::Sender<bool>,
}
impl From<LogSubscriptionHandle> for SubscriptionHandle {
fn from(h: LogSubscriptionHandle) -> Self {
Self {
join_handle: h.join_handle,
stop: h.stop,
}
}
}
impl From<AccountDiffSubscriptionHandle> for SubscriptionHandle {
fn from(h: AccountDiffSubscriptionHandle) -> Self {
Self {
join_handle: h.join_handle,
stop: h.stop,
}
}
}
impl From<ActionSubscriptionHandle> for SubscriptionHandle {
fn from(h: ActionSubscriptionHandle) -> Self {
Self {
join_handle: h.join_handle,
stop: h.stop,
}
}
}
impl From<DiagnosticSubscriptionHandle> for SubscriptionHandle {
fn from(h: DiagnosticSubscriptionHandle) -> Self {
Self {
join_handle: h.join_handle,
stop: h.stop,
}
}
}
pub struct LogSubscriptionHandle {
pub join_handle: SubscriptionTaskHandle,
pub stop: watch::Sender<bool>,
}
pub async fn subscribe_program_logs<F, Fut>(
rpc_endpoint: &str,
program_id: &str,
commitment: CommitmentConfig,
on_notification: F,
) -> Result<LogSubscriptionHandle, SubscriptionError>
where
F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let ws_url = http_to_ws_url(rpc_endpoint)?;
let program_id = program_id.to_string();
let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
let (stop_tx, mut stop_rx) = watch::channel(false);
let join_handle = tokio::spawn(async move {
let client = match PubsubClient::new(&ws_url).await {
Ok(c) => c,
Err(e) => {
let _ = ready_tx.send(Err(SubscriptionError::Connect {
url: ws_url,
source: Box::new(e),
}));
return Ok(());
}
};
let (mut stream, _unsubscribe) = match client
.logs_subscribe(
RpcTransactionLogsFilter::Mentions(vec![program_id.clone()]),
RpcTransactionLogsConfig {
commitment: Some(commitment),
},
)
.await
{
Ok(s) => s,
Err(e) => {
let _ = ready_tx.send(Err(SubscriptionError::Subscribe {
source: Box::new(e),
}));
return Ok(());
}
};
let _ = ready_tx.send(Ok(()));
let mut tasks: Vec<JoinHandle<()>> = Vec::new();
let kind = "program logs";
loop {
if *stop_rx.borrow() {
let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
while let Ok(Ok(Some(notification))) = tokio::time::timeout_at(
drain_deadline,
tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, stream.next()),
)
.await
{
tasks.push(tokio::spawn(on_notification(notification)));
}
break;
}
let notification = tokio::select! {
n = stream.next() => n,
_ = stop_rx.changed() => continue,
};
match notification {
Some(n) => tasks.push(tokio::spawn(on_notification(n))),
None => return Err(subscription_runtime_closed(kind, &program_id)),
}
}
for task in tasks {
if let Err(source) = task.await {
return Err(callback_worker_failed(kind, &program_id, source));
}
}
Ok(())
});
match ready_rx.await {
Ok(Ok(())) => Ok(LogSubscriptionHandle {
join_handle,
stop: stop_tx,
}),
Ok(Err(e)) => {
join_handle.abort();
Err(e)
}
Err(_) => {
join_handle.abort();
Err(SubscriptionError::TaskDropped)
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct AccountDiffContext {
pub slot: u64,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AccountDiffNotification {
pub context: AccountDiffContext,
pub account: Option<String>,
pub signature: Option<String>,
#[serde(default)]
pub tx_index: Option<u32>,
#[serde(default)]
pub block_time: Option<i64>,
pub pre: Option<serde_json::Value>,
pub post: Option<serde_json::Value>,
}
impl AccountDiffNotification {
pub fn post_account_data(&self) -> Option<Result<AccountData, UiAccountConversionError>> {
self.post.as_ref().map(account_data_from_ui)
}
}
#[derive(Debug, Error)]
pub enum UiAccountConversionError {
#[error("payload is not a UiAccount: {0}")]
NotAUiAccount(#[from] serde_json::Error),
#[error("unsupported ui-account data encoding, expected base64")]
UnsupportedEncoding,
#[error("decoding base64 account data: {0}")]
Data(#[from] base64::DecodeError),
#[error("parsing owner address: {0}")]
Owner(#[from] solana_address::error::ParseAddressError),
}
pub fn account_data_from_ui(
value: &serde_json::Value,
) -> Result<AccountData, UiAccountConversionError> {
let ui = UiAccount::deserialize(value)?;
let UiAccountData::Binary(data, UiAccountEncoding::Base64) = ui.data else {
return Err(UiAccountConversionError::UnsupportedEncoding);
};
let encoded = EncodedBinary::new(data, BinaryEncoding::Base64);
let space = match ui.space {
Some(space) => space,
None => encoded.decode()?.len() as u64,
};
Ok(AccountData {
data: encoded,
executable: ui.executable,
lamports: ui.lamports,
owner: ui.owner.parse()?,
space,
})
}
#[derive(Debug, Clone, Deserialize)]
pub struct ActionResultContext {
pub slot: u64,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionResultNotification {
pub context: ActionResultContext,
pub slot: u64,
#[serde(default)]
pub batch_index: Option<u32>,
#[serde(default)]
pub tx_index: Option<u32>,
pub action_index: u32,
#[serde(default)]
pub label: Option<String>,
pub committed: bool,
#[serde(default)]
pub transaction_outcomes: Vec<ActionTransactionOutcome>,
#[serde(default)]
pub accounts: Vec<Option<serde_json::Value>>,
#[serde(default)]
pub matched: Option<EncodedBinary>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionTransactionOutcome {
#[serde(default)]
pub err: Option<String>,
#[serde(default)]
pub logs: Vec<String>,
pub units_consumed: u64,
#[serde(default)]
pub fee: Option<u64>,
#[serde(default)]
pub return_data: Option<serde_json::Value>,
}
#[derive(Debug, Clone)]
pub struct RoutedAccountDiffNotification {
pub account: String,
pub notification: AccountDiffNotification,
}
pub struct AccountDiffSubscriptionHandle {
pub join_handle: SubscriptionTaskHandle,
pub stop: watch::Sender<bool>,
}
fn subscription_runtime_closed(
kind: &'static str,
target: impl Into<String>,
) -> SubscriptionRuntimeError {
SubscriptionRuntimeError::Closed {
kind,
target: target.into(),
}
}
fn callback_worker_failed(
kind: &'static str,
target: impl Into<String>,
source: tokio::task::JoinError,
) -> SubscriptionRuntimeError {
SubscriptionRuntimeError::CallbackWorker {
kind,
target: target.into(),
source,
}
}
pub async fn subscribe_account_diffs<F, Fut>(
rpc_endpoint: &str,
account: &str,
on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
subscribe_account_diffs_many(rpc_endpoint, [account.to_string()], move |notification| {
on_notification(notification.notification)
})
.await
}
pub async fn subscribe_account_diffs_many<F, Fut, I, S>(
rpc_endpoint: &str,
accounts: I,
on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
F: Fn(RoutedAccountDiffNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
I: IntoIterator<Item = S>,
S: Into<String>,
{
let ws_url = http_to_ws_url(rpc_endpoint)?;
let accounts = dedup_accounts(accounts);
if accounts.is_empty() {
let (stop_tx, stop_rx) = watch::channel(false);
return Ok(AccountDiffSubscriptionHandle {
join_handle: tokio::spawn(async move {
let _ = stop_rx;
Ok(())
}),
stop: stop_tx,
});
}
let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
let (stop_tx, mut stop_rx) = watch::channel(false);
let target = format!("{} accounts", accounts.len());
let join_handle = tokio::spawn(async move {
let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
let callback_handle = tokio::spawn(async move {
while let Some(notification) = notification_rx.recv().await {
on_notification(notification).await;
}
});
let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
Ok(connection) => connection,
Err(e) => {
let _ = ready_tx.send(Err(SubscriptionError::Connect {
url: ws_url,
source: Box::new(e),
}));
return Ok(());
}
};
let subscriptions =
match send_account_diff_subscribe_many(&mut ws, &accounts, ¬ification_tx).await {
Ok(subscriptions) => subscriptions,
Err(error) => {
let _ = ready_tx.send(Err(error));
return Ok(());
}
};
let _ = ready_tx.send(Ok(()));
if let Err(error) =
drive_account_diff_stream_many(&mut ws, &subscriptions, ¬ification_tx, &mut stop_rx)
.await
{
drop(notification_tx);
if let Err(source) = callback_handle.await {
return Err(callback_worker_failed("account diff", target, source));
}
return Err(error);
}
drop(notification_tx);
if let Err(source) = callback_handle.await {
return Err(callback_worker_failed("account diff", target, source));
}
Ok(())
});
match ready_rx.await {
Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
join_handle,
stop: stop_tx,
}),
Ok(Err(e)) => {
join_handle.abort();
Err(e)
}
Err(_) => {
join_handle.abort();
Err(SubscriptionError::TaskDropped)
}
}
}
#[derive(Deserialize)]
struct AccountDiffMessage {
method: String,
params: AccountDiffParams,
}
#[derive(Deserialize)]
struct AccountDiffParams {
subscription: u64,
result: AccountDiffNotification,
}
async fn send_account_diff_subscribe_many(
ws: &mut AccountDiffWs,
accounts: &[String],
notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
) -> Result<std::collections::HashMap<u64, String>, SubscriptionError> {
#[derive(Deserialize)]
struct SubscriptionConfirmation {
id: u64,
result: Option<u64>,
}
let mut pending: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
let mut subscriptions = std::collections::HashMap::with_capacity(accounts.len());
for (index, account) in accounts.iter().enumerate() {
let request_id = (index + 1) as u64;
let req = serde_json::json!({
"jsonrpc": "2.0",
"id": request_id,
"method": "accountDiffSubscribe",
"params": [account]
});
ws.send(Message::Text(req.to_string()))
.await
.map_err(|source| SubscriptionError::Subscribe {
source: Box::new(source),
})?;
pending.insert(request_id, account.clone());
}
while !pending.is_empty() {
match ws.next().await {
Some(Ok(Message::Text(text))) => {
if let Ok(confirmation) = serde_json::from_str::<SubscriptionConfirmation>(&text) {
let Some(account) = pending.remove(&confirmation.id) else {
continue;
};
let Some(subscription_id) = confirmation.result else {
return Err(SubscriptionError::TaskDropped);
};
subscriptions.insert(subscription_id, account);
continue;
}
if let Some(notification) =
parse_routed_account_diff_notification(&text, &subscriptions)
{
let _ = notification_tx.send(notification);
}
}
Some(Ok(_)) => {}
_ => return Err(SubscriptionError::TaskDropped),
}
}
Ok(subscriptions)
}
async fn drive_account_diff_stream_many(
ws: &mut AccountDiffWs,
subscriptions: &std::collections::HashMap<u64, String>,
notification_tx: &tokio::sync::mpsc::UnboundedSender<RoutedAccountDiffNotification>,
stop_rx: &mut watch::Receiver<bool>,
) -> Result<(), SubscriptionRuntimeError> {
loop {
if *stop_rx.borrow() {
let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
loop {
match tokio::time::timeout_at(
drain_deadline,
tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
)
.await
{
Ok(Ok(Some(Ok(Message::Text(text))))) => {
if let Some(notification) =
parse_routed_account_diff_notification(&text, subscriptions)
{
let _ = notification_tx.send(notification);
}
}
_ => return Ok(()),
}
}
}
let msg = tokio::select! {
m = ws.next() => m,
_ = stop_rx.changed() => continue,
};
match msg {
Some(Ok(Message::Text(text))) => {
if let Some(notification) =
parse_routed_account_diff_notification(&text, subscriptions)
{
let _ = notification_tx.send(notification);
}
}
Some(Ok(_)) => {}
_ => {
return Err(subscription_runtime_closed(
"account diff",
format!("{} accounts", subscriptions.len()),
));
}
}
}
}
fn parse_account_diff_message(text: &str) -> Option<AccountDiffMessage> {
let msg: AccountDiffMessage = serde_json::from_str(text).ok()?;
(msg.method == "accountDiffNotification").then_some(msg)
}
fn parse_routed_account_diff_notification(
text: &str,
subscriptions: &std::collections::HashMap<u64, String>,
) -> Option<RoutedAccountDiffNotification> {
let msg = parse_account_diff_message(text)?;
let account = subscriptions.get(&msg.params.subscription)?.clone();
Some(RoutedAccountDiffNotification {
account,
notification: msg.params.result,
})
}
fn dedup_accounts<I, S>(accounts: I) -> Vec<String>
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let mut unique = std::collections::BTreeSet::new();
accounts
.into_iter()
.map(Into::into)
.filter(|account| unique.insert(account.clone()))
.collect()
}
pub async fn subscribe_program_diffs<F, Fut>(
rpc_endpoint: &str,
program_id: &str,
on_notification: F,
) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
where
F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let ws_url = http_to_ws_url(rpc_endpoint)?;
let program_id = program_id.to_string();
let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
let (stop_tx, mut stop_rx) = watch::channel(false);
let join_handle = tokio::spawn(async move {
let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
let callback_handle = tokio::spawn(async move {
while let Some(notification) = notification_rx.recv().await {
on_notification(notification).await;
}
});
let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
Ok(connection) => connection,
Err(e) => {
let _ = ready_tx.send(Err(SubscriptionError::Connect {
url: ws_url,
source: Box::new(e),
}));
return Ok(());
}
};
if let Err(error) = send_program_diff_subscribe(&mut ws, &program_id).await {
let _ = ready_tx.send(Err(error));
return Ok(());
}
let _ = ready_tx.send(Ok(()));
if let Err(error) =
drive_program_diff_stream(&mut ws, ¬ification_tx, &mut stop_rx, &program_id).await
{
drop(notification_tx);
if let Err(source) = callback_handle.await {
return Err(callback_worker_failed(
"program account diff",
&program_id,
source,
));
}
return Err(error);
}
drop(notification_tx);
if let Err(source) = callback_handle.await {
return Err(callback_worker_failed(
"program account diff",
&program_id,
source,
));
}
Ok(())
});
match ready_rx.await {
Ok(Ok(())) => Ok(AccountDiffSubscriptionHandle {
join_handle,
stop: stop_tx,
}),
Ok(Err(e)) => {
join_handle.abort();
Err(e)
}
Err(_) => {
join_handle.abort();
Err(SubscriptionError::TaskDropped)
}
}
}
async fn send_program_diff_subscribe(
ws: &mut AccountDiffWs,
program_id: &str,
) -> Result<(), SubscriptionError> {
#[derive(Deserialize)]
struct SubscriptionConfirmation {
result: Option<u64>,
}
let req = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": "accountDiffSubscribe",
"params": [program_id, {"address_type": "program"}]
});
ws.send(Message::Text(req.to_string()))
.await
.map_err(|source| SubscriptionError::Subscribe {
source: Box::new(source),
})?;
loop {
match ws.next().await {
Some(Ok(Message::Text(text))) => {
match serde_json::from_str::<SubscriptionConfirmation>(&text) {
Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
Ok(_) => continue,
Err(source) => {
return Err(SubscriptionError::Subscribe {
source: Box::new(source),
});
}
}
}
Some(Ok(_)) => continue,
_ => return Err(SubscriptionError::TaskDropped),
}
}
}
async fn drive_program_diff_stream(
ws: &mut AccountDiffWs,
notification_tx: &tokio::sync::mpsc::UnboundedSender<AccountDiffNotification>,
stop_rx: &mut watch::Receiver<bool>,
program_id: &str,
) -> Result<(), SubscriptionRuntimeError> {
loop {
if *stop_rx.borrow() {
let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
loop {
match tokio::time::timeout_at(
drain_deadline,
tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
)
.await
{
Ok(Ok(Some(Ok(Message::Text(text))))) => {
if let Some(msg) = parse_account_diff_message(&text) {
let _ = notification_tx.send(msg.params.result);
}
}
_ => return Ok(()),
}
}
}
let msg = tokio::select! {
m = ws.next() => m,
_ = stop_rx.changed() => continue,
};
match msg {
Some(Ok(Message::Text(text))) => {
if let Some(msg) = parse_account_diff_message(&text) {
let _ = notification_tx.send(msg.params.result);
}
}
Some(Ok(_)) => {}
_ => {
return Err(subscription_runtime_closed(
"program account diff",
program_id,
));
}
}
}
}
#[derive(Clone, Copy)]
struct NotificationStream {
subscribe_method: &'static str,
notification_method: &'static str,
kind: &'static str,
target: &'static str,
}
const ACTION_STREAM: NotificationStream = NotificationStream {
subscribe_method: "actionSubscribe",
notification_method: "actionNotification",
kind: "action",
target: "actions",
};
const REPLACEMENT_STREAM: NotificationStream = NotificationStream {
subscribe_method: "replacementSubscribe",
notification_method: "replacementNotification",
kind: "replacement",
target: "replacements",
};
const DIAGNOSTIC_STREAM: NotificationStream = NotificationStream {
subscribe_method: "diagnosticSubscribe",
notification_method: "diagnosticNotification",
kind: "diagnostic",
target: "diagnostics",
};
#[derive(Deserialize)]
struct NotificationMessage<N> {
method: String,
params: NotificationParams<N>,
}
#[derive(Deserialize)]
struct NotificationParams<N> {
#[allow(dead_code)]
subscription: u64,
result: N,
}
fn parse_notification_message<N: DeserializeOwned>(
text: &str,
notification_method: &str,
) -> Option<N> {
let msg: NotificationMessage<N> = serde_json::from_str(text).ok()?;
(msg.method == notification_method).then_some(msg.params.result)
}
fn is_subscription_complete_message(text: &str) -> bool {
#[derive(Deserialize)]
struct SubscriptionCompleteMessage {
method: String,
}
serde_json::from_str::<SubscriptionCompleteMessage>(text)
.is_ok_and(|msg| msg.method == "subscriptionComplete")
}
async fn subscribe_notifications<N, F, Fut>(
rpc_endpoint: &str,
stream: NotificationStream,
on_notification: F,
) -> Result<SubscriptionHandle, SubscriptionError>
where
N: DeserializeOwned + Send + 'static,
F: Fn(N) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let ws_url = http_to_ws_url(rpc_endpoint)?;
let (ready_tx, ready_rx) = oneshot::channel::<Result<(), SubscriptionError>>();
let (stop_tx, mut stop_rx) = watch::channel(false);
let join_handle = tokio::spawn(async move {
let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel();
let callback_handle = tokio::spawn(async move {
while let Some(notification) = notification_rx.recv().await {
on_notification(notification).await;
}
});
let (mut ws, _) = match tokio_tungstenite::connect_async(&ws_url).await {
Ok(connection) => connection,
Err(e) => {
let _ = ready_tx.send(Err(SubscriptionError::Connect {
url: ws_url,
source: Box::new(e),
}));
return Ok(());
}
};
if let Err(error) = send_stream_subscribe(&mut ws, stream.subscribe_method).await {
let _ = ready_tx.send(Err(error));
return Ok(());
}
let _ = ready_tx.send(Ok(()));
if let Err(error) =
drive_notification_stream::<N>(&mut ws, stream, ¬ification_tx, &mut stop_rx).await
{
drop(notification_tx);
if let Err(source) = callback_handle.await {
return Err(callback_worker_failed(stream.kind, stream.target, source));
}
return Err(error);
}
drop(notification_tx);
if let Err(source) = callback_handle.await {
return Err(callback_worker_failed(stream.kind, stream.target, source));
}
Ok(())
});
match ready_rx.await {
Ok(Ok(())) => Ok(SubscriptionHandle {
join_handle,
stop: stop_tx,
}),
Ok(Err(e)) => {
join_handle.abort();
Err(e)
}
Err(_) => {
join_handle.abort();
Err(SubscriptionError::TaskDropped)
}
}
}
async fn send_stream_subscribe(
ws: &mut AccountDiffWs,
subscribe_method: &str,
) -> Result<(), SubscriptionError> {
#[derive(Deserialize)]
struct SubscriptionConfirmation {
result: Option<u64>,
}
let req = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": subscribe_method,
"params": [serde_json::Value::Null, {}]
});
ws.send(Message::Text(req.to_string()))
.await
.map_err(|source| SubscriptionError::Subscribe {
source: Box::new(source),
})?;
loop {
match ws.next().await {
Some(Ok(Message::Text(text))) => {
match serde_json::from_str::<SubscriptionConfirmation>(&text) {
Ok(SubscriptionConfirmation { result: Some(_) }) => return Ok(()),
Ok(_) => continue,
Err(source) => {
return Err(SubscriptionError::Subscribe {
source: Box::new(source),
});
}
}
}
Some(Ok(_)) => continue,
_ => return Err(SubscriptionError::TaskDropped),
}
}
}
async fn drive_notification_stream<N: DeserializeOwned>(
ws: &mut AccountDiffWs,
stream: NotificationStream,
notification_tx: &tokio::sync::mpsc::UnboundedSender<N>,
stop_rx: &mut watch::Receiver<bool>,
) -> Result<(), SubscriptionRuntimeError> {
loop {
if *stop_rx.borrow() {
let drain_deadline = tokio::time::Instant::now() + SUBSCRIPTION_DRAIN_MAX_DURATION;
loop {
match tokio::time::timeout_at(
drain_deadline,
tokio::time::timeout(SUBSCRIPTION_DRAIN_IDLE_TIMEOUT, ws.next()),
)
.await
{
Ok(Ok(Some(Ok(Message::Text(text))))) => {
if is_subscription_complete_message(&text) {
return Ok(());
}
if let Some(result) =
parse_notification_message::<N>(&text, stream.notification_method)
{
let _ = notification_tx.send(result);
}
}
_ => return Ok(()),
}
}
}
let msg = tokio::select! {
m = ws.next() => m,
_ = stop_rx.changed() => continue,
};
match msg {
Some(Ok(Message::Text(text))) => {
if is_subscription_complete_message(&text) {
return Ok(());
}
if let Some(result) =
parse_notification_message::<N>(&text, stream.notification_method)
{
let _ = notification_tx.send(result);
}
}
Some(Ok(_)) => {}
_ => return Err(subscription_runtime_closed(stream.kind, stream.target)),
}
}
}
pub struct ActionSubscriptionHandle {
pub join_handle: SubscriptionTaskHandle,
pub stop: watch::Sender<bool>,
}
pub async fn subscribe_actions<F, Fut>(
rpc_endpoint: &str,
on_notification: F,
) -> Result<ActionSubscriptionHandle, SubscriptionError>
where
F: Fn(ActionResultNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let SubscriptionHandle { join_handle, stop } =
subscribe_notifications(rpc_endpoint, ACTION_STREAM, on_notification).await?;
Ok(ActionSubscriptionHandle { join_handle, stop })
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticContext {
pub slot: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticNotification {
pub context: DiagnosticContext,
pub slot: u64,
pub probe_index: u32,
#[serde(default)]
pub label: Option<String>,
pub market: String,
pub usd_value: u32,
#[serde(default)]
pub router_slot: Option<u64>,
#[serde(default)]
pub results: Option<serde_json::Value>,
#[serde(default)]
pub account_hashes: Vec<String>,
#[serde(default)]
pub err: Option<String>,
}
pub struct DiagnosticSubscriptionHandle {
pub join_handle: SubscriptionTaskHandle,
pub stop: watch::Sender<bool>,
}
pub async fn subscribe_diagnostics<F, Fut>(
rpc_endpoint: &str,
on_notification: F,
) -> Result<DiagnosticSubscriptionHandle, SubscriptionError>
where
F: Fn(DiagnosticNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let SubscriptionHandle { join_handle, stop } =
subscribe_notifications(rpc_endpoint, DIAGNOSTIC_STREAM, on_notification).await?;
Ok(DiagnosticSubscriptionHandle { join_handle, stop })
}
pub use simulator_api::replacement::{
DirectFillNotification, L1Score, OriginalNotification, ProbedHop, ReplacementContext,
ReplacementCore, ReplacementNotification, RequoteNotification, RerouteLegNotification,
};
pub async fn subscribe_replacements<F, Fut>(
rpc_endpoint: &str,
on_notification: F,
) -> Result<SubscriptionHandle, SubscriptionError>
where
F: Fn(ReplacementNotification) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
subscribe_notifications(rpc_endpoint, REPLACEMENT_STREAM, on_notification).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_account_diff_notification_ignores_other_messages() {
let confirmation = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
assert!(parse_account_diff_message(confirmation).is_none());
}
#[test]
fn parse_account_diff_notification_extracts_payload() {
let text = r#"{
"jsonrpc":"2.0",
"method":"accountDiffNotification",
"params":{
"subscription":7,
"result":{
"context":{"slot":123},
"signature":"sig",
"pre":{"a":1},
"post":{"a":2}
}
}
}"#;
let notification = parse_account_diff_message(text)
.expect("notification")
.params
.result;
assert_eq!(notification.context.slot, 123);
assert_eq!(notification.signature.as_deref(), Some("sig"));
assert_eq!(notification.pre, Some(serde_json::json!({"a": 1})));
assert_eq!(notification.post, Some(serde_json::json!({"a": 2})));
}
#[test]
fn parse_routed_account_diff_notification_extracts_subscription_account() {
let text = r#"{
"jsonrpc":"2.0",
"method":"accountDiffNotification",
"params":{
"subscription":42,
"result":{
"context":{"slot":456},
"signature":"sig",
"pre":null,
"post":{"a":2}
}
}
}"#;
let subscriptions = std::collections::HashMap::from([(42_u64, "acct".to_string())]);
let notification =
parse_routed_account_diff_notification(text, &subscriptions).expect("notification");
assert_eq!(notification.account, "acct");
assert_eq!(notification.notification.context.slot, 456);
}
#[test]
fn converts_ui_account_json() {
let value = serde_json::json!({
"lamports": 5,
"data": ["AQID", "base64"],
"owner": "11111111111111111111111111111111",
"executable": false,
"rentEpoch": 0,
});
let account = account_data_from_ui(&value).unwrap();
assert_eq!(account.lamports, 5);
assert_eq!(account.space, 3);
assert_eq!(account.data.decode().unwrap(), vec![1, 2, 3]);
}
#[test]
fn rejects_non_base64_encodings() {
let value = serde_json::json!({
"lamports": 5,
"data": ["{}", "jsonParsed"],
"owner": "11111111111111111111111111111111",
"executable": false,
"rentEpoch": 0,
});
assert!(matches!(
account_data_from_ui(&value),
Err(UiAccountConversionError::UnsupportedEncoding)
));
}
#[test]
fn dedup_accounts_preserves_first_seen_order() {
let accounts = dedup_accounts([
"b".to_string(),
"a".to_string(),
"b".to_string(),
"c".to_string(),
]);
assert_eq!(accounts, vec!["b", "a", "c"]);
}
fn fixture_signature() -> String {
simulator_api::replacement::Signature::default().to_string()
}
fn route_hop(set: serde_json::Value, program: serde_json::Value) -> serde_json::Value {
use serde_json::json;
let mut swap_info = json!({
"label": null, "ammKey": null, "inputMint": null,
"inAmount": null, "outputMint": null, "outAmount": null,
});
for (key, value) in set.as_object().expect("an object") {
swap_info[key] = value.clone();
}
json!({"leg": null, "percent": 100, "program": program, "bps": null, "swapInfo": swap_info})
}
#[test]
fn a_requote_notification_round_trips_through_its_own_encoding() {
use serde_json::{Value, json};
let wire = serde_json::json!({
"kind": "requote",
"context": {"slot": 42},
"slot": 42,
"batchIndex": 3,
"originalSignature": fixture_signature(),
"originalFailed": false,
"outcome": "filled",
"legs": [{
"inputMint": simulator_api::mints::SOL.to_string(),
"outputMint": simulator_api::mints::USDC.to_string(),
"amount": 1_000,
"swapMode": "ExactIn",
"originalQuotedOut": 990,
"metisQuotedOut": 1_010,
"routeSummary": "SolFi",
"routePlan": [route_hop(json!({"ammKey": "pool", "label": "SolFi"}), Value::Null)],
"originalRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "990"}), json!("prog"))],
"realizedRoutePlan": [route_hop(json!({"inAmount": "1000", "outAmount": "1009"}), json!("prog"))],
}],
"routedTransaction": {"data": "AA==", "encoding": "base64"},
"logs": ["Program log: swap"],
"computeUnitsConsumed": 123_456,
"fee": 5_000,
"realizedOutputAmount": 1_009,
"originalRealizedOutputAmount": 991,
});
let notification: ReplacementNotification =
serde_json::from_value(wire.clone()).expect("wire decodes");
let recorded = serde_json::to_value(¬ification).expect("notification encodes");
assert_eq!(recorded, wire);
let ReplacementNotification::Requote(read_back) =
serde_json::from_value::<ReplacementNotification>(recorded).expect("recording decodes")
else {
panic!("kind=requote must decode to the Requote variant");
};
assert_eq!(read_back.core.batch_index, 3);
assert_eq!(read_back.legs[0].swap_mode, "ExactIn");
assert_eq!(read_back.original_realized_output_amount, Some(991));
assert!(
read_back
.legs
.iter()
.all(|leg| leg.realized_route_plan.is_some() && leg.route_plan.is_some())
);
}
#[test]
fn a_direct_fill_notification_round_trips_through_its_own_encoding() {
let wire = serde_json::json!({
"kind": "directFill",
"context": {"slot": 7},
"slot": 7,
"batchIndex": 1,
"originalSignature": fixture_signature(),
"originalFailed": false,
"template": "Tempest",
"program": simulator_api::mints::USDC.to_string(),
"hop": {
"slot": 9,
"blockTime": 1_767_225_600i64,
"txIndex": 4,
"ixIndex": 0,
"legIndex": 0,
"program": simulator_api::mints::SOL.to_string(),
"inputAmount": 1_000,
"outputAmount": 1_000,
"replayInputAmount": 1_000,
"replayOutputAmount": 1_005,
},
"quoteTxIndex": 1,
"quoteLagBlocks": 2,
"inputMint": simulator_api::mints::SOL.to_string(),
"outputMint": simulator_api::mints::USDC.to_string(),
"amount": 1_000,
"swapMode": "ExactIn",
"templateFill": 1_010,
"l1Fill": 1_000,
"changeVsL1Bps": 100,
"outcome": "filled",
});
let notification: ReplacementNotification =
serde_json::from_value(wire.clone()).expect("wire decodes");
let recorded = serde_json::to_value(¬ification).expect("notification encodes");
assert_eq!(recorded, wire);
let ReplacementNotification::DirectFill(read_back) = notification else {
panic!("kind=directFill must decode to the DirectFill variant");
};
assert_eq!(read_back.template, "Tempest");
assert_eq!(read_back.template_fill, Some(1_010));
assert_eq!(read_back.comparison.l1_fill, Some(1_000));
assert_eq!(read_back.comparison.change_vs_l1_bps, Some(100));
assert!(
read_back.core.category.is_none(),
"a filled probe carries no category"
);
}
#[test]
fn an_original_notification_round_trips_through_its_own_encoding() {
let wire = serde_json::json!({
"kind": "original",
"context": {"slot": 9},
"slot": 9,
"batchIndex": 2,
"originalSignature": fixture_signature(),
"originalFailed": false,
"l1Fill": 2_000,
"changeVsL1Bps": -25,
"computeUnitsConsumed": 31_400,
"fee": 5_000,
"simulatedOutputAmount": 1_995,
"outcome": "filled",
});
let notification: ReplacementNotification =
serde_json::from_value(wire.clone()).expect("wire decodes");
let ReplacementNotification::Original(read_back) = notification else {
panic!("kind=original must decode to the Original variant");
};
assert_eq!(read_back.core.slot, 9);
assert_eq!(
read_back.core.original_signature.to_string(),
fixture_signature()
);
assert_eq!(read_back.comparison.l1_fill, Some(2_000));
assert_eq!(read_back.comparison.change_vs_l1_bps, Some(-25));
assert_eq!(read_back.cost.compute_units_consumed, 31_400);
assert_eq!(read_back.simulated_output_amount, Some(1_995));
assert_eq!(read_back.core.outcome, "filled");
}
#[test]
fn an_untagged_old_format_payload_fails_to_deserialize() {
let old_wire = serde_json::json!({
"context": {"slot": 42},
"slot": 42,
"batchIndex": 3,
"originalSignature": fixture_signature(),
"legs": [],
"routedTransaction": {"data": "AA==", "encoding": "base64"},
"err": serde_json::Value::Null,
"logs": [],
"computeUnitsConsumed": 0,
"fee": serde_json::Value::Null,
"realizedOutputAmount": serde_json::Value::Null,
"originalRealizedOutputAmount": serde_json::Value::Null,
"originalFailed": false,
});
let err = serde_json::from_value::<ReplacementNotification>(old_wire).expect_err(
"an untagged old-format payload must not deserialize as a ReplacementNotification",
);
assert!(
err.to_string().contains("kind"),
"must fail on the missing tag, not misparse into either variant: {err}"
);
}
}