use crate::{Result, ToolkitError};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use solana_sdk::{pubkey::Pubkey, signature::Signature};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot, RwLock};
use tokio_tungstenite::{connect_async, tungstenite::Message};
pub type SubscriptionId = u64;
#[derive(Debug, Clone)]
pub enum WebsocketEvent {
SlotUpdate(u64),
AccountChange {
pubkey: Pubkey,
data: Vec<u8>,
slot: u64,
},
LogsUpdate {
signature: Signature,
logs: Vec<String>,
},
TransactionConfirmed(Signature),
Connected,
Disconnected,
Error(String),
}
#[derive(Debug, Clone, Serialize)]
struct SubscribeRequest {
jsonrpc: String,
id: u64,
method: String,
params: serde_json::Value,
}
#[derive(Debug, Clone, Deserialize)]
struct Notification {
jsonrpc: String,
method: String,
params: NotificationParams,
}
#[derive(Debug, Clone, Deserialize)]
struct NotificationParams {
result: serde_json::Value,
subscription: u64,
}
#[derive(Debug, Clone, Deserialize)]
struct SubscriptionResponse {
jsonrpc: String,
result: u64,
id: u64,
}
#[derive(Debug, Clone)]
pub enum WsError {
ConnectionFailed(String),
SubscriptionFailed(String),
SendFailed(String),
Timeout(String),
ParseError(String),
}
impl std::fmt::Display for WsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WsError::ConnectionFailed(msg) => write!(f, "Connection failed: {}", msg),
WsError::SubscriptionFailed(msg) => write!(f, "Subscription failed: {}", msg),
WsError::SendFailed(msg) => write!(f, "Send failed: {}", msg),
WsError::Timeout(msg) => write!(f, "Timeout: {}", msg),
WsError::ParseError(msg) => write!(f, "Parse error: {}", msg),
}
}
}
impl std::error::Error for WsError {}
impl From<WsError> for ToolkitError {
fn from(e: WsError) -> Self {
ToolkitError::NetworkError(e.to_string())
}
}
pub type EventCallback = Box<dyn Fn(WebsocketEvent) + Send + Sync>;
struct Subscription {
id: SubscriptionId,
callback: EventCallback,
}
pub struct SolanaWebsocket {
url: String,
next_id: AtomicU64,
subscriptions: RwLock<HashMap<u64, Subscription>>,
command_tx: Option<mpsc::Sender<WsCommand>>,
connected: Arc<std::sync::atomic::AtomicBool>,
}
enum WsCommand {
Subscribe {
method: String,
params: serde_json::Value,
response_tx: oneshot::Sender<Result<u64>>,
},
Unsubscribe {
subscription_id: u64,
response_tx: oneshot::Sender<Result<()>>,
},
SendMessage {
message: String,
},
}
impl SolanaWebsocket {
pub fn new(wss_url: &str) -> Self {
Self {
url: wss_url.to_string(),
next_id: AtomicU64::new(1),
subscriptions: RwLock::new(HashMap::new()),
command_tx: None,
connected: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}
}
pub async fn connect(&mut self) -> Result<()> {
let (ws_stream, _) = connect_async(&self.url)
.await
.map_err(|e| WsError::ConnectionFailed(e.to_string()))?;
let (mut write, mut read) = ws_stream.split();
let (command_tx, mut command_rx) = mpsc::channel::<WsCommand>(100);
let (_event_tx, _event_rx) = mpsc::channel::<WebsocketEvent>(1000);
self.command_tx = Some(command_tx);
self.connected.store(true, Ordering::Relaxed);
let connected = self.connected.clone();
let subscriptions = Arc::new(RwLock::new(HashMap::<u64, EventCallback>::new()));
let subs_for_read = subscriptions.clone();
tokio::spawn(async move {
while let Some(cmd) = command_rx.recv().await {
match cmd {
WsCommand::SendMessage { message } => {
if write.send(Message::Text(message.into())).await.is_err() {
break;
}
}
_ => {}
}
}
});
tokio::spawn(async move {
while let Some(msg) = read.next().await {
match msg {
Ok(Message::Text(text)) => {
if let Ok(notification) = serde_json::from_str::<Notification>(&text) {
let subs = subs_for_read.read().await;
if let Some(callback) = subs.get(¬ification.params.subscription) {
let event = parse_event(¬ification.method, ¬ification.params.result);
callback(event);
}
}
}
Ok(Message::Close(_)) => {
connected.store(false, Ordering::Relaxed);
break;
}
Err(_) => {
connected.store(false, Ordering::Relaxed);
break;
}
_ => {}
}
}
});
Ok(())
}
pub fn is_connected(&self) -> bool {
self.connected.load(Ordering::Relaxed)
}
fn next_id(&self) -> u64 {
self.next_id.fetch_add(1, Ordering::Relaxed)
}
pub async fn subscribe_account<F>(
&self,
pubkey: &Pubkey,
callback: F,
) -> Result<SubscriptionId>
where
F: Fn(Vec<u8>) + Send + Sync + 'static,
{
let request_id = self.next_id();
let request = SubscribeRequest {
jsonrpc: "2.0".to_string(),
id: request_id,
method: "accountSubscribe".to_string(),
params: serde_json::json!([
pubkey.to_string(),
{"encoding": "base64", "commitment": "confirmed"}
]),
};
let sub_id = self.send_subscribe_request(request).await?;
let wrapped: EventCallback = Box::new(move |event| {
if let WebsocketEvent::AccountChange { data, .. } = event {
callback(data);
}
});
self.subscriptions.write().await.insert(
sub_id,
Subscription {
id: sub_id,
callback: wrapped,
},
);
Ok(sub_id)
}
pub async fn subscribe_logs<F>(
&self,
program_id: &Pubkey,
callback: F,
) -> Result<SubscriptionId>
where
F: Fn(Vec<String>) + Send + Sync + 'static,
{
let request_id = self.next_id();
let request = SubscribeRequest {
jsonrpc: "2.0".to_string(),
id: request_id,
method: "logsSubscribe".to_string(),
params: serde_json::json!([
{"mentions": [program_id.to_string()]},
{"commitment": "confirmed"}
]),
};
let sub_id = self.send_subscribe_request(request).await?;
let wrapped: EventCallback = Box::new(move |event| {
if let WebsocketEvent::LogsUpdate { logs, .. } = event {
callback(logs);
}
});
self.subscriptions.write().await.insert(
sub_id,
Subscription {
id: sub_id,
callback: wrapped,
},
);
Ok(sub_id)
}
pub async fn subscribe_slots<F>(&self, callback: F) -> Result<SubscriptionId>
where
F: Fn(u64) + Send + Sync + 'static,
{
let request_id = self.next_id();
let request = SubscribeRequest {
jsonrpc: "2.0".to_string(),
id: request_id,
method: "slotSubscribe".to_string(),
params: serde_json::json!([]),
};
let sub_id = self.send_subscribe_request(request).await?;
let wrapped: EventCallback = Box::new(move |event| {
if let WebsocketEvent::SlotUpdate(slot) = event {
callback(slot);
}
});
self.subscriptions.write().await.insert(
sub_id,
Subscription {
id: sub_id,
callback: wrapped,
},
);
Ok(sub_id)
}
pub async fn wait_for_confirmation(
&self,
signature: &Signature,
timeout_ms: u64,
) -> Result<bool> {
let sig = *signature;
let (tx, mut rx) = mpsc::channel(1);
let request_id = self.next_id();
let request = SubscribeRequest {
jsonrpc: "2.0".to_string(),
id: request_id,
method: "signatureSubscribe".to_string(),
params: serde_json::json!([
sig.to_string(),
{"commitment": "confirmed"}
]),
};
let sub_id = self.send_subscribe_request(request).await?;
let wrapped: EventCallback = Box::new(move |event| {
if let WebsocketEvent::TransactionConfirmed(_) = event {
let _ = tx.try_send(true);
}
});
self.subscriptions.write().await.insert(
sub_id,
Subscription {
id: sub_id,
callback: wrapped,
},
);
let result = tokio::time::timeout(
Duration::from_millis(timeout_ms),
rx.recv(),
)
.await;
self.unsubscribe(sub_id).await?;
match result {
Ok(Some(true)) => Ok(true),
Ok(_) => Ok(false),
Err(_) => Err(WsError::Timeout("Transaction confirmation timeout".to_string()).into()),
}
}
pub async fn unsubscribe(&self, id: SubscriptionId) -> Result<()> {
self.subscriptions.write().await.remove(&id);
let request_id = self.next_id();
let request = SubscribeRequest {
jsonrpc: "2.0".to_string(),
id: request_id,
method: "slotUnsubscribe".to_string(), params: serde_json::json!([id]),
};
if let Some(tx) = &self.command_tx {
let msg = serde_json::to_string(&request)
.map_err(|e| WsError::ParseError(e.to_string()))?;
tx.send(WsCommand::SendMessage { message: msg })
.await
.map_err(|e| WsError::SendFailed(e.to_string()))?;
}
Ok(())
}
async fn send_subscribe_request(&self, request: SubscribeRequest) -> Result<u64> {
let tx = self
.command_tx
.as_ref()
.ok_or_else(|| WsError::ConnectionFailed("Not connected".to_string()))?;
let msg = serde_json::to_string(&request)
.map_err(|e| WsError::ParseError(e.to_string()))?;
tx.send(WsCommand::SendMessage { message: msg })
.await
.map_err(|e| WsError::SendFailed(e.to_string()))?;
Ok(request.id)
}
pub async fn close(&mut self) {
self.command_tx = None;
self.connected.store(false, Ordering::Relaxed);
}
}
fn parse_event(method: &str, result: &serde_json::Value) -> WebsocketEvent {
match method {
"slotNotification" => {
let slot = result.get("slot").and_then(|s| s.as_u64()).unwrap_or(0);
WebsocketEvent::SlotUpdate(slot)
}
"accountNotification" => {
let data = result
.get("value")
.and_then(|v| v.get("data"))
.and_then(|d| d.as_array())
.and_then(|arr| arr.first())
.and_then(|s| s.as_str())
.and_then(|s| base64::Engine::decode(&base64::engine::general_purpose::STANDARD, s).ok())
.unwrap_or_default();
let slot = result
.get("context")
.and_then(|c| c.get("slot"))
.and_then(|s| s.as_u64())
.unwrap_or(0);
WebsocketEvent::AccountChange {
pubkey: Pubkey::default(), data,
slot,
}
}
"logsNotification" => {
let logs = result
.get("value")
.and_then(|v| v.get("logs"))
.and_then(|l| l.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let sig_str = result
.get("value")
.and_then(|v| v.get("signature"))
.and_then(|s| s.as_str())
.unwrap_or_default();
let signature = sig_str.parse().unwrap_or_default();
WebsocketEvent::LogsUpdate { signature, logs }
}
"signatureNotification" => {
let sig_str = result
.get("value")
.and_then(|v| v.get("signature"))
.and_then(|s| s.as_str())
.unwrap_or_default();
let signature = sig_str.parse().unwrap_or_default();
WebsocketEvent::TransactionConfirmed(signature)
}
_ => WebsocketEvent::Error(format!("Unknown method: {}", method)),
}
}
pub struct PoolWatcher {
ws: SolanaWebsocket,
dex_programs: Vec<Pubkey>,
}
impl PoolWatcher {
pub fn new(wss_url: &str) -> Self {
Self {
ws: SolanaWebsocket::new(wss_url),
dex_programs: vec![],
}
}
pub fn watch_dex(&mut self, program_id: Pubkey) {
self.dex_programs.push(program_id);
}
pub async fn start<F>(&mut self, callback: F) -> Result<()>
where
F: Fn(Pubkey, Vec<String>) + Send + Sync + Clone + 'static,
{
self.ws.connect().await?;
for program_id in &self.dex_programs {
let cb = callback.clone();
let pid = *program_id;
self.ws
.subscribe_logs(program_id, move |logs| {
let is_pool_creation = logs.iter().any(|log| {
log.contains("InitializePool")
|| log.contains("Initialize2")
|| log.contains("createPool")
});
if is_pool_creation {
cb(pid, logs);
}
})
.await?;
}
Ok(())
}
pub async fn stop(&mut self) {
self.ws.close().await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_websocket_creation() {
let ws = SolanaWebsocket::new("wss://api.mainnet-beta.solana.com");
assert!(!ws.is_connected());
}
#[test]
fn test_parse_slot_event() {
let result = serde_json::json!({"slot": 12345});
let event = parse_event("slotNotification", &result);
match event {
WebsocketEvent::SlotUpdate(slot) => assert_eq!(slot, 12345),
_ => panic!("Expected SlotUpdate"),
}
}
#[test]
fn test_parse_logs_event() {
let result = serde_json::json!({
"value": {
"logs": ["Program log: Instruction: Initialize", "Program success"],
"signature": "5K..."
}
});
let event = parse_event("logsNotification", &result);
match event {
WebsocketEvent::LogsUpdate { logs, .. } => {
assert_eq!(logs.len(), 2);
}
_ => panic!("Expected LogsUpdate"),
}
}
#[test]
fn test_pool_watcher_creation() {
let mut watcher = PoolWatcher::new("wss://api.mainnet-beta.solana.com");
watcher.watch_dex(Pubkey::new_unique());
assert_eq!(watcher.dex_programs.len(), 1);
}
}