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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Collateral management system
//!
//! This module provides collateral management functionality including:
//! - Multi-collateral support
//! - Collateral valuation
//! - Haircut calculations
//! - Cross-collateralization

use crate::error::{CoreError, Result};
use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Collateral asset configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollateralConfig {
    /// Asset symbol
    pub symbol: String,

    /// Collateral factor (0.0 to 1.0)
    /// e.g., 0.8 means $100 of collateral can support $80 of borrowing
    pub collateral_factor: Decimal,

    /// Liquidation threshold (0.0 to 1.0)
    /// e.g., 0.85 means liquidation starts when debt/collateral > 0.85
    pub liquidation_threshold: Decimal,

    /// Haircut percentage (reduction in value for risk)
    /// e.g., 0.1 means 10% haircut
    pub haircut: Decimal,

    /// Minimum deposit amount
    pub min_deposit: Decimal,

    /// Maximum single deposit
    pub max_deposit: Option<Decimal>,

    /// Is this asset enabled as collateral
    pub enabled: bool,

    /// Asset category
    pub category: AssetCategory,

    /// Updated timestamp
    pub updated_at: DateTime<Utc>,
}

/// Asset category for risk classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssetCategory {
    /// Stablecoins (USDT, USDC, etc.)
    Stablecoin,

    /// Major cryptocurrencies (BTC, ETH)
    MajorCrypto,

    /// Altcoins
    Altcoin,

    /// Platform tokens
    PlatformToken,

    /// LP tokens
    LiquidityToken,
}

impl AssetCategory {
    /// Get default collateral factor for category
    pub fn default_collateral_factor(&self) -> Decimal {
        match self {
            AssetCategory::Stablecoin => dec!(0.95),
            AssetCategory::MajorCrypto => dec!(0.80),
            AssetCategory::Altcoin => dec!(0.60),
            AssetCategory::PlatformToken => dec!(0.70),
            AssetCategory::LiquidityToken => dec!(0.50),
        }
    }

    /// Get default liquidation threshold for category
    pub fn default_liquidation_threshold(&self) -> Decimal {
        match self {
            AssetCategory::Stablecoin => dec!(0.98),
            AssetCategory::MajorCrypto => dec!(0.85),
            AssetCategory::Altcoin => dec!(0.75),
            AssetCategory::PlatformToken => dec!(0.80),
            AssetCategory::LiquidityToken => dec!(0.70),
        }
    }

    /// Get default haircut for category
    pub fn default_haircut(&self) -> Decimal {
        match self {
            AssetCategory::Stablecoin => dec!(0.02),     // 2%
            AssetCategory::MajorCrypto => dec!(0.10),    // 10%
            AssetCategory::Altcoin => dec!(0.20),        // 20%
            AssetCategory::PlatformToken => dec!(0.15),  // 15%
            AssetCategory::LiquidityToken => dec!(0.25), // 25%
        }
    }
}

impl CollateralConfig {
    /// Create new collateral config with defaults
    pub fn new(symbol: String, category: AssetCategory) -> Self {
        Self {
            symbol,
            collateral_factor: category.default_collateral_factor(),
            liquidation_threshold: category.default_liquidation_threshold(),
            haircut: category.default_haircut(),
            min_deposit: dec!(10),
            max_deposit: None,
            enabled: true,
            category,
            updated_at: Utc::now(),
        }
    }

    /// Calculate effective value after haircut
    pub fn effective_value(&self, amount: Decimal, price: Decimal) -> Decimal {
        let gross_value = amount * price;
        gross_value * (Decimal::ONE - self.haircut)
    }

    /// Calculate borrowing power
    pub fn borrowing_power(&self, amount: Decimal, price: Decimal) -> Decimal {
        let effective_value = self.effective_value(amount, price);
        effective_value * self.collateral_factor
    }
}

/// Collateral deposit
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollateralAssetDeposit {
    /// Deposit ID
    pub deposit_id: String,

    /// User ID
    pub user_id: String,

    /// Asset symbol
    pub symbol: String,

    /// Amount deposited
    pub amount: Decimal,

    /// Price at deposit (USD)
    pub deposit_price: Decimal,

    /// Current price (USD)
    pub current_price: Decimal,

    /// Is this deposit locked
    pub locked: bool,

    /// Lock expiry (if locked)
    pub lock_expiry: Option<DateTime<Utc>>,

    /// Deposited timestamp
    pub deposited_at: DateTime<Utc>,
}

impl CollateralAssetDeposit {
    /// Create new collateral deposit
    pub fn new(
        deposit_id: String,
        user_id: String,
        symbol: String,
        amount: Decimal,
        price: Decimal,
    ) -> Self {
        Self {
            deposit_id,
            user_id,
            symbol,
            amount,
            deposit_price: price,
            current_price: price,
            locked: false,
            lock_expiry: None,
            deposited_at: Utc::now(),
        }
    }

    /// Get current value in USD
    pub fn current_value(&self) -> Decimal {
        self.amount * self.current_price
    }

    /// Get PnL since deposit
    pub fn unrealized_pnl(&self) -> Decimal {
        self.amount * (self.current_price - self.deposit_price)
    }

    /// Update current price
    pub fn update_price(&mut self, price: Decimal) {
        self.current_price = price;
    }

    /// Check if deposit is locked
    pub fn is_locked(&self) -> bool {
        if !self.locked {
            return false;
        }

        if let Some(expiry) = self.lock_expiry {
            Utc::now() < expiry
        } else {
            true
        }
    }
}

/// Collateral portfolio for a user
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollateralPortfolio {
    /// User ID
    pub user_id: String,

    /// All deposits
    pub deposits: Vec<CollateralAssetDeposit>,

    /// Total borrowed amount (in USD)
    pub total_borrowed: Decimal,

    /// Updated timestamp
    pub updated_at: DateTime<Utc>,
}

impl CollateralPortfolio {
    /// Create new collateral portfolio
    pub fn new(user_id: String) -> Self {
        Self {
            user_id,
            deposits: Vec::new(),
            total_borrowed: Decimal::ZERO,
            updated_at: Utc::now(),
        }
    }

    /// Add collateral deposit
    pub fn add_deposit(&mut self, deposit: CollateralAssetDeposit) {
        self.deposits.push(deposit);
        self.updated_at = Utc::now();
    }

    /// Remove collateral deposit
    pub fn remove_deposit(&mut self, deposit_id: &str) -> Result<CollateralAssetDeposit> {
        let idx = self
            .deposits
            .iter()
            .position(|d| d.deposit_id == deposit_id)
            .ok_or_else(|| CoreError::NotFound(format!("Deposit {} not found", deposit_id)))?;

        let deposit = self.deposits.remove(idx);

        if deposit.is_locked() {
            return Err(CoreError::Validation(
                "Cannot withdraw locked collateral".to_string(),
            ));
        }

        self.updated_at = Utc::now();
        Ok(deposit)
    }

    /// Calculate total collateral value
    pub fn total_collateral_value(&self) -> Decimal {
        self.deposits.iter().map(|d| d.current_value()).sum()
    }

    /// Calculate effective collateral value (with configs)
    pub fn effective_collateral_value(
        &self,
        configs: &HashMap<String, CollateralConfig>,
    ) -> Decimal {
        self.deposits
            .iter()
            .filter_map(|d| {
                configs
                    .get(&d.symbol)
                    .map(|config| config.effective_value(d.amount, d.current_price))
            })
            .sum()
    }

    /// Calculate total borrowing power
    pub fn total_borrowing_power(&self, configs: &HashMap<String, CollateralConfig>) -> Decimal {
        self.deposits
            .iter()
            .filter_map(|d| {
                configs
                    .get(&d.symbol)
                    .map(|config| config.borrowing_power(d.amount, d.current_price))
            })
            .sum()
    }

    /// Calculate available borrowing power
    pub fn available_borrowing_power(
        &self,
        configs: &HashMap<String, CollateralConfig>,
    ) -> Decimal {
        let total_power = self.total_borrowing_power(configs);
        (total_power - self.total_borrowed).max(Decimal::ZERO)
    }

    /// Calculate health factor
    /// Health factor = (collateral value * liquidation threshold) / total borrowed
    /// < 1.0 means account is subject to liquidation
    pub fn health_factor(&self, configs: &HashMap<String, CollateralConfig>) -> Decimal {
        if self.total_borrowed.is_zero() {
            return Decimal::MAX;
        }

        let liquidation_value: Decimal = self
            .deposits
            .iter()
            .filter_map(|d| {
                configs.get(&d.symbol).map(|config| {
                    let value = d.current_value();
                    value * config.liquidation_threshold
                })
            })
            .sum();

        liquidation_value / self.total_borrowed
    }

    /// Check if portfolio is healthy
    pub fn is_healthy(&self, configs: &HashMap<String, CollateralConfig>) -> bool {
        self.health_factor(configs) > Decimal::ONE
    }

    /// Update deposit prices
    pub fn update_prices(&mut self, prices: &HashMap<String, Decimal>) {
        for deposit in &mut self.deposits {
            if let Some(&price) = prices.get(&deposit.symbol) {
                deposit.update_price(price);
            }
        }
        self.updated_at = Utc::now();
    }

    /// Add borrowing
    pub fn add_borrowing(&mut self, amount: Decimal) {
        self.total_borrowed += amount;
        self.updated_at = Utc::now();
    }

    /// Repay borrowing
    pub fn repay_borrowing(&mut self, amount: Decimal) {
        self.total_borrowed = (self.total_borrowed - amount).max(Decimal::ZERO);
        self.updated_at = Utc::now();
    }

    /// Get collateral breakdown by asset
    pub fn breakdown(&self) -> HashMap<String, Decimal> {
        let mut breakdown = HashMap::new();

        for deposit in &self.deposits {
            *breakdown
                .entry(deposit.symbol.clone())
                .or_insert(Decimal::ZERO) += deposit.current_value();
        }

        breakdown
    }
}

/// Collateral manager
pub struct CollateralManager {
    /// Collateral configurations
    configs: HashMap<String, CollateralConfig>,

    /// User portfolios
    portfolios: HashMap<String, CollateralPortfolio>,
}

impl CollateralManager {
    /// Create new collateral manager
    pub fn new() -> Self {
        Self {
            configs: HashMap::new(),
            portfolios: HashMap::new(),
        }
    }

    /// Add collateral config
    pub fn add_config(&mut self, config: CollateralConfig) {
        self.configs.insert(config.symbol.clone(), config);
    }

    /// Get collateral config
    pub fn get_config(&self, symbol: &str) -> Option<&CollateralConfig> {
        self.configs.get(symbol)
    }

    /// Get or create user portfolio
    pub fn get_or_create_portfolio(&mut self, user_id: &str) -> &mut CollateralPortfolio {
        self.portfolios
            .entry(user_id.to_string())
            .or_insert_with(|| CollateralPortfolio::new(user_id.to_string()))
    }

    /// Get user portfolio
    pub fn get_portfolio(&self, user_id: &str) -> Option<&CollateralPortfolio> {
        self.portfolios.get(user_id)
    }

    /// Deposit collateral
    pub fn deposit_collateral(&mut self, deposit: CollateralAssetDeposit) -> Result<()> {
        // Validate asset is enabled
        let config = self.configs.get(&deposit.symbol).ok_or_else(|| {
            CoreError::NotFound(format!(
                "Collateral config for {} not found",
                deposit.symbol
            ))
        })?;

        if !config.enabled {
            return Err(CoreError::Validation(format!(
                "{} is not enabled as collateral",
                deposit.symbol
            )));
        }

        // Validate amount
        if deposit.amount < config.min_deposit {
            return Err(CoreError::Validation(format!(
                "Deposit amount {} below minimum {}",
                deposit.amount, config.min_deposit
            )));
        }

        if let Some(max) = config.max_deposit {
            if deposit.amount > max {
                return Err(CoreError::Validation(format!(
                    "Deposit amount {} exceeds maximum {}",
                    deposit.amount, max
                )));
            }
        }

        let portfolio = self.get_or_create_portfolio(&deposit.user_id);
        portfolio.add_deposit(deposit);

        Ok(())
    }

    /// Withdraw collateral
    pub fn withdraw_collateral(
        &mut self,
        user_id: &str,
        deposit_id: &str,
    ) -> Result<CollateralAssetDeposit> {
        let portfolio = self
            .portfolios
            .get_mut(user_id)
            .ok_or_else(|| CoreError::NotFound(format!("Portfolio for {} not found", user_id)))?;

        let deposit = portfolio.remove_deposit(deposit_id)?;

        // Check if withdrawal would make portfolio unhealthy
        if !portfolio.is_healthy(&self.configs) {
            // Restore deposit
            portfolio.add_deposit(deposit.clone());
            return Err(CoreError::Validation(
                "Withdrawal would make portfolio unhealthy".to_string(),
            ));
        }

        Ok(deposit)
    }

    /// Update all prices
    pub fn update_prices(&mut self, prices: &HashMap<String, Decimal>) {
        for portfolio in self.portfolios.values_mut() {
            portfolio.update_prices(prices);
        }
    }

    /// Get unhealthy portfolios
    pub fn get_unhealthy_portfolios(&self) -> Vec<String> {
        self.portfolios
            .iter()
            .filter(|(_, portfolio)| !portfolio.is_healthy(&self.configs))
            .map(|(user_id, _)| user_id.clone())
            .collect()
    }

    /// Calculate total value locked (TVL)
    pub fn total_value_locked(&self) -> Decimal {
        self.portfolios
            .values()
            .map(|p| p.total_collateral_value())
            .sum()
    }
}

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

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

    #[test]
    fn test_asset_category_defaults() {
        assert_eq!(
            AssetCategory::Stablecoin.default_collateral_factor(),
            dec!(0.95)
        );
        assert_eq!(
            AssetCategory::MajorCrypto.default_collateral_factor(),
            dec!(0.80)
        );
    }

    #[test]
    fn test_collateral_config() {
        let config = CollateralConfig::new("BTC".to_string(), AssetCategory::MajorCrypto);

        let effective_value = config.effective_value(dec!(1), dec!(50000));
        assert_eq!(effective_value, dec!(45000)); // 50000 * (1 - 0.1)

        let borrowing_power = config.borrowing_power(dec!(1), dec!(50000));
        assert_eq!(borrowing_power, dec!(36000)); // 45000 * 0.8
    }

    #[test]
    fn test_collateral_deposit() {
        let deposit = CollateralAssetDeposit::new(
            "dep1".to_string(),
            "user1".to_string(),
            "BTC".to_string(),
            dec!(10),
            dec!(50000),
        );

        assert_eq!(deposit.current_value(), dec!(500000));
        assert_eq!(deposit.unrealized_pnl(), Decimal::ZERO);
    }

    #[test]
    fn test_collateral_portfolio() {
        let mut portfolio = CollateralPortfolio::new("user1".to_string());

        let deposit = CollateralAssetDeposit::new(
            "dep1".to_string(),
            "user1".to_string(),
            "BTC".to_string(),
            dec!(1),
            dec!(50000),
        );

        portfolio.add_deposit(deposit);
        assert_eq!(portfolio.total_collateral_value(), dec!(50000));
    }

    #[test]
    fn test_health_factor() {
        let mut portfolio = CollateralPortfolio::new("user1".to_string());

        let deposit = CollateralAssetDeposit::new(
            "dep1".to_string(),
            "user1".to_string(),
            "BTC".to_string(),
            dec!(1),
            dec!(50000),
        );

        portfolio.add_deposit(deposit);
        portfolio.add_borrowing(dec!(30000));

        let mut configs = HashMap::new();
        configs.insert(
            "BTC".to_string(),
            CollateralConfig::new("BTC".to_string(), AssetCategory::MajorCrypto),
        );

        let health = portfolio.health_factor(&configs);
        assert!(health > Decimal::ONE);
        assert!(portfolio.is_healthy(&configs));
    }

    #[test]
    fn test_collateral_manager() {
        let mut manager = CollateralManager::new();

        manager.add_config(CollateralConfig::new(
            "BTC".to_string(),
            AssetCategory::MajorCrypto,
        ));

        let deposit = CollateralAssetDeposit::new(
            "dep1".to_string(),
            "user1".to_string(),
            "BTC".to_string(),
            dec!(10), // Meets minimum deposit requirement
            dec!(50000),
        );

        manager.deposit_collateral(deposit).unwrap();

        let portfolio = manager.get_portfolio("user1").unwrap();
        assert_eq!(portfolio.deposits.len(), 1);
    }
}