pot-o-extensions 0.10.0

DeFi, staking, and external-chain extensions for the PoT-O validator
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
use std::collections::HashMap;
use std::sync::Arc;

use pot_o_core::TokenType;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tokio::sync::RwLock;
use tracing;

use crate::tx::{CoinbaseTransaction, TransferTransaction};
use hexchain_p2p::block::HexBlock;

pub const TRIBE_HARD_CAP: u64 = 1_000_000_000_000_000;
pub const TRIBE_BLOCK_REWARD_INITIAL: u64 = 1_000_000_000; // 1,000 TRIBE per block
pub const TRIBE_HALVING_INTERVAL: u64 = 210_000; // ~73 days at 30s blocks
pub const TRIBE_PROOF_REWARD: u64 = 10_000_000; // 10 TRIBE per proof
pub const COINBASE_MATURITY_DEPTH: u64 = 100;

pub fn block_reward_at_height(height: u64) -> u64 {
    let halvings = height / TRIBE_HALVING_INTERVAL;
    if halvings >= 64 {
        return 0;
    }
    TRIBE_BLOCK_REWARD_INITIAL >> halvings
}

#[derive(Debug, Clone)]
pub struct CoinbaseEntry {
    pub amount: u64,
    pub mature_at_height: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LedgerEntry {
    pub address: String,
    pub token: TokenType,
    pub balance: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LedgerSnapshot {
    pub entries: Vec<LedgerEntry>,
    pub tx_history: Vec<TxReceipt>,
    pub nonces: Vec<(String, u64)>,
    pub block_height: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TxReceipt {
    pub tx_hash: String,
    pub from: String,
    pub to: String,
    pub token: TokenType,
    pub amount: u64,
    pub fee: u64,
    pub block_height: u64,
    pub timestamp: u64,
}

pub struct Ledger {
    balances: HashMap<(String, TokenType), u64>,
    tx_history: Vec<TxReceipt>,
    block_height: u64,
    protocol_fee_address: String,
    modified: bool,
    nonces: HashMap<String, u64>,
    coinbase_maturity: HashMap<String, Vec<CoinbaseEntry>>,
    total_supply_map: HashMap<TokenType, u64>,
    last_interaction: HashMap<(String, TokenType), u64>, // block height of last interaction
    minter_allowlist: HashMap<TokenType, Vec<String>>,   // authorized minters per token
}

impl Ledger {
    pub fn new(protocol_fee_address: String) -> Self {
        Self {
            balances: HashMap::new(),
            tx_history: Vec::new(),
            block_height: 0,
            protocol_fee_address,
            modified: false,
            nonces: HashMap::new(),
            coinbase_maturity: HashMap::new(),
            total_supply_map: HashMap::new(),
            last_interaction: HashMap::new(),
            minter_allowlist: HashMap::new(),
        }
    }

    pub fn balance_of(&self, address: &str, token: &TokenType) -> u64 {
        self.balances
            .get(&(address.to_string(), token.clone()))
            .copied()
            .unwrap_or(0)
    }

    pub fn balances(&self) -> &std::collections::HashMap<(String, TokenType), u64> {
        &self.balances
    }

    pub fn issue(&mut self, to: &str, token: &TokenType, amount: u64) {
        let key = (to.to_string(), token.clone());
        let entry = self.balances.entry(key).or_insert(0);
        *entry = entry.saturating_add(amount);

        // Update total supply map
        let total = self.total_supply_map.entry(token.clone()).or_insert(0);
        *total = total.saturating_add(amount);

        self.block_height = self.block_height.saturating_add(1);
        self.modified = true;

        let mut hasher = Sha256::new();
        hasher.update(b"MINTER");
        hasher.update(to.as_bytes());
        hasher.update(amount.to_le_bytes());
        hasher.update(self.block_height.to_le_bytes());
        let tx_hash = hex::encode(hasher.finalize());

        let receipt = TxReceipt {
            tx_hash,
            from: "MINTER".to_string(),
            to: to.to_string(),
            token: token.clone(),
            amount,
            fee: 0,
            block_height: self.block_height,
            timestamp: chrono::Utc::now().timestamp() as u64,
        };
        self.tx_history.push(receipt);
    }

    /// Try to issue tokens, respecting supply caps from token_config
    pub fn try_issue(&mut self, to: &str, token: &TokenType, amount: u64) -> Result<(), String> {
        use pot_o_core::token_config::token_config;

        // Get token configuration
        let config_set = token_config();

        // Check if token has a supply cap configured
        if let Some(config) = config_set.get(token) {
            // Calculate current total supply
            let current_supply = self.total_supply_of(token);

            // Check if adding this amount would exceed the cap
            if current_supply.saturating_add(amount) > config.supply_cap {
                return Err(format!(
                    "Supply cap exceeded for {:?}: current={}, requested={}, cap={}",
                    token, current_supply, amount, config.supply_cap
                ));
            }
        }

        // If all checks pass, issue the tokens
        let key = (to.to_string(), token.clone());
        let entry = self.balances.entry(key).or_insert(0);
        *entry = entry.saturating_add(amount);

        // Update total supply map
        let total = self.total_supply_map.entry(token.clone()).or_insert(0);
        *total = total.saturating_add(amount);

        self.block_height = self.block_height.saturating_add(1);
        self.modified = true;

        let mut hasher = Sha256::new();
        hasher.update(b"MINTER");
        hasher.update(to.as_bytes());
        hasher.update(amount.to_le_bytes());
        hasher.update(self.block_height.to_le_bytes());
        let tx_hash = hex::encode(hasher.finalize());

        let receipt = TxReceipt {
            tx_hash,
            from: "MINTER".to_string(),
            to: to.to_string(),
            token: token.clone(),
            amount,
            fee: 0,
            block_height: self.block_height,
            timestamp: chrono::Utc::now().timestamp() as u64,
        };
        self.tx_history.push(receipt);

        Ok(())
    }

    pub fn transfer(
        &mut self,
        from: &str,
        to: &str,
        token: &TokenType,
        amount: u64,
        fee: u64,
    ) -> Result<TxReceipt, String> {
        use pot_o_core::token_config::token_config;

        if amount == 0 {
            return Err("Transfer amount must be positive".into());
        }

        // Calculate burn amount based on token configuration
        let config_set = token_config();
        let burn = if let Some(config) = config_set.get(token) {
            config.calculate_burn(amount)
        } else {
            0
        };

        let total = amount.checked_add(fee).ok_or("Overflow in amount + fee")?;
        let from_key = (from.to_string(), token.clone());
        let from_bal = self.balances.get(&from_key).copied().unwrap_or(0);

        // Sender must have: amount + fee + burn
        let total_needed = total.checked_add(burn).ok_or("Overflow in total + burn")?;
        if from_bal < total_needed {
            return Err(format!(
                "Insufficient balance: have {}, need {} (amount {} + fee {} + burn {})",
                from_bal, total_needed, amount, fee, burn
            ));
        }

        self.balances
            .insert(from_key.clone(), from_bal - total_needed);

        let to_key = (to.to_string(), token.clone());
        let to_bal = self.balances.entry(to_key).or_insert(0);

        if fee > 0 && !self.protocol_fee_address.is_empty() && self.protocol_fee_address == to {
            *to_bal = to_bal.saturating_add(amount + fee);
        } else {
            *to_bal = to_bal.saturating_add(amount);
            if fee > 0 && !self.protocol_fee_address.is_empty() {
                let fee_key = (self.protocol_fee_address.clone(), token.clone());
                let fee_bal = self.balances.entry(fee_key).or_insert(0);
                *fee_bal = fee_bal.saturating_add(fee);
            }
        }

        // Update total supply to reflect burn
        if burn > 0 {
            let total = self.total_supply_map.entry(token.clone()).or_insert(0);
            *total = total.saturating_sub(burn);
        }

        self.block_height = self.block_height.saturating_add(1);
        self.modified = true;

        let mut hasher = Sha256::new();
        hasher.update(from.as_bytes());
        hasher.update(to.as_bytes());
        hasher.update(amount.to_le_bytes());
        hasher.update(fee.to_le_bytes());
        hasher.update(self.block_height.to_le_bytes());
        let tx_hash = hex::encode(hasher.finalize());

        let receipt = TxReceipt {
            tx_hash,
            from: from.to_string(),
            to: to.to_string(),
            token: token.clone(),
            amount,
            fee,
            block_height: self.block_height,
            timestamp: chrono::Utc::now().timestamp() as u64,
        };
        self.tx_history.push(receipt.clone());

        Ok(receipt)
    }

    pub fn tx_history(&self) -> &[TxReceipt] {
        &self.tx_history
    }

    pub fn tx_history_for(&self, address: &str) -> Vec<TxReceipt> {
        self.tx_history
            .iter()
            .filter(|t| t.from == address || t.to == address)
            .cloned()
            .collect()
    }

    pub fn block_height(&self) -> u64 {
        self.block_height
    }

    pub fn nonces(&self) -> &HashMap<String, u64> {
        &self.nonces
    }

    pub fn is_modified(&self) -> bool {
        self.modified
    }

    pub fn clear_modified(&mut self) {
        self.modified = false;
    }

    pub fn protocol_fee_address(&self) -> &str {
        &self.protocol_fee_address
    }

    pub fn total_supply(&self, token: &TokenType) -> u64 {
        self.balances
            .iter()
            .filter(|((_, t), _)| t == token)
            .map(|(_, bal)| *bal)
            .sum()
    }

    pub fn current_nonce(&self, address: &str) -> u64 {
        self.nonces.get(address).copied().unwrap_or(0)
    }

    pub fn total_supply_of(&self, token: &TokenType) -> u64 {
        self.total_supply_map.get(token).copied().unwrap_or(0)
    }

    /// Record an interaction (transfer/issue) for an address-token pair
    pub fn update_interaction(&mut self, address: &str, token: &TokenType) {
        let key = (address.to_string(), token.clone());
        self.last_interaction.insert(key, self.block_height);
    }

    /// Get the block height of the last interaction for an address-token pair
    pub fn last_interaction(&self, address: &str, token: &TokenType) -> Option<u64> {
        self.last_interaction
            .get(&(address.to_string(), token.clone()))
            .copied()
    }

    /// Apply age-based decay to a balance based on blocks elapsed
    /// Returns the decayed amount using exponential decay formula
    pub fn apply_decay(&self, address: &str, token: &TokenType, blocks_elapsed: u64) -> u64 {
        use pot_o_core::token_config::token_config;

        let balance = self.balance_of(address, token);

        // Get token configuration
        let config_set = token_config();

        if let Some(config) = config_set.get(token) {
            config.apply_decay(balance, blocks_elapsed)
        } else {
            // No decay configured for this token
            balance
        }
    }

    /// Calculate AUM block reward with halving schedule
    /// Halving occurs every 1M blocks
    pub fn aum_block_reward(&self, height: u64) -> u64 {
        const AUM_INITIAL_REWARD: u64 = 1_000_000_000; // 1 billion
        const AUM_HALVING_INTERVAL: u64 = 1_000_000; // 1 million blocks

        let halvings = height / AUM_HALVING_INTERVAL;
        if halvings >= 64 {
            return 0; // After 64 halvings, reward becomes 0
        }
        AUM_INITIAL_REWARD >> halvings
    }

    /// Add an address to the minter allowlist for a specific token
    pub fn add_minter(&mut self, token: &TokenType, minter: &str) {
        self.minter_allowlist
            .entry(token.clone())
            .or_default()
            .push(minter.to_string());
    }

    /// Check if an address is an authorized minter for a token
    pub fn is_authorized_minter(&self, token: &TokenType, minter: &str) -> bool {
        self.minter_allowlist
            .get(token)
            .map(|minters| minters.contains(&minter.to_string()))
            .unwrap_or(false)
    }

    /// Try to issue tokens with minter authorization check
    pub fn try_issue_with_minter(
        &mut self,
        minter: &str,
        token: &TokenType,
        to: &str,
        amount: u64,
    ) -> Result<(), String> {
        // Check minter authorization
        if !self.is_authorized_minter(token, minter) {
            return Err(format!(
                "Minter {} is not authorized to mint {:?}",
                minter, token
            ));
        }

        // Use try_issue to respect supply caps
        self.try_issue(to, token, amount)
    }

    pub fn is_coinbase_mature(&self, _address: &str, height: u64, current_height: u64) -> bool {
        current_height >= height + COINBASE_MATURITY_DEPTH
    }

    pub fn apply_transfer(
        &mut self,
        tx: &TransferTransaction,
        miner: &str,
    ) -> Result<TxReceipt, String> {
        if tx.amount == 0 {
            return Err("Transfer amount must be positive".into());
        }
        let total = tx
            .amount
            .checked_add(tx.fee)
            .ok_or("Overflow in amount + fee")?;
        let from_key = (tx.from.clone(), tx.token.clone());
        let from_bal = self.balances.get(&from_key).copied().unwrap_or(0);
        if from_bal < total {
            return Err(format!(
                "Insufficient balance: have {}, need {} (amount {} + fee {})",
                from_bal, total, tx.amount, tx.fee
            ));
        }

        self.balances.insert(from_key, from_bal - total);

        let to_key = (tx.to.clone(), tx.token.clone());
        let to_bal = self.balances.entry(to_key).or_insert(0);
        *to_bal = to_bal.saturating_add(tx.amount);

        if tx.fee > 0 {
            let miner_key = (miner.to_string(), tx.token.clone());
            let miner_bal = self.balances.entry(miner_key).or_insert(0);
            *miner_bal = miner_bal.saturating_add(tx.fee);
        }

        self.nonces
            .entry(tx.from.clone())
            .and_modify(|n| *n += 1)
            .or_insert(1);

        self.modified = true;

        let receipt = TxReceipt {
            tx_hash: hex::encode(tx.tx_hash),
            from: tx.from.clone(),
            to: tx.to.clone(),
            token: tx.token.clone(),
            amount: tx.amount,
            fee: tx.fee,
            block_height: self.block_height,
            timestamp: tx.timestamp,
        };
        self.tx_history.push(receipt.clone());

        Ok(receipt)
    }

    pub fn rollback_transfer(
        &mut self,
        tx: &TransferTransaction,
        miner: &str,
    ) -> Result<(), String> {
        let to_key = (tx.to.clone(), tx.token.clone());
        let to_bal = self.balances.get(&to_key).copied().unwrap_or(0);
        if to_bal < tx.amount {
            return Err(format!(
                "Insufficient balance to rollback recipient: have {}, need {}",
                to_bal, tx.amount
            ));
        }
        self.balances.insert(to_key, to_bal - tx.amount);

        if tx.fee > 0 {
            let miner_key = (miner.to_string(), tx.token.clone());
            let miner_bal = self.balances.get(&miner_key).copied().unwrap_or(0);
            if miner_bal < tx.fee {
                return Err(format!(
                    "Insufficient balance to rollback miner fee: have {}, need {}",
                    miner_bal, tx.fee
                ));
            }
            self.balances.insert(miner_key, miner_bal - tx.fee);
        }

        let from_key = (tx.from.clone(), tx.token.clone());
        let from_bal = self.balances.entry(from_key).or_insert(0);
        *from_bal = from_bal.saturating_add(tx.amount + tx.fee);

        self.nonces.entry(tx.from.clone()).and_modify(|n| {
            if *n > 0 {
                *n -= 1
            }
        });

        self.modified = true;
        Ok(())
    }

    pub fn apply_coinbase(&mut self, cb: &CoinbaseTransaction) -> Result<(), String> {
        let total_proof_rewards: u64 = cb.proof_rewards.iter().map(|pr| pr.reward_amount).sum();
        let total_mint = cb.block_reward + total_proof_rewards;

        let current_supply = self.total_supply_of(&TokenType::TribeChain);
        if current_supply
            .checked_add(total_mint)
            .is_none_or(|s| s > TRIBE_HARD_CAP)
        {
            return Err("Supply cap exceeded".into());
        }

        let miner_key = (cb.miner_address.clone(), TokenType::TribeChain);
        let miner_bal = self.balances.entry(miner_key).or_insert(0);
        *miner_bal = miner_bal.saturating_add(cb.block_reward);

        for pr in &cb.proof_rewards {
            let pr_key = (pr.miner_pubkey.clone(), TokenType::TribeChain);
            let pr_bal = self.balances.entry(pr_key).or_insert(0);
            *pr_bal = pr_bal.saturating_add(pr.reward_amount);
        }

        self.coinbase_maturity
            .entry(cb.miner_address.clone())
            .or_default()
            .push(CoinbaseEntry {
                amount: cb.block_reward,
                mature_at_height: cb.height + COINBASE_MATURITY_DEPTH,
            });

        *self
            .total_supply_map
            .entry(TokenType::TribeChain)
            .or_insert(0) += total_mint;

        self.modified = true;
        Ok(())
    }

    pub fn rollback_coinbase(&mut self, cb: &CoinbaseTransaction) -> Result<(), String> {
        let miner_key = (cb.miner_address.clone(), TokenType::TribeChain);
        let miner_bal = self.balances.entry(miner_key).or_insert(0);
        *miner_bal = miner_bal.saturating_sub(cb.block_reward);

        for pr in &cb.proof_rewards {
            let pr_key = (pr.miner_pubkey.clone(), TokenType::TribeChain);
            let pr_bal = self.balances.entry(pr_key).or_insert(0);
            *pr_bal = pr_bal.saturating_sub(pr.reward_amount);
        }

        if let Some(entries) = self.coinbase_maturity.get_mut(&cb.miner_address) {
            entries.pop();
        }

        let total_proof_rewards: u64 = cb.proof_rewards.iter().map(|pr| pr.reward_amount).sum();
        *self
            .total_supply_map
            .entry(TokenType::TribeChain)
            .or_insert(0) -= cb.block_reward + total_proof_rewards;

        self.modified = true;
        Ok(())
    }

    pub fn apply_block(&mut self, block: &HexBlock) -> Result<Vec<TxReceipt>, String> {
        let txs = block
            .transactions
            .as_ref()
            .ok_or_else(|| "Block has no transactions".to_string())?;

        if txs.is_empty() {
            return Err("Block has no transactions".into());
        }

        self.block_height = block.height;

        let cb: CoinbaseTransaction = serde_json::from_value(txs[0].clone())
            .map_err(|e| format!("Failed to deserialize coinbase: {}", e))?;
        let miner = cb.miner_address.clone();

        self.apply_coinbase(&cb)?;

        let mut receipts = Vec::new();
        for tx_val in txs[1..].iter() {
            let tx: TransferTransaction = serde_json::from_value(tx_val.clone())
                .map_err(|e| format!("Failed to deserialize transfer: {}", e))?;
            let receipt = self.apply_transfer(&tx, &miner)?;
            receipts.push(receipt);
        }

        Ok(receipts)
    }

    pub fn rollback_block(&mut self, block: &HexBlock) -> Result<(), String> {
        let txs = block
            .transactions
            .as_ref()
            .ok_or_else(|| "Block has no transactions".to_string())?;

        if txs.is_empty() {
            return Err("Block has no transactions".into());
        }

        let cb: CoinbaseTransaction = serde_json::from_value(txs[0].clone())
            .map_err(|e| format!("Failed to deserialize coinbase: {}", e))?;
        let miner = cb.miner_address.clone();

        for tx_val in txs[1..].iter().rev() {
            let tx: TransferTransaction = serde_json::from_value(tx_val.clone())
                .map_err(|e| format!("Failed to deserialize transfer: {}", e))?;
            self.rollback_transfer(&tx, &miner)?;
        }

        self.rollback_coinbase(&cb)?;

        Ok(())
    }

    pub fn compute_state_root(&self) -> [u8; 32] {
        use crate::state_root::compute_state_root;
        use std::collections::BTreeMap;

        let mut balances = BTreeMap::new();
        for ((addr, token), balance) in &self.balances {
            let key = format!("{:?}:{:?}", addr, token);
            balances.insert(key, *balance);
        }

        let mut nonces = BTreeMap::new();
        for (addr, nonce) in &self.nonces {
            nonces.insert(addr.clone(), *nonce);
        }

        compute_state_root(&balances, &nonces)
    }

    pub fn mint_tokens(&mut self, to: &str, token: &TokenType, amount: u64) -> Result<(), String> {
        let current = self.total_supply_of(token);
        if current
            .checked_add(amount)
            .is_none_or(|s| *token == TokenType::TribeChain && s > TRIBE_HARD_CAP)
        {
            return Err("Supply cap exceeded".into());
        }
        self.issue(to, token, amount);
        Ok(())
    }
}

pub fn load_ledger(path: &str, protocol_fee_address: &str) -> Ledger {
    let content = std::fs::read_to_string(path).ok();
    let mut ledger = Ledger::new(protocol_fee_address.to_string());
    if let Some(ref s) = content {
        // Try full snapshot first, fall back to old entry list for backward compat
        if let Ok(snapshot) = serde_json::from_str::<LedgerSnapshot>(s) {
            for entry in snapshot.entries {
                let key = (entry.address, entry.token);
                ledger.balances.insert(key, entry.balance);
            }
            ledger.tx_history = snapshot.tx_history;
            for (addr, nonce) in snapshot.nonces {
                ledger.nonces.insert(addr, nonce);
            }
            ledger.block_height = snapshot.block_height;
        } else if let Ok(entries) = serde_json::from_str::<Vec<LedgerEntry>>(s) {
            for entry in entries {
                let key = (entry.address, entry.token);
                ledger.balances.insert(key, entry.balance);
            }
        }
    }
    ledger.modified = false;
    ledger
}

pub fn spawn_persist_ledger(ledger: Arc<RwLock<Ledger>>, path: String) {
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
        loop {
            interval.tick().await;
            let snapshot: LedgerSnapshot = {
                let l = ledger.read().await;
                if !l.is_modified() {
                    continue;
                }
                let entries: Vec<LedgerEntry> = l
                    .balances
                    .iter()
                    .map(|((addr, token), bal)| LedgerEntry {
                        address: addr.clone(),
                        token: token.clone(),
                        balance: *bal,
                    })
                    .collect();
                let nonces: Vec<(String, u64)> =
                    l.nonces.iter().map(|(k, v)| (k.clone(), *v)).collect();
                LedgerSnapshot {
                    entries,
                    tx_history: l.tx_history.clone(),
                    nonces,
                    block_height: l.block_height,
                }
            };
            let path_clone = path.clone();
            let json = serde_json::to_string_pretty(&snapshot).unwrap();
            let write_result =
                tokio::task::spawn_blocking(move || std::fs::write(&path_clone, json)).await;
            match write_result {
                Ok(Ok(())) => {
                    let mut l = ledger.write().await;
                    l.clear_modified();
                }
                Ok(Err(e)) => {
                    tracing::warn!(error = %e, "Failed to persist ledger");
                }
                Err(e) => {
                    tracing::warn!(error = %e, "spawn_blocking join error for ledger persist");
                }
            }
        }
    });
}

pub const DEFAULT_LEDGER_PATH: &str = "ledger.json";

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

    #[test]
    fn test_issue_and_balance() {
        let mut ledger = Ledger::new("protocol".into());
        ledger.issue("alice", &TokenType::TribeChain, 1000);
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 1000);
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 0);
        assert_eq!(ledger.block_height(), 1);
    }

    #[test]
    fn test_transfer_basic() {
        let mut ledger = Ledger::new("protocol".into());
        ledger.issue("alice", &TokenType::TribeChain, 1000);
        let receipt = ledger
            .transfer("alice", "bob", &TokenType::TribeChain, 300, 10)
            .unwrap();
        assert_eq!(receipt.amount, 300);
        assert_eq!(receipt.fee, 10);
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 690);
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 300);
        assert_eq!(ledger.balance_of("protocol", &TokenType::TribeChain), 10);
    }

    #[test]
    fn test_transfer_insufficient_balance() {
        let mut ledger = Ledger::new("protocol".into());
        ledger.issue("alice", &TokenType::TribeChain, 100);
        let err = ledger
            .transfer("alice", "bob", &TokenType::TribeChain, 200, 0)
            .unwrap_err();
        assert!(err.contains("Insufficient balance"));
    }

    #[test]
    fn test_transfer_zero_amount() {
        let mut ledger = Ledger::new("protocol".into());
        let err = ledger
            .transfer("alice", "bob", &TokenType::TribeChain, 0, 0)
            .unwrap_err();
        assert!(err.contains("positive"));
    }

    #[test]
    fn test_tx_history() {
        let mut ledger = Ledger::new("protocol".into());
        ledger.issue("alice", &TokenType::TribeChain, 1000);
        ledger
            .transfer("alice", "bob", &TokenType::TribeChain, 200, 5)
            .unwrap();
        assert_eq!(ledger.tx_history().len(), 2);
        let alice_txs = ledger.tx_history_for("alice");
        assert_eq!(alice_txs.len(), 2);
        let bob_txs = ledger.tx_history_for("bob");
        assert_eq!(bob_txs.len(), 1);
        let charlie_txs = ledger.tx_history_for("charlie");
        assert_eq!(charlie_txs.len(), 0);
    }

    #[test]
    fn test_load_ledger_persistence_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_ledger.json");
        let path_str = path.to_str().unwrap().to_string();

        {
            let mut ledger = Ledger::new("fee_addr".into());
            ledger.issue("alice", &TokenType::PTtC, 500);
            let entries: Vec<LedgerEntry> = ledger
                .balances
                .iter()
                .map(|((addr, token), bal)| LedgerEntry {
                    address: addr.clone(),
                    token: token.clone(),
                    balance: *bal,
                })
                .collect();
            std::fs::write(&path, serde_json::to_string_pretty(&entries).unwrap()).unwrap();
        }

        let loaded = load_ledger(&path_str, "fee_addr");
        assert_eq!(loaded.balance_of("alice", &TokenType::PTtC), 500);
        assert_eq!(loaded.balance_of("bob", &TokenType::PTtC), 0);
        assert!(!loaded.is_modified());
    }

    #[test]
    fn test_no_fee_when_protocol_is_recipient() {
        let mut ledger = Ledger::new("bob".into());
        ledger.issue("alice", &TokenType::TribeChain, 1000);
        ledger
            .transfer("alice", "bob", &TokenType::TribeChain, 300, 10)
            .unwrap();
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 690);
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 310);
    }

    #[test]
    fn test_multiple_token_types_independent() {
        let mut ledger = Ledger::new("protocol".into());
        ledger.issue("alice", &TokenType::TribeChain, 100);
        ledger.issue("alice", &TokenType::PTtC, 200);
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 100);
        assert_eq!(ledger.balance_of("alice", &TokenType::PTtC), 200);
        ledger
            .transfer("alice", "bob", &TokenType::TribeChain, 50, 0)
            .unwrap();
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 50);
        assert_eq!(ledger.balance_of("alice", &TokenType::PTtC), 200);
    }

    #[test]
    fn test_block_reward_halving() {
        assert_eq!(block_reward_at_height(0), TRIBE_BLOCK_REWARD_INITIAL);
        assert_eq!(
            block_reward_at_height(TRIBE_HALVING_INTERVAL),
            TRIBE_BLOCK_REWARD_INITIAL / 2
        );
        assert_eq!(block_reward_at_height(TRIBE_HALVING_INTERVAL * 64), 0);
    }

    #[test]
    fn test_apply_transfer_normal() {
        let mut ledger = Ledger::new("protocol".to_string());
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, 1000)
            .unwrap();
        let tx = TransferTransaction {
            tx_hash: [0u8; 32],
            nonce: 0,
            from: "alice".to_string(),
            to: "bob".to_string(),
            token: TokenType::TribeChain,
            amount: 100,
            fee: 1,
            signature: vec![],
            timestamp: 0,
        };
        let result = ledger.apply_transfer(&tx, "miner").unwrap();
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 899);
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 100);
        assert_eq!(ledger.balance_of("miner", &TokenType::TribeChain), 1);
        assert_eq!(ledger.current_nonce("alice"), 1);
    }

    #[test]
    fn test_apply_transfer_insufficient() {
        let mut ledger = Ledger::new("protocol".to_string());
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, 50)
            .unwrap();
        let tx = TransferTransaction {
            tx_hash: [0u8; 32],
            nonce: 0,
            from: "alice".to_string(),
            to: "bob".to_string(),
            token: TokenType::TribeChain,
            amount: 100,
            fee: 1,
            signature: vec![],
            timestamp: 0,
        };
        assert!(ledger.apply_transfer(&tx, "miner").is_err());
    }

    #[test]
    fn test_supply_cap_enforcement() {
        let mut ledger = Ledger::new("protocol".to_string());
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, TRIBE_HARD_CAP)
            .unwrap();
        let result = ledger.mint_tokens("bob", &TokenType::TribeChain, 1);
        assert!(result.is_err(), "Should reject minting beyond hard cap");
    }

    #[test]
    fn test_coinbase_maturity() {
        let mut ledger = Ledger::new("protocol".to_string());
        assert!(!ledger.is_coinbase_mature("miner", 0, 50));
        assert!(ledger.is_coinbase_mature("miner", 0, 100));
        assert!(ledger.is_coinbase_mature("miner", 0, 200));
    }

    #[test]
    fn test_rollback_transfer() {
        let mut ledger = Ledger::new("protocol".to_string());
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, 1000)
            .unwrap();
        let alice_before = ledger.balance_of("alice", &TokenType::TribeChain);
        let tx = TransferTransaction {
            tx_hash: [0u8; 32],
            nonce: 0,
            from: "alice".to_string(),
            to: "bob".to_string(),
            token: TokenType::TribeChain,
            amount: 200,
            fee: 1,
            signature: vec![],
            timestamp: 0,
        };
        ledger.apply_transfer(&tx, "miner").unwrap();
        ledger.rollback_transfer(&tx, "miner").unwrap();
        assert_eq!(
            ledger.balance_of("alice", &TokenType::TribeChain),
            alice_before
        );
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 0);
        assert_eq!(ledger.balance_of("miner", &TokenType::TribeChain), 0);
    }

    #[test]
    fn test_current_nonce() {
        let mut ledger = Ledger::new("protocol".to_string());
        assert_eq!(ledger.current_nonce("alice"), 0);
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, 1000)
            .unwrap();
        let tx = TransferTransaction {
            tx_hash: [0u8; 32],
            nonce: 0,
            from: "alice".to_string(),
            to: "bob".to_string(),
            token: TokenType::TribeChain,
            amount: 100,
            fee: 0,
            signature: vec![],
            timestamp: 0,
        };
        ledger.apply_transfer(&tx, "miner").unwrap();
        assert_eq!(ledger.current_nonce("alice"), 1);
    }

    #[test]
    fn test_total_supply_of() {
        let mut ledger = Ledger::new("protocol".to_string());
        assert_eq!(ledger.total_supply_of(&TokenType::TribeChain), 0);
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, 500)
            .unwrap();
        assert_eq!(ledger.total_supply_of(&TokenType::TribeChain), 500);
    }

    #[test]
    fn test_apply_coinbase_supply_cap() {
        let mut ledger = Ledger::new("protocol".to_string());
        let cb = CoinbaseTransaction {
            tx_hash: [0u8; 32],
            height: 1,
            miner_address: "miner".to_string(),
            block_reward: TRIBE_HARD_CAP,
            proof_rewards: vec![],
            signature: vec![],
        };
        ledger.apply_coinbase(&cb).unwrap();
        let cb2 = CoinbaseTransaction {
            tx_hash: [1u8; 32],
            height: 2,
            miner_address: "miner".to_string(),
            block_reward: 1,
            proof_rewards: vec![],
            signature: vec![],
        };
        assert!(ledger.apply_coinbase(&cb2).is_err());
    }

    #[test]
    fn test_apply_rollback_block() {
        let mut ledger = Ledger::new("protocol".to_string());
        ledger
            .mint_tokens("alice", &TokenType::TribeChain, 1000)
            .unwrap();

        let tx1 = serde_json::to_value(TransferTransaction {
            tx_hash: [1u8; 32],
            nonce: 0,
            from: "alice".to_string(),
            to: "bob".to_string(),
            token: TokenType::TribeChain,
            amount: 100,
            fee: 5,
            signature: vec![],
            timestamp: 0,
        })
        .unwrap();

        let cb = serde_json::to_value(CoinbaseTransaction {
            tx_hash: [0u8; 32],
            height: 1,
            miner_address: "miner".to_string(),
            block_reward: 100,
            proof_rewards: vec![ProofRewardEntry {
                miner_pubkey: "prover1".to_string(),
                reward_amount: 10,
                proof_hash: "proof1".to_string(),
            }],
            signature: vec![],
        })
        .unwrap();

        let block = HexBlock {
            parent_hash: [0u8; 32],
            height: 1,
            tx_merkle_root: [0u8; 32],
            transactions: Some(vec![cb, tx1]),
            miner_address: Some("miner".to_string()),
            timestamp: 100,
            nonce: 0,
            coord: hexchain_p2p::lattice_geometry::HCPCoord { q: 0, r: 0, s: 0 },
            neighbor_hashes: [hexchain_p2p::types::NEIGHBOR_SLOT_EMPTY; 12],
            tensor: hexchain_p2p::types::TensorMeta {
                expected_capacity: 1000,
                actual_capacity: 1000,
                compression_num: 1,
                compression_den: 1,
            },
        };

        let receipts = ledger.apply_block(&block).unwrap();
        assert_eq!(receipts.len(), 1);
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 895);
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 100);
        assert!(ledger.balance_of("miner", &TokenType::TribeChain) >= 100);
        assert_eq!(ledger.block_height(), 1);

        ledger.rollback_block(&block).unwrap();
        assert_eq!(ledger.balance_of("alice", &TokenType::TribeChain), 1000);
        assert_eq!(ledger.balance_of("bob", &TokenType::TribeChain), 0);
    }

    #[test]
    fn test_try_issue_respects_pttc_cap() {
        let mut ledger = Ledger::new("protocol".to_string());
        let cap = 21_000_000_000_000u64;
        ledger.try_issue("alice", &TokenType::PTtC, cap).unwrap();
        assert!(ledger.try_issue("bob", &TokenType::PTtC, 1).is_err());
    }
}