Skip to main content

orca_sdk/
monitoring.rs

1use solana_commitment_config::CommitmentConfig;
2use solana_transaction_status::UiTransactionEncoding;
3
4use super::*;
5use crate::{pool::PoolInfo, types::OrcaResult};
6use std::collections::HashMap;
7
8#[derive(Debug, Clone)]
9pub struct PriceData {
10    pub timestamp: u64,
11    pub price: f64,
12    pub liquidity: u128,
13}
14
15#[derive(Debug, Clone)]
16pub struct PriceAlert {
17    pub token_pair: String,
18    pub target_price: f64,
19    pub condition: PriceCondition,
20}
21
22#[derive(Debug, Clone)]
23pub enum PriceCondition {
24    Above,
25    Below,
26}
27
28#[derive(Debug, Clone)]
29pub struct PriceMonitor {
30    alerts: HashMap<String, Vec<PriceAlert>>,
31}
32
33impl OrcaClient {
34    /// Monitors the health of a liquidity pool by analyzing key metrics.
35    ///
36    /// # Params
37    /// pool_address - The address of the pool to monitor
38    ///
39    /// # Returns
40    /// Returns a `PoolHealth` struct containing liquidity, volume, fee growth, and health score
41    ///
42    /// # Example
43    /// ```no_run
44    /// use orca_client::OrcaClient;
45    ///
46    /// tokio_test::block_on(async {
47    /// let client = OrcaClient::new();
48    /// let pool_health = client.monitor_pool_health("POOL_ADDRESS_HERE").await.unwrap();
49    /// println!("Pool health score: {}", pool_health.health_score);
50    /// });
51    /// ```
52    pub async fn monitor_pool_health(&self, pool_address: &str) -> OrcaResult<PoolHealth> {
53        let pool_info = self.get_pool_state_onchain(pool_address).await?;
54        let liquidity = pool_info.liquidity;
55        let volume_24h = self.estimate_24h_volume(&pool_info).await?;
56        let fee_growth = pool_info.fee_growth_global_a + pool_info.fee_growth_global_b;
57        Ok(PoolHealth {
58            liquidity,
59            volume_24h,
60            fee_growth,
61            health_score: self.calculate_health_score(liquidity, volume_24h, fee_growth),
62        })
63    }
64
65    /// Estimates 24-hour trading volume using multiple reliable methods.
66    ///
67    /// Combines fee-based estimation and transaction count analysis for robust volume calculation.
68    async fn estimate_24h_volume(&self, pool: &PoolInfo) -> OrcaResult<u64> {
69        let client = self
70            .solana
71            .client
72            .as_ref()
73            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
74        let pool_pubkey = Pubkey::from_str(&pool.address)
75            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
76        let volume_from_fees = self.estimate_volume_from_fee_growth(pool).await?;
77        let volume_from_tx_count = self.estimate_volume_from_tx_count(&pool_pubkey).await?;
78        Ok(volume_from_fees.max(volume_from_tx_count))
79    }
80
81    /// Estimates trading volume based on fee growth data.
82    ///
83    /// This is the most stable and reliable method for volume estimation.
84    async fn estimate_volume_from_fee_growth(&self, pool: &PoolInfo) -> OrcaResult<u64> {
85        let total_fee_growth = pool.fee_growth_global_a + pool.fee_growth_global_b;
86        const FEE_RATE: f64 = 0.003;
87        let estimated_volume = (total_fee_growth as f64 / FEE_RATE) as u64;
88        Ok(estimated_volume.min((u64::MAX as u128).try_into().unwrap()) as u64)
89    }
90
91    /// Estimates trading volume based on transaction count analysis.
92    ///
93    /// Uses recent transaction samples to extrapolate daily volume.
94    async fn estimate_volume_from_tx_count(&self, pool_pubkey: &Pubkey) -> OrcaResult<u64> {
95        let client = self
96            .solana
97            .client
98            .as_ref()
99            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
100        let signatures = client
101            .get_signatures_for_address(pool_pubkey)
102            .await
103            .map_err(|e| OrcaError::Error(format!("Failed to get signatures: {}", e)))?;
104        let mut total_sample_volume = 0u64;
105        let mut sample_count = 0;
106        for sig_info in signatures.iter().take(20) {
107            if let Some(volume) = self.estimate_single_tx_volume(&sig_info.signature).await? {
108                total_sample_volume += volume;
109                sample_count += 1;
110            }
111        }
112        if sample_count == 0 {
113            return Ok(0);
114        }
115        let avg_tx_volume = total_sample_volume / sample_count;
116        let estimated_daily_tx_count = signatures.len().min(1000); // 保守估计
117        Ok(avg_tx_volume * estimated_daily_tx_count as u64)
118    }
119
120    /// Estimates volume for a single transaction using multiple approaches.
121    ///
122    /// # Params
123    /// signature - The transaction signature to analyze
124    ///
125    /// # Returns
126    /// Returns estimated volume if successful, None if transaction cannot be analyzed
127    ///
128    /// # Example
129    /// ```no_run
130    /// use orca_client::OrcaClient;
131    ///
132    /// tokio_test::block_on(async {
133    /// let client = OrcaClient::new();
134    /// let volume = client.estimate_single_tx_volume("SIGNATURE_HERE").await.unwrap();
135    /// println!("Estimated transaction volume: {:?}", volume);
136    /// });
137    /// ```
138    async fn estimate_single_tx_volume(&self, signature: &str) -> OrcaResult<Option<u64>> {
139        let client = self
140            .solana
141            .client
142            .as_ref()
143            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
144        let signature = Signature::from_str(signature)
145            .map_err(|e| OrcaError::Error(format!("Invalid signature: {}", e)))?;
146        let transaction = client
147            .get_transaction_with_config(
148                &signature,
149                solana_client::rpc_config::RpcTransactionConfig {
150                    encoding: Some(UiTransactionEncoding::JsonParsed),
151                    commitment: Some(CommitmentConfig::confirmed()),
152                    max_supported_transaction_version: Some(0),
153                },
154            )
155            .await;
156        match transaction {
157            Ok(tx_response) => {
158                if let Some(meta) = &tx_response.transaction.meta {
159                    let fee = meta.fee;
160                    let estimated_volume = (fee as f64 / 0.003) as u64;
161                    return Ok(Some(estimated_volume));
162                }
163                if let Some(logs) = &tx_response
164                    .transaction
165                    .meta
166                    .and_then(|m| Some(m.log_messages))
167                {
168                    for log in logs.clone().unwrap() {
169                        if log.contains("swap") || log.contains("amount") || log.contains("Swap") {
170                            if let Some(amount) = Self::extract_amount_from_log(&log) {
171                                return Ok(Some(amount));
172                            }
173                        }
174                    }
175                }
176
177                Ok(None)
178            }
179            Err(e) => {
180                log::debug!("Failed to get transaction {}: {}", signature, e);
181                Ok(None)
182            }
183        }
184    }
185
186    /// Extracts numerical amounts from transaction log messages.
187    ///
188    /// # Params
189    /// log - The log message to parse
190    ///
191    /// # Returns
192    /// Returns the extracted amount if found, None otherwise
193    ///
194    /// # Example
195    /// ```
196    /// use orca_client::OrcaClient;
197    ///
198    /// let amount = OrcaClient::extract_amount_from_log("amount: 1500000");
199    /// assert_eq!(amount, Some(1500000));
200    /// ```
201    fn extract_amount_from_log(log: &str) -> Option<u64> {
202        let words: Vec<&str> = log
203            .split(|c: char| c.is_whitespace() || c == ':' || c == '=' || c == ',')
204            .collect();
205        for (i, word) in words.iter().enumerate() {
206            let lower_word = word.to_lowercase();
207            if lower_word.contains("amount")
208                || lower_word.contains("input")
209                || lower_word.contains("output")
210                || lower_word.contains("swap")
211                || lower_word.contains("transfer")
212            {
213                for j in (i + 1)..words.len().min(i + 4) {
214                    if let Some(amount) = Self::parse_possible_number(words[j]) {
215                        if amount > 100 {
216                            return Some(amount);
217                        }
218                    }
219                }
220            }
221            if let Some(amount) = Self::parse_possible_number(word) {
222                if amount > 1000 && amount < 1_000_000_000 {
223                    return Some(amount);
224                }
225            }
226        }
227        None
228    }
229
230    /// Parses numeric values from strings, filtering out non-digit characters.
231    ///
232    /// # Params
233    /// s - String that may contain a number
234    ///
235    /// # Returns
236    /// Returns the parsed number if successful, None otherwise
237    ///
238    /// # Example
239    /// ```
240    /// use orca_client::OrcaClient;
241    ///
242    /// let number = OrcaClient::parse_possible_number("123abc");
243    /// assert_eq!(number, Some(123));
244    ///
245    /// let invalid = OrcaClient::parse_possible_number("abc");
246    /// assert_eq!(invalid, None);
247    /// ```
248    fn parse_possible_number(s: &str) -> Option<u64> {
249        let cleaned: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
250        if !cleaned.is_empty() {
251            cleaned.parse::<u64>().ok()
252        } else {
253            None
254        }
255    }
256
257    /// Calculates a comprehensive health score for a liquidity pool.
258    ///
259    /// Uses logarithmic scaling to normalize metrics and weighted averaging for final score.
260    ///
261    /// # Params
262    /// liquidity - Total liquidity in the pool
263    /// volume - 24-hour trading volume
264    /// fee_growth - Total fee growth
265    ///
266    /// # Example
267    /// ```rust
268    /// use orca_client::OrcaClient;
269    ///
270    /// let client = OrcaClient::new();
271    /// let score = client.calculate_health_score(1_000_000, 500_000, 100_000);
272    /// assert!(score >= 0.0 && score <= 100.0);
273    /// ```
274    fn calculate_health_score(&self, liquidity: u128, volume: u64, fee_growth: u128) -> f64 {
275        let liquidity_score = (liquidity as f64 / 1e6).ln_1p().min(10.0);
276        let volume_score = (volume as f64 / 1e3).ln_1p().min(10.0);
277        let fee_score = (fee_growth as f64 / 1e6).ln_1p().min(10.0);
278        (liquidity_score * 0.5 + volume_score * 0.3 + fee_score * 0.2) * 10.0
279    }
280}
281
282#[derive(Debug, Clone)]
283pub struct PoolHealth {
284    pub liquidity: u128,
285    pub volume_24h: u64,
286    pub fee_growth: u128,
287    pub health_score: f64,
288}