governance 0.1.0

Governance and voting system for Neural Trader - proposal management, voting mechanisms, and consensus protocols
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
use crate::error::{GovernanceError, Result};
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Treasury transaction type
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TransactionType {
    Deposit,
    Withdrawal,
    Allocation,
    Fee,
    Dividend,
    Emergency,
}

/// Treasury transaction
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transaction {
    pub id: String,
    pub transaction_type: TransactionType,
    pub amount: Decimal,
    pub from: Option<String>,
    pub to: Option<String>,
    pub purpose: String,
    pub proposal_id: Option<String>,
    pub timestamp: DateTime<Utc>,
    pub approved: bool,
}

impl Transaction {
    pub fn new(
        transaction_type: TransactionType,
        amount: Decimal,
        from: Option<String>,
        to: Option<String>,
        purpose: String,
        proposal_id: Option<String>,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            transaction_type,
            amount,
            from,
            to,
            purpose,
            proposal_id,
            timestamp: Utc::now(),
            approved: false,
        }
    }
}

/// Budget allocation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BudgetAllocation {
    pub category: String,
    pub allocated: Decimal,
    pub spent: Decimal,
    pub remaining: Decimal,
    pub last_updated: DateTime<Utc>,
}

impl BudgetAllocation {
    pub fn new(category: String, allocated: Decimal) -> Self {
        Self {
            category,
            allocated,
            spent: Decimal::ZERO,
            remaining: allocated,
            last_updated: Utc::now(),
        }
    }

    pub fn spend(&mut self, amount: Decimal) -> Result<()> {
        if amount > self.remaining {
            return Err(GovernanceError::TreasuryOperationFailed(
                "Insufficient budget allocation".to_string(),
            ));
        }
        self.spent += amount;
        self.remaining -= amount;
        self.last_updated = Utc::now();
        Ok(())
    }

    pub fn increase_allocation(&mut self, amount: Decimal) {
        self.allocated += amount;
        self.remaining += amount;
        self.last_updated = Utc::now();
    }
}

/// Treasury manager
pub struct TreasuryManager {
    balance: Arc<DashMap<String, Decimal>>, // asset -> balance
    transactions: Arc<DashMap<String, Transaction>>,
    budgets: Arc<DashMap<String, BudgetAllocation>>,
    emergency_fund: Decimal,
    emergency_threshold: Decimal,
}

impl TreasuryManager {
    pub fn new(initial_balance: Decimal, emergency_threshold: Decimal) -> Self {
        let balance = Arc::new(DashMap::new());
        balance.insert("USD".to_string(), initial_balance);

        Self {
            balance,
            transactions: Arc::new(DashMap::new()),
            budgets: Arc::new(DashMap::new()),
            emergency_fund: Decimal::ZERO,
            emergency_threshold,
        }
    }

    /// Get current balance for an asset
    pub fn get_balance(&self, asset: &str) -> Decimal {
        self.balance
            .get(asset)
            .map(|r| *r.value())
            .unwrap_or(Decimal::ZERO)
    }

    /// Deposit funds
    pub fn deposit(&self, asset: &str, amount: Decimal, from: String, purpose: String) -> Result<String> {
        if amount <= Decimal::ZERO {
            return Err(GovernanceError::InvalidParameter(
                "Amount must be positive".to_string(),
            ));
        }

        // Create transaction
        let transaction = Transaction::new(
            TransactionType::Deposit,
            amount,
            Some(from),
            None,
            purpose,
            None,
        );
        let tx_id = transaction.id.clone();

        // Update balance
        self.balance
            .entry(asset.to_string())
            .and_modify(|b| *b += amount)
            .or_insert(amount);

        // Record transaction
        self.transactions.insert(tx_id.clone(), transaction);

        Ok(tx_id)
    }

    /// Withdraw funds (requires governance approval for large amounts)
    pub fn withdraw(
        &self,
        asset: &str,
        amount: Decimal,
        to: String,
        purpose: String,
        proposal_id: Option<String>,
    ) -> Result<String> {
        if amount <= Decimal::ZERO {
            return Err(GovernanceError::InvalidParameter(
                "Amount must be positive".to_string(),
            ));
        }

        let current_balance = self.get_balance(asset);
        if amount > current_balance {
            return Err(GovernanceError::TreasuryOperationFailed(
                "Insufficient balance".to_string(),
            ));
        }

        // Create transaction
        let mut transaction = Transaction::new(
            TransactionType::Withdrawal,
            amount,
            None,
            Some(to),
            purpose,
            proposal_id.clone(),
        );

        // Require approval if no proposal_id or large amount
        transaction.approved = proposal_id.is_some();

        let tx_id = transaction.id.clone();

        // Update balance only if approved
        if transaction.approved {
            self.balance
                .entry(asset.to_string())
                .and_modify(|b| *b -= amount);
        }

        // Record transaction
        self.transactions.insert(tx_id.clone(), transaction);

        Ok(tx_id)
    }

    /// Allocate budget to a category
    pub fn allocate_budget(&self, category: String, amount: Decimal, proposal_id: String) -> Result<()> {
        if amount <= Decimal::ZERO {
            return Err(GovernanceError::InvalidParameter(
                "Amount must be positive".to_string(),
            ));
        }

        // Check if sufficient balance
        let balance = self.get_balance("USD");
        if amount > balance {
            return Err(GovernanceError::TreasuryOperationFailed(
                "Insufficient treasury balance".to_string(),
            ));
        }

        // Create or update budget allocation
        self.budgets
            .entry(category.clone())
            .and_modify(|b| b.increase_allocation(amount))
            .or_insert_with(|| BudgetAllocation::new(category, amount));

        // Record transaction
        let transaction = Transaction::new(
            TransactionType::Allocation,
            amount,
            Some("Treasury".to_string()),
            None,
            "Budget allocation".to_string(),
            Some(proposal_id),
        );
        self.transactions.insert(transaction.id.clone(), transaction);

        Ok(())
    }

    /// Spend from budget allocation
    pub fn spend_from_budget(&self, category: &str, amount: Decimal, purpose: String) -> Result<String> {
        let mut budget = self.budgets
            .get_mut(category)
            .ok_or_else(|| {
                GovernanceError::TreasuryOperationFailed("Budget category not found".to_string())
            })?;

        budget.spend(amount)?;

        // Record transaction
        let transaction = Transaction::new(
            TransactionType::Withdrawal,
            amount,
            Some(format!("Budget:{}", category)),
            None,
            purpose,
            None,
        );
        let tx_id = transaction.id.clone();
        self.transactions.insert(tx_id.clone(), transaction);

        Ok(tx_id)
    }

    /// Transfer to emergency fund
    pub fn transfer_to_emergency_fund(&self, amount: Decimal) -> Result<()> {
        let balance = self.get_balance("USD");
        if amount > balance {
            return Err(GovernanceError::TreasuryOperationFailed(
                "Insufficient balance for emergency fund transfer".to_string(),
            ));
        }

        self.balance
            .entry("USD".to_string())
            .and_modify(|b| *b -= amount);

        // In a real system, this would be stored separately
        // For now, we'll just track it
        let transaction = Transaction::new(
            TransactionType::Emergency,
            amount,
            Some("Treasury".to_string()),
            Some("EmergencyFund".to_string()),
            "Emergency fund allocation".to_string(),
            None,
        );
        self.transactions.insert(transaction.id.clone(), transaction);

        Ok(())
    }

    /// Access emergency fund (requires governance approval)
    pub fn access_emergency_fund(&self, amount: Decimal, proposal_id: String, purpose: String) -> Result<String> {
        if amount > self.emergency_fund {
            return Err(GovernanceError::TreasuryOperationFailed(
                "Insufficient emergency fund".to_string(),
            ));
        }

        let transaction = Transaction::new(
            TransactionType::Emergency,
            amount,
            Some("EmergencyFund".to_string()),
            None,
            purpose,
            Some(proposal_id),
        );
        let tx_id = transaction.id.clone();
        self.transactions.insert(tx_id.clone(), transaction);

        Ok(tx_id)
    }

    /// Get transaction by ID
    pub fn get_transaction(&self, tx_id: &str) -> Result<Transaction> {
        self.transactions
            .get(tx_id)
            .map(|r| r.value().clone())
            .ok_or_else(|| {
                GovernanceError::TreasuryOperationFailed(format!("Transaction {} not found", tx_id))
            })
    }

    /// Get all transactions
    pub fn get_all_transactions(&self) -> Vec<Transaction> {
        self.transactions.iter().map(|r| r.value().clone()).collect()
    }

    /// Get budget allocation
    pub fn get_budget(&self, category: &str) -> Result<BudgetAllocation> {
        self.budgets
            .get(category)
            .map(|r| r.value().clone())
            .ok_or_else(|| {
                GovernanceError::TreasuryOperationFailed(format!("Budget {} not found", category))
            })
    }

    /// Get all budget allocations
    pub fn get_all_budgets(&self) -> Vec<BudgetAllocation> {
        self.budgets.iter().map(|r| r.value().clone()).collect()
    }

    /// Get treasury statistics
    pub fn get_statistics(&self) -> TreasuryStatistics {
        let total_balance: Decimal = self.balance.iter().map(|r| *r.value()).sum();
        let total_allocated: Decimal = self.budgets.iter().map(|r| r.value().allocated).sum();
        let total_spent: Decimal = self.budgets.iter().map(|r| r.value().spent).sum();

        TreasuryStatistics {
            total_balance,
            total_allocated,
            total_spent,
            emergency_fund: self.emergency_fund,
            transaction_count: self.transactions.len(),
            budget_categories: self.budgets.len(),
        }
    }
}

/// Treasury statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TreasuryStatistics {
    pub total_balance: Decimal,
    pub total_allocated: Decimal,
    pub total_spent: Decimal,
    pub emergency_fund: Decimal,
    pub transaction_count: usize,
    pub budget_categories: usize,
}

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

    #[test]
    fn test_treasury_creation() {
        let treasury = TreasuryManager::new(Decimal::from(1000000), Decimal::from(100000));
        assert_eq!(treasury.get_balance("USD"), Decimal::from(1000000));
    }

    #[test]
    fn test_deposit() {
        let treasury = TreasuryManager::new(Decimal::from(1000000), Decimal::from(100000));
        let tx_id = treasury.deposit(
            "USD",
            Decimal::from(50000),
            "Investor".to_string(),
            "Investment".to_string(),
        ).unwrap();

        assert!(!tx_id.is_empty());
        assert_eq!(treasury.get_balance("USD"), Decimal::from(1050000));
    }

    #[test]
    fn test_withdraw() {
        let treasury = TreasuryManager::new(Decimal::from(1000000), Decimal::from(100000));
        let tx_id = treasury.withdraw(
            "USD",
            Decimal::from(50000),
            "Recipient".to_string(),
            "Payment".to_string(),
            Some("proposal123".to_string()),
        ).unwrap();

        assert!(!tx_id.is_empty());
        assert_eq!(treasury.get_balance("USD"), Decimal::from(950000));
    }

    #[test]
    fn test_budget_allocation() {
        let treasury = TreasuryManager::new(Decimal::from(1000000), Decimal::from(100000));
        assert!(treasury.allocate_budget(
            "Development".to_string(),
            Decimal::from(200000),
            "proposal456".to_string(),
        ).is_ok());

        let budget = treasury.get_budget("Development").unwrap();
        assert_eq!(budget.allocated, Decimal::from(200000));
        assert_eq!(budget.remaining, Decimal::from(200000));
    }

    #[test]
    fn test_spend_from_budget() {
        let treasury = TreasuryManager::new(Decimal::from(1000000), Decimal::from(100000));
        treasury.allocate_budget(
            "Development".to_string(),
            Decimal::from(200000),
            "proposal456".to_string(),
        ).unwrap();

        assert!(treasury.spend_from_budget(
            "Development",
            Decimal::from(50000),
            "Contractor payment".to_string(),
        ).is_ok());

        let budget = treasury.get_budget("Development").unwrap();
        assert_eq!(budget.spent, Decimal::from(50000));
        assert_eq!(budget.remaining, Decimal::from(150000));
    }

    #[test]
    fn test_insufficient_balance() {
        let treasury = TreasuryManager::new(Decimal::from(1000), Decimal::from(100));
        assert!(treasury.withdraw(
            "USD",
            Decimal::from(2000),
            "Recipient".to_string(),
            "Payment".to_string(),
            Some("proposal789".to_string()),
        ).is_err());
    }
}