kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
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
//! Price oracle module for external price data
//!
//! This module provides interfaces and implementations for fetching external price data,
//! particularly BTC/USD prices from various sources.

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use rust_decimal::prelude::*;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

use crate::error::{CoreError, Result};

/// Price data from an oracle source
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceData {
    /// Symbol (e.g., "BTC/USD")
    pub symbol: String,
    /// Price value
    pub price: Decimal,
    /// When the price was fetched
    pub timestamp: DateTime<Utc>,
    /// Source of the price (e.g., "coinbase", "binance")
    pub source: String,
    /// Confidence/reliability score (0.0 to 1.0)
    pub confidence: Decimal,
}

impl PriceData {
    /// Create a new price data point
    pub fn new(symbol: String, price: Decimal, source: String) -> Self {
        Self {
            symbol,
            price,
            timestamp: Utc::now(),
            source,
            confidence: dec!(1.0),
        }
    }

    /// Check if price data is stale (older than threshold)
    pub fn is_stale(&self, max_age_seconds: i64) -> bool {
        let age = Utc::now().signed_duration_since(self.timestamp);
        age.num_seconds() > max_age_seconds
    }

    /// Get age in seconds
    pub fn age_seconds(&self) -> i64 {
        Utc::now()
            .signed_duration_since(self.timestamp)
            .num_seconds()
    }
}

/// Aggregated price from multiple sources
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregatedPrice {
    /// Symbol (e.g., "BTC/USD")
    pub symbol: String,
    /// Median price from all sources
    pub median_price: Decimal,
    /// Mean (average) price from all sources
    pub mean_price: Decimal,
    /// Minimum price from all sources
    pub min_price: Decimal,
    /// Maximum price from all sources
    pub max_price: Decimal,
    /// Standard deviation of prices
    pub std_dev: Decimal,
    /// Number of sources used
    pub num_sources: usize,
    /// Individual source prices
    pub sources: Vec<PriceData>,
    /// When aggregation was performed
    pub aggregated_at: DateTime<Utc>,
}

impl AggregatedPrice {
    /// Create aggregated price from multiple sources
    pub fn from_sources(symbol: String, mut sources: Vec<PriceData>) -> Result<Self> {
        if sources.is_empty() {
            return Err(CoreError::Validation(
                "Cannot aggregate from empty sources".to_string(),
            ));
        }

        sources.sort_by(|a, b| a.price.cmp(&b.price));
        let prices: Vec<Decimal> = sources.iter().map(|s| s.price).collect();

        let median_price = if prices.len() % 2 == 0 {
            let mid = prices.len() / 2;
            (prices[mid - 1] + prices[mid]) / dec!(2)
        } else {
            prices[prices.len() / 2]
        };

        let sum: Decimal = prices.iter().sum();
        let mean_price = sum / Decimal::from(prices.len());

        let min_price = *prices.first().unwrap();
        let max_price = *prices.last().unwrap();

        // Calculate standard deviation
        let variance: Decimal = prices
            .iter()
            .map(|p| (*p - mean_price) * (*p - mean_price))
            .sum::<Decimal>()
            / Decimal::from(prices.len());
        let std_dev = variance.sqrt().unwrap_or(dec!(0));

        Ok(Self {
            symbol,
            median_price,
            mean_price,
            min_price,
            max_price,
            std_dev,
            num_sources: sources.len(),
            sources,
            aggregated_at: Utc::now(),
        })
    }

    /// Get price spread (max - min) as percentage of median
    pub fn spread_percentage(&self) -> Decimal {
        if self.median_price.is_zero() {
            return dec!(0);
        }
        ((self.max_price - self.min_price) / self.median_price) * dec!(100)
    }

    /// Check if spread is within acceptable threshold
    pub fn is_spread_acceptable(&self, max_spread_pct: Decimal) -> bool {
        self.spread_percentage() <= max_spread_pct
    }

    /// Get coefficient of variation (std_dev / mean)
    pub fn coefficient_of_variation(&self) -> Decimal {
        if self.mean_price.is_zero() {
            return dec!(0);
        }
        self.std_dev / self.mean_price
    }
}

/// Price oracle trait for fetching external prices
#[async_trait::async_trait]
pub trait PriceOracle: Send + Sync {
    /// Get the name of this oracle source
    fn source_name(&self) -> &str;

    /// Fetch current price for a symbol
    async fn fetch_price(&self, symbol: &str) -> Result<PriceData>;

    /// Check if this oracle supports a symbol
    fn supports_symbol(&self, symbol: &str) -> bool;
}

/// Mock price oracle for testing
pub struct MockPriceOracle {
    name: String,
    prices: HashMap<String, Decimal>,
}

impl MockPriceOracle {
    /// Create a new mock oracle
    pub fn new(name: String) -> Self {
        Self {
            name,
            prices: HashMap::new(),
        }
    }

    /// Set a mock price for a symbol
    pub fn set_price(&mut self, symbol: String, price: Decimal) {
        self.prices.insert(symbol, price);
    }
}

#[async_trait::async_trait]
impl PriceOracle for MockPriceOracle {
    fn source_name(&self) -> &str {
        &self.name
    }

    async fn fetch_price(&self, symbol: &str) -> Result<PriceData> {
        self.prices
            .get(symbol)
            .map(|&price| PriceData::new(symbol.to_string(), price, self.name.clone()))
            .ok_or_else(|| CoreError::NotFound(format!("Price not found for {}", symbol)))
    }

    fn supports_symbol(&self, symbol: &str) -> bool {
        self.prices.contains_key(symbol)
    }
}

/// Price oracle aggregator that combines multiple oracles
pub struct OracleAggregator {
    oracles: Vec<Box<dyn PriceOracle>>,
    max_age_seconds: i64,
    max_spread_pct: Decimal,
}

impl OracleAggregator {
    /// Create a new aggregator
    pub fn new() -> Self {
        Self {
            oracles: Vec::new(),
            max_age_seconds: 300,      // 5 minutes
            max_spread_pct: dec!(5.0), // 5% max spread
        }
    }

    /// Add an oracle source
    pub fn add_oracle(&mut self, oracle: Box<dyn PriceOracle>) {
        self.oracles.push(oracle);
    }

    /// Set maximum age for price data
    pub fn with_max_age(mut self, seconds: i64) -> Self {
        self.max_age_seconds = seconds;
        self
    }

    /// Set maximum acceptable spread
    pub fn with_max_spread(mut self, spread_pct: Decimal) -> Self {
        self.max_spread_pct = spread_pct;
        self
    }

    /// Fetch aggregated price from all oracles
    pub async fn fetch_aggregated_price(&self, symbol: &str) -> Result<AggregatedPrice> {
        if self.oracles.is_empty() {
            return Err(CoreError::Configuration(
                "No oracles configured".to_string(),
            ));
        }

        let mut prices = Vec::new();
        let mut errors = Vec::new();

        for oracle in &self.oracles {
            if !oracle.supports_symbol(symbol) {
                continue;
            }

            match oracle.fetch_price(symbol).await {
                Ok(price_data) => {
                    if !price_data.is_stale(self.max_age_seconds) {
                        prices.push(price_data);
                    }
                }
                Err(e) => {
                    errors.push((oracle.source_name(), e));
                }
            }
        }

        if prices.is_empty() {
            return Err(CoreError::NotFound(format!(
                "No valid price data available for {} (errors: {})",
                symbol,
                errors.len()
            )));
        }

        let aggregated = AggregatedPrice::from_sources(symbol.to_string(), prices)?;

        // Check if spread is acceptable
        if !aggregated.is_spread_acceptable(self.max_spread_pct) {
            tracing::warn!(
                symbol = symbol,
                spread_pct = %aggregated.spread_percentage(),
                max_spread_pct = %self.max_spread_pct,
                "Price spread exceeds threshold"
            );
        }

        Ok(aggregated)
    }

    /// Get number of configured oracles
    pub fn oracle_count(&self) -> usize {
        self.oracles.len()
    }
}

impl Default for OracleAggregator {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for OracleAggregator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OracleAggregator")
            .field("oracle_count", &self.oracles.len())
            .field("max_age_seconds", &self.max_age_seconds)
            .field("max_spread_pct", &self.max_spread_pct)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_price_data_creation() {
        let price = PriceData::new("BTC/USD".to_string(), dec!(50000), "test".to_string());
        assert_eq!(price.symbol, "BTC/USD");
        assert_eq!(price.price, dec!(50000));
        assert_eq!(price.source, "test");
        assert_eq!(price.confidence, dec!(1.0));
    }

    #[test]
    fn test_price_data_staleness() {
        let price = PriceData::new("BTC/USD".to_string(), dec!(50000), "test".to_string());
        assert!(!price.is_stale(3600)); // Not stale after 1 hour
        assert!(price.age_seconds() >= 0);
    }

    #[test]
    fn test_aggregated_price_from_sources() {
        let sources = vec![
            PriceData::new("BTC/USD".to_string(), dec!(50000), "source1".to_string()),
            PriceData::new("BTC/USD".to_string(), dec!(50100), "source2".to_string()),
            PriceData::new("BTC/USD".to_string(), dec!(49900), "source3".to_string()),
        ];

        let aggregated = AggregatedPrice::from_sources("BTC/USD".to_string(), sources).unwrap();
        assert_eq!(aggregated.median_price, dec!(50000));
        assert_eq!(aggregated.min_price, dec!(49900));
        assert_eq!(aggregated.max_price, dec!(50100));
        assert_eq!(aggregated.num_sources, 3);
    }

    #[test]
    fn test_aggregated_price_spread() {
        let sources = vec![
            PriceData::new("BTC/USD".to_string(), dec!(50000), "source1".to_string()),
            PriceData::new("BTC/USD".to_string(), dec!(52000), "source2".to_string()),
        ];

        let aggregated = AggregatedPrice::from_sources("BTC/USD".to_string(), sources).unwrap();
        let spread = aggregated.spread_percentage();
        assert!(spread > dec!(3.8) && spread < dec!(4.0)); // ~3.9%
    }

    #[test]
    fn test_aggregated_price_empty_sources() {
        let result = AggregatedPrice::from_sources("BTC/USD".to_string(), vec![]);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_mock_oracle() {
        let mut oracle = MockPriceOracle::new("test".to_string());
        oracle.set_price("BTC/USD".to_string(), dec!(50000));

        let price = oracle.fetch_price("BTC/USD").await.unwrap();
        assert_eq!(price.price, dec!(50000));
        assert_eq!(price.source, "test");

        assert!(oracle.supports_symbol("BTC/USD"));
        assert!(!oracle.supports_symbol("ETH/USD"));
    }

    #[tokio::test]
    async fn test_oracle_aggregator() {
        let mut oracle1 = MockPriceOracle::new("oracle1".to_string());
        oracle1.set_price("BTC/USD".to_string(), dec!(50000));

        let mut oracle2 = MockPriceOracle::new("oracle2".to_string());
        oracle2.set_price("BTC/USD".to_string(), dec!(50100));

        let mut aggregator = OracleAggregator::new();
        aggregator.add_oracle(Box::new(oracle1));
        aggregator.add_oracle(Box::new(oracle2));

        let aggregated = aggregator.fetch_aggregated_price("BTC/USD").await.unwrap();
        assert_eq!(aggregated.num_sources, 2);
        assert!(aggregated.median_price > dec!(49000));
        assert!(aggregated.median_price < dec!(51000));
    }

    #[tokio::test]
    async fn test_oracle_aggregator_no_oracles() {
        let aggregator = OracleAggregator::new();
        let result = aggregator.fetch_aggregated_price("BTC/USD").await;
        assert!(result.is_err());
    }

    #[test]
    fn test_oracle_aggregator_configuration() {
        let aggregator = OracleAggregator::new()
            .with_max_age(600)
            .with_max_spread(dec!(10.0));

        assert_eq!(aggregator.max_age_seconds, 600);
        assert_eq!(aggregator.max_spread_pct, dec!(10.0));
    }
}