solana-pipkit 2.2.0

Pragmatic Rust utilities for Solana development - safety, speed, analytics, and DeFi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Real-time websocket listener for fastest reaction times.
//!
//! This module provides websocket subscriptions to Solana events for
//! real-time trading signals and instant transaction confirmation.
//!
//! # Features
//! - Account change subscriptions
//! - Program log subscriptions (for pool detection)
//! - Slot updates
//! - Transaction confirmation watching
//!
//! # Example
//! ```rust,no_run
//! use solana_pipkit::speed::SolanaWebsocket;
//! use solana_sdk::pubkey::Pubkey;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let ws = SolanaWebsocket::new("wss://api.mainnet-beta.solana.com");
//!
//!     // Subscribe to slot updates
//!     let subscription = ws.subscribe_slots(|slot| {
//!         println!("New slot: {}", slot);
//!     }).await?;
//!
//!     // Keep running...
//!     tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
//!
//!     ws.unsubscribe(subscription).await?;
//!     Ok(())
//! }
//! ```

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};

/// Subscription ID type.
pub type SubscriptionId = u64;

/// Websocket events.
#[derive(Debug, Clone)]
pub enum WebsocketEvent {
    /// Slot update.
    SlotUpdate(u64),
    /// Account data changed.
    AccountChange {
        /// Account pubkey.
        pubkey: Pubkey,
        /// New account data.
        data: Vec<u8>,
        /// Slot of the update.
        slot: u64,
    },
    /// Program logs.
    LogsUpdate {
        /// Transaction signature.
        signature: Signature,
        /// Log messages.
        logs: Vec<String>,
    },
    /// Transaction confirmed.
    TransactionConfirmed(Signature),
    /// Connection established.
    Connected,
    /// Connection lost.
    Disconnected,
    /// Error occurred.
    Error(String),
}

/// Websocket subscription request.
#[derive(Debug, Clone, Serialize)]
struct SubscribeRequest {
    jsonrpc: String,
    id: u64,
    method: String,
    params: serde_json::Value,
}

/// Websocket notification.
#[derive(Debug, Clone, Deserialize)]
struct Notification {
    jsonrpc: String,
    method: String,
    params: NotificationParams,
}

/// Notification parameters.
#[derive(Debug, Clone, Deserialize)]
struct NotificationParams {
    result: serde_json::Value,
    subscription: u64,
}

/// Subscription response.
#[derive(Debug, Clone, Deserialize)]
struct SubscriptionResponse {
    jsonrpc: String,
    result: u64,
    id: u64,
}

/// Websocket error types.
#[derive(Debug, Clone)]
pub enum WsError {
    /// Connection failed.
    ConnectionFailed(String),
    /// Subscription failed.
    SubscriptionFailed(String),
    /// Send failed.
    SendFailed(String),
    /// Timeout.
    Timeout(String),
    /// Parse error.
    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())
    }
}

/// Callback type for event handlers.
pub type EventCallback = Box<dyn Fn(WebsocketEvent) + Send + Sync>;

/// Internal subscription state.
struct Subscription {
    id: SubscriptionId,
    callback: EventCallback,
}

/// Solana websocket client for real-time updates.
pub struct SolanaWebsocket {
    /// Websocket URL.
    url: String,
    /// Next request ID.
    next_id: AtomicU64,
    /// Active subscriptions.
    subscriptions: RwLock<HashMap<u64, Subscription>>,
    /// Command channel.
    command_tx: Option<mpsc::Sender<WsCommand>>,
    /// Connection state.
    connected: Arc<std::sync::atomic::AtomicBool>,
}

/// Internal commands.
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 {
    /// Create a new websocket client.
    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)),
        }
    }

    /// Connect to the websocket.
    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();

        // Spawn write task
        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;
                        }
                    }
                    _ => {}
                }
            }
        });

        // Spawn read task
        tokio::spawn(async move {
            while let Some(msg) = read.next().await {
                match msg {
                    Ok(Message::Text(text)) => {
                        // Parse and dispatch events
                        if let Ok(notification) = serde_json::from_str::<Notification>(&text) {
                            let subs = subs_for_read.read().await;
                            if let Some(callback) = subs.get(&notification.params.subscription) {
                                // Parse event based on method
                                let event = parse_event(&notification.method, &notification.params.result);
                                callback(event);
                            }
                        }
                    }
                    Ok(Message::Close(_)) => {
                        connected.store(false, Ordering::Relaxed);
                        break;
                    }
                    Err(_) => {
                        connected.store(false, Ordering::Relaxed);
                        break;
                    }
                    _ => {}
                }
            }
        });

        Ok(())
    }

    /// Check if connected.
    pub fn is_connected(&self) -> bool {
        self.connected.load(Ordering::Relaxed)
    }

    /// Get next request ID.
    fn next_id(&self) -> u64 {
        self.next_id.fetch_add(1, Ordering::Relaxed)
    }

    /// Subscribe to account changes.
    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?;

        // Wrap callback
        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)
    }

    /// Subscribe to program logs.
    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)
    }

    /// Subscribe to slot updates.
    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)
    }

    /// Wait for transaction confirmation.
    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,
            },
        );

        // Wait for confirmation or timeout
        let result = tokio::time::timeout(
            Duration::from_millis(timeout_ms),
            rx.recv(),
        )
        .await;

        // Cleanup subscription
        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()),
        }
    }

    /// Unsubscribe.
    pub async fn unsubscribe(&self, id: SubscriptionId) -> Result<()> {
        self.subscriptions.write().await.remove(&id);

        // Send unsubscribe request (simplified - real impl would track subscription type)
        let request_id = self.next_id();
        let request = SubscribeRequest {
            jsonrpc: "2.0".to_string(),
            id: request_id,
            method: "slotUnsubscribe".to_string(), // Would need to track actual method
            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(())
    }

    /// Send subscription request.
    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()))?;

        // In a real implementation, we'd wait for the subscription response
        // For now, return the request ID as subscription ID
        Ok(request.id)
    }

    /// Close the connection.
    pub async fn close(&mut self) {
        self.command_tx = None;
        self.connected.store(false, Ordering::Relaxed);
    }
}

/// Parse websocket event from notification.
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(), // Would need to track this
                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)),
    }
}

/// Pool watcher for detecting new liquidity pools.
pub struct PoolWatcher {
    ws: SolanaWebsocket,
    dex_programs: Vec<Pubkey>,
}

impl PoolWatcher {
    /// Create a new pool watcher.
    pub fn new(wss_url: &str) -> Self {
        Self {
            ws: SolanaWebsocket::new(wss_url),
            dex_programs: vec![],
        }
    }

    /// Add DEX program to watch.
    pub fn watch_dex(&mut self, program_id: Pubkey) {
        self.dex_programs.push(program_id);
    }

    /// Start watching for new pools.
    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| {
                    // Check for pool creation 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(())
    }

    /// Stop watching.
    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);
    }
}