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 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 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 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 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); Ok(avg_tx_volume * estimated_daily_tx_count as u64)
118 }
119
120 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 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 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 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}