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
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
//! Enhanced trade validation module
//!
//! This module provides comprehensive validation for trading operations to ensure:
//! - Price sanity checks
//! - Amount validation
//! - Slippage protection
//! - Market manipulation detection
//! - Risk limit enforcement

use crate::error::{CoreError, Result};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};

/// Trade validation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeValidationConfig {
    /// Maximum price deviation from oracle price (as percentage)
    pub max_price_deviation: Decimal,

    /// Minimum order amount
    pub min_order_amount: Decimal,

    /// Maximum order amount
    pub max_order_amount: Decimal,

    /// Maximum slippage tolerance (as percentage)
    pub max_slippage: Decimal,

    /// Maximum price impact allowed (as percentage)
    pub max_price_impact: Decimal,

    /// Minimum time between orders from same user (seconds)
    pub min_order_interval_secs: i64,

    /// Maximum number of orders per user per hour
    pub max_orders_per_hour: usize,
}

impl Default for TradeValidationConfig {
    fn default() -> Self {
        Self {
            max_price_deviation: dec!(0.10), // 10%
            min_order_amount: dec!(0.0001),  // 0.0001 BTC
            max_order_amount: dec!(100.0),   // 100 BTC
            max_slippage: dec!(0.05),        // 5%
            max_price_impact: dec!(0.15),    // 15%
            min_order_interval_secs: 1,      // 1 second
            max_orders_per_hour: 1000,       // 1000 orders/hour
        }
    }
}

/// Trade validation result
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationResult {
    /// Trade is valid
    Valid,

    /// Trade is rejected with reason
    Rejected(String),

    /// Trade requires additional confirmation
    RequiresConfirmation(String),
}

/// Trade validator
pub struct TradeValidator {
    config: TradeValidationConfig,
}

impl TradeValidator {
    /// Create a new trade validator with default config
    pub fn new() -> Self {
        Self {
            config: TradeValidationConfig::default(),
        }
    }

    /// Create a new trade validator with custom config
    pub fn with_config(config: TradeValidationConfig) -> Self {
        Self { config }
    }

    /// Validate order amount
    pub fn validate_amount(&self, amount: Decimal) -> ValidationResult {
        if amount <= Decimal::ZERO {
            return ValidationResult::Rejected("Amount must be positive".to_string());
        }

        if amount < self.config.min_order_amount {
            return ValidationResult::Rejected(format!(
                "Amount {} is below minimum {}",
                amount, self.config.min_order_amount
            ));
        }

        if amount > self.config.max_order_amount {
            return ValidationResult::Rejected(format!(
                "Amount {} exceeds maximum {}",
                amount, self.config.max_order_amount
            ));
        }

        ValidationResult::Valid
    }

    /// Validate price against oracle price
    pub fn validate_price(&self, price: Decimal, oracle_price: Decimal) -> ValidationResult {
        if price <= Decimal::ZERO {
            return ValidationResult::Rejected("Price must be positive".to_string());
        }

        if oracle_price <= Decimal::ZERO {
            return ValidationResult::RequiresConfirmation(
                "Oracle price unavailable, manual review required".to_string(),
            );
        }

        let deviation = ((price - oracle_price) / oracle_price).abs();

        if deviation > self.config.max_price_deviation {
            return ValidationResult::Rejected(format!(
                "Price deviation {:.2}% exceeds maximum {:.2}%",
                deviation * dec!(100),
                self.config.max_price_deviation * dec!(100)
            ));
        }

        ValidationResult::Valid
    }

    /// Validate slippage
    pub fn validate_slippage(
        &self,
        expected_price: Decimal,
        execution_price: Decimal,
    ) -> ValidationResult {
        if expected_price <= Decimal::ZERO || execution_price <= Decimal::ZERO {
            return ValidationResult::Rejected("Invalid price values".to_string());
        }

        let slippage = ((execution_price - expected_price) / expected_price).abs();

        if slippage > self.config.max_slippage {
            return ValidationResult::Rejected(format!(
                "Slippage {:.2}% exceeds maximum {:.2}%",
                slippage * dec!(100),
                self.config.max_slippage * dec!(100)
            ));
        }

        ValidationResult::Valid
    }

    /// Validate price impact
    pub fn validate_price_impact(&self, price_impact: Decimal) -> ValidationResult {
        if price_impact < Decimal::ZERO {
            return ValidationResult::Rejected("Price impact cannot be negative".to_string());
        }

        if price_impact > self.config.max_price_impact {
            return ValidationResult::RequiresConfirmation(format!(
                "High price impact {:.2}% detected (max {:.2}%). Confirm to proceed.",
                price_impact * dec!(100),
                self.config.max_price_impact * dec!(100)
            ));
        }

        ValidationResult::Valid
    }

    /// Validate order frequency
    pub fn validate_order_frequency(
        &self,
        seconds_since_last_order: i64,
        orders_in_last_hour: usize,
    ) -> ValidationResult {
        if seconds_since_last_order < self.config.min_order_interval_secs {
            return ValidationResult::Rejected(format!(
                "Orders too frequent. Wait {} seconds between orders",
                self.config.min_order_interval_secs - seconds_since_last_order
            ));
        }

        if orders_in_last_hour >= self.config.max_orders_per_hour {
            return ValidationResult::Rejected(format!(
                "Order limit exceeded. Maximum {} orders per hour",
                self.config.max_orders_per_hour
            ));
        }

        ValidationResult::Valid
    }

    /// Validate total position size
    pub fn validate_position_size(
        &self,
        new_position: Decimal,
        current_position: Decimal,
        position_limit: Decimal,
    ) -> ValidationResult {
        let total_position = current_position + new_position;

        if total_position > position_limit {
            return ValidationResult::Rejected(format!(
                "Position size {} would exceed limit {}",
                total_position, position_limit
            ));
        }

        ValidationResult::Valid
    }

    /// Comprehensive trade validation
    #[allow(clippy::too_many_arguments)]
    pub fn validate_trade(
        &self,
        amount: Decimal,
        price: Decimal,
        oracle_price: Option<Decimal>,
        expected_price: Option<Decimal>,
        price_impact: Decimal,
        current_position: Decimal,
        position_limit: Decimal,
        seconds_since_last: i64,
        orders_last_hour: usize,
    ) -> Result<()> {
        // Validate amount
        match self.validate_amount(amount) {
            ValidationResult::Valid => {}
            ValidationResult::Rejected(reason) => {
                return Err(CoreError::Validation(reason));
            }
            ValidationResult::RequiresConfirmation(reason) => {
                return Err(CoreError::Validation(reason));
            }
        }

        // Validate price if oracle price available
        if let Some(oracle) = oracle_price {
            match self.validate_price(price, oracle) {
                ValidationResult::Valid => {}
                ValidationResult::Rejected(reason) => {
                    return Err(CoreError::Validation(reason));
                }
                ValidationResult::RequiresConfirmation(_) => {
                    // Log warning but allow
                }
            }
        }

        // Validate slippage if expected price available
        if let Some(expected) = expected_price {
            match self.validate_slippage(expected, price) {
                ValidationResult::Valid => {}
                ValidationResult::Rejected(reason) => {
                    return Err(CoreError::Validation(reason));
                }
                ValidationResult::RequiresConfirmation(reason) => {
                    return Err(CoreError::Validation(reason));
                }
            }
        }

        // Validate price impact
        match self.validate_price_impact(price_impact) {
            ValidationResult::Valid => {}
            ValidationResult::Rejected(reason) => {
                return Err(CoreError::Validation(reason));
            }
            ValidationResult::RequiresConfirmation(_) => {
                // Log warning but allow
            }
        }

        // Validate position size
        match self.validate_position_size(amount, current_position, position_limit) {
            ValidationResult::Valid => {}
            ValidationResult::Rejected(reason) => {
                return Err(CoreError::Validation(reason));
            }
            ValidationResult::RequiresConfirmation(reason) => {
                return Err(CoreError::Validation(reason));
            }
        }

        // Validate order frequency
        match self.validate_order_frequency(seconds_since_last, orders_last_hour) {
            ValidationResult::Valid => {}
            ValidationResult::Rejected(reason) => {
                return Err(CoreError::Validation(reason));
            }
            ValidationResult::RequiresConfirmation(reason) => {
                return Err(CoreError::Validation(reason));
            }
        }

        Ok(())
    }
}

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

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

    #[test]
    fn test_validate_amount_valid() {
        let validator = TradeValidator::new();
        let result = validator.validate_amount(dec!(1.0));
        assert_eq!(result, ValidationResult::Valid);
    }

    #[test]
    fn test_validate_amount_too_small() {
        let validator = TradeValidator::new();
        let result = validator.validate_amount(dec!(0.00001));
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_amount_too_large() {
        let validator = TradeValidator::new();
        let result = validator.validate_amount(dec!(200.0));
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_amount_zero() {
        let validator = TradeValidator::new();
        let result = validator.validate_amount(Decimal::ZERO);
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_price_within_deviation() {
        let validator = TradeValidator::new();
        let result = validator.validate_price(dec!(105.0), dec!(100.0));
        assert_eq!(result, ValidationResult::Valid);
    }

    #[test]
    fn test_validate_price_exceeds_deviation() {
        let validator = TradeValidator::new();
        let result = validator.validate_price(dec!(115.0), dec!(100.0));
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_slippage_acceptable() {
        let validator = TradeValidator::new();
        let result = validator.validate_slippage(dec!(100.0), dec!(103.0));
        assert_eq!(result, ValidationResult::Valid);
    }

    #[test]
    fn test_validate_slippage_excessive() {
        let validator = TradeValidator::new();
        let result = validator.validate_slippage(dec!(100.0), dec!(110.0));
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_price_impact_low() {
        let validator = TradeValidator::new();
        let result = validator.validate_price_impact(dec!(0.05));
        assert_eq!(result, ValidationResult::Valid);
    }

    #[test]
    fn test_validate_price_impact_high() {
        let validator = TradeValidator::new();
        let result = validator.validate_price_impact(dec!(0.20));
        match result {
            ValidationResult::RequiresConfirmation(_) => {}
            _ => panic!("Expected confirmation required"),
        }
    }

    #[test]
    fn test_validate_order_frequency_ok() {
        let validator = TradeValidator::new();
        let result = validator.validate_order_frequency(10, 50);
        assert_eq!(result, ValidationResult::Valid);
    }

    #[test]
    fn test_validate_order_frequency_too_fast() {
        let validator = TradeValidator::new();
        let result = validator.validate_order_frequency(0, 50);
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_order_frequency_too_many() {
        let validator = TradeValidator::new();
        let result = validator.validate_order_frequency(10, 1001);
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_validate_position_size_ok() {
        let validator = TradeValidator::new();
        let result = validator.validate_position_size(dec!(10.0), dec!(5.0), dec!(20.0));
        assert_eq!(result, ValidationResult::Valid);
    }

    #[test]
    fn test_validate_position_size_exceeds_limit() {
        let validator = TradeValidator::new();
        let result = validator.validate_position_size(dec!(10.0), dec!(15.0), dec!(20.0));
        match result {
            ValidationResult::Rejected(_) => {}
            _ => panic!("Expected rejection"),
        }
    }

    #[test]
    fn test_comprehensive_validation_success() {
        let validator = TradeValidator::new();
        let result = validator.validate_trade(
            dec!(1.0),         // amount
            dec!(105.0),       // price
            Some(dec!(100.0)), // oracle_price
            Some(dec!(103.0)), // expected_price
            dec!(0.05),        // price_impact
            dec!(5.0),         // current_position
            dec!(20.0),        // position_limit
            10,                // seconds_since_last
            50,                // orders_last_hour
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_comprehensive_validation_invalid_amount() {
        let validator = TradeValidator::new();
        let result = validator.validate_trade(
            dec!(200.0),       // amount exceeds max
            dec!(105.0),       // price
            Some(dec!(100.0)), // oracle_price
            Some(dec!(103.0)), // expected_price
            dec!(0.05),        // price_impact
            dec!(5.0),         // current_position
            dec!(20.0),        // position_limit
            10,                // seconds_since_last
            50,                // orders_last_hour
        );
        assert!(result.is_err());
    }
}