Skip to main content

orca_sdk/
events.rs

1use std::{sync::Arc, time::Duration};
2
3use tokio::sync::mpsc;
4
5use crate::{OrcaClient, types::OrcaResult};
6
7impl OrcaClient {
8    /// Monitors price changes for a given pool with production-ready error handling and configurable thresholds.
9    ///
10    /// # Params
11    ///
12    /// pool_address - The address of the liquidity pool to monitor
13    /// min_change_percent - Minimum percentage change required to trigger callback
14    /// callback - Function called when significant price change is detected
15    ///
16    /// # Examples
17    ///
18    /// ```rust
19    /// use std::sync::Arc;
20    /// use orca_sdk::OrcaClient;
21    ///
22    /// let client = Arc::new(OrcaClient::new().await?);
23    /// let pool_address = "POOL_ADDRESS_HERE";
24    ///
25    /// let monitor_handle = client.monitor_price_changes_production(
26    ///     pool_address,
27    ///     1.0, // 1% minimum change
28    ///     |update| {
29    ///         println!("Price changed: {}%", update.change_percent);
30    ///         println!("Old price: {}, New price: {}", update.old_price, update.new_price);
31    ///     },
32    /// ).await?;
33    /// ```
34    pub async fn monitor_price_changes_production<F>(
35        self: Arc<Self>,
36        pool_address: &str,
37        min_change_percent: f64,
38        callback: F,
39    ) -> OrcaResult<PriceMonitorHandle>
40    where
41        F: Fn(PriceUpdate) + Send + Sync + 'static,
42    {
43        let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);
44        let client = self;
45        let pool_address = pool_address.to_string();
46        let handle = tokio::spawn(async move {
47            let mut last_price: Option<f64> = None;
48            let mut consecutive_errors = 0;
49            const MAX_CONSECUTIVE_ERRORS: u32 = 5;
50            const POLL_INTERVAL: Duration = Duration::from_secs(10);
51            loop {
52                tokio::select! {
53                    _ = tokio::time::sleep(POLL_INTERVAL) => {}
54                    _ = shutdown_rx.recv() => {
55                        log::info!("Price monitor for {} shutting down", pool_address);
56                        break;
57                    }
58                }
59                let client_clone = client.clone();
60                // 使用克隆的客户端获取价格
61                match Self::get_current_price_impl(&client_clone, &pool_address).await {
62                    Ok(current_price) => {
63                        consecutive_errors = 0;
64                        if let Some(prev_price) = last_price {
65                            let prev_price: f64 = prev_price;
66                            let current_price: f64 = current_price;
67                            if prev_price > 0.0 {
68                                let change_percent =
69                                    ((current_price - prev_price) / prev_price).abs() * 100.0;
70                                if change_percent >= min_change_percent {
71                                    callback(PriceUpdate {
72                                        pool_address: pool_address.clone(),
73                                        old_price: prev_price,
74                                        new_price: current_price,
75                                        change_percent,
76                                        timestamp: chrono::Utc::now(),
77                                    });
78                                }
79                            }
80                        }
81                        last_price = Some(current_price);
82                    }
83                    Err(_e) => {
84                        consecutive_errors += 1;
85                        if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
86                            log::error!(
87                                "Too many consecutive errors, shutting down monitor for {}",
88                                pool_address
89                            );
90                            break;
91                        }
92                        tokio::time::sleep(Duration::from_secs(30)).await;
93                    }
94                }
95            }
96        });
97
98        Ok(PriceMonitorHandle {
99            shutdown_tx,
100            task_handle: handle,
101        })
102    }
103
104    /// Internal implementation for fetching current price from on-chain data
105    async fn get_current_price_impl(client: &OrcaClient, pool_address: &str) -> OrcaResult<f64> {
106        // 使用已有的池子状态获取价格
107        let pool_info = client.get_pool_state_onchain(pool_address).await?;
108        // 使用第一个代币作为基准计算价格
109        let base_mint = &pool_info.token_mint_a;
110        client
111            .derive_price_from_pool_state(&pool_info, base_mint)
112            .await
113    }
114}
115
116/// Handle for controlling a price monitoring task
117///
118/// Use this handle to gracefully shutdown the monitoring task
119/// when it's no longer needed.
120///
121/// # Examples
122///
123/// ```rust
124/// let client = std::sync::Arc::new(orca_sdk::OrcaClient::new().await?);
125/// let monitor_handle = client.monitor_price_changes_production(
126///     "POOL_ADDRESS",
127///     1.0,
128///     |_| {},
129/// ).await?;
130///
131/// // Shutdown the monitor when done
132/// monitor_handle.shutdown().await;
133/// ```
134#[derive(Debug)]
135pub struct PriceMonitorHandle {
136    shutdown_tx: mpsc::Sender<()>,
137    task_handle: tokio::task::JoinHandle<()>,
138}
139
140impl PriceMonitorHandle {
141    /// Gracefully shuts down the price monitoring task
142    ///
143    /// Sends a shutdown signal to the monitoring task and waits
144    /// for it to complete cleanup.
145    pub async fn shutdown(self) {
146        let _ = self.shutdown_tx.send(()).await;
147        let _ = self.task_handle.await;
148    }
149}
150/// Represents a significant price change event
151///
152/// Contains all relevant information about a price change
153/// that exceeded the configured threshold.
154#[derive(Debug, Clone)]
155pub struct PriceUpdate {
156    /// Address of the pool where the price change occurred
157    pub pool_address: String,
158    /// Price before the change
159    pub old_price: f64,
160    /// Current price after the change
161    pub new_price: f64,
162    /// Percentage change between old and new price
163    pub change_percent: f64,
164    /// Timestamp when the change was detected
165    pub timestamp: chrono::DateTime<chrono::Utc>,
166}